<?php



namespace App\Http\Controllers;

use App\Models\Vendor;

use App\Models\Quotation;

use Auth, DB, Mail, Validator, File, DataTables, Exception;

use Illuminate\Http\Request;

use App\Models\Department;

use App\Models\Branch;

use Illuminate\Support\Str;

use Maatwebsite\Excel\Facades\Excel;

use Spatie\Permission\Models\Permission;

use Spatie\Permission\Models\Role;

use Illuminate\Support\Facades\Hash;





class VendorController extends Controller{

    /** construct */

        public function __construct(){

            $this->middleware('permission:vendor-create', ['only' => ['create']]);

            $this->middleware('permission:vendor-edit', ['only' => ['edit']]);

            $this->middleware('permission:vendor-view', ['only' => ['view']]);

            $this->middleware('permission:vendor-delete', ['only' => ['delete']]);

            $this->middleware('permission:vendor-profile', ['only' => ['profile']]);





        }

    /** construct */



    /** index */

        public function index(Request $request){

            if($request->ajax()){

                $data = Vendor::where('status','!=','deleted')->get();

                //DB::enableQueryLog(); 
                //$quotation_data = Quotation::where('status','=','active')->get();
                //dd(DB::getQueryLog());

                

                return Datatables::of($data)

                        ->addIndexColumn()

                        ->addColumn('action', function($data){

                            $return = '<div class="btn-group">';



                            if(auth()->user()->can('vendor-view')){

                                $return .= '<a href="'.route('vendor.view', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">

                                                <i class="fa fa-eye"></i>

                                            </a> &nbsp;';

                           }   

                            

                             if(auth()->user()->can('vendor-edit')){

                                $return .= '<a href="'.route('vendor.edit', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">

                                                <i class="fa fa-pencil"></i>

                                            </a> &nbsp;';

                            }   



                             if (auth()->user()->can('vendor-delete')) {

                                $return .= '<a href="javascript:;" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">

                                                    <i class="fa fa-bars"></i>

                                                </a> &nbsp;

                                                <ul class="dropdown-menu">

                                                <li><a class="dropdown-item" href="' . route('vendor.code', ['id' => base64_encode($data->id)]) . '" data-status="active">Vendor Code</a></li>

                                                    <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="active" data-id="' . base64_encode($data->id) . '">Active</a></li>

                                                    <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="inactive" data-id="' . base64_encode($data->id) . '">Inactive</a></li>

                                                    <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="deleted" data-id="' . base64_encode($data->id) . '">Deleted</a></li>

                                                </ul>';

                           }

                           $return .= '<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModal">View Quotation</button>

                        <div id="myModal" class="modal fade" role="dialog" > 
                          <div class="modal-dialog modal-lg" >
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                                </div>
                                <div class="modal-body">
                                    <table class="form-table">
                                      <thead>
                                        <tr>
                                          <th scope="col">#</th>
                                          <th scope="col">Quotation Name</th>
                                          <th scope="col">Description</th>
                                          <th scope="col">Quotation Attachment</th>
                                          <th scope="col">Quotation Amount</th>
                                          <th scope="col">Remark</th>
                                          <th scope="col">Status</th>
                                           <th scope="col">Approval Status</th>
                                        </tr>
                                      </thead>
                                      <tbody>';

                                      $quotation_data = Quotation::where(['status'=>'active','vendor_id'=>$data->created_by])->get();
                                      
                                      $qi=1;
                                      foreach($quotation_data as $Qdata){


                                        if($Qdata->approval_status == "Approved"){
                                            $approval_stratus='<button class="btn btn-success">Approved</button>';
                                        }

                                        else if($Qdata->approval_status == "Rejected") {
                                            $approval_stratus='<button class="btn btn-danger">Rejected</button>';
                                        }

                                        else if($Qdata->approval_status == "" || $Qdata->approval_status == NULL) {

                                            $approval_stratus='<button class="btn btn-success" id="approved" name="approved" onclick="approve_func('.$Qdata->id.')" >Approve</button>
                                                    <button class="btn btn-danger" id="rejected" name="rejected" onclick="reject_func('.$Qdata->id.')" >Reject</button>';

                                        }
                                        
                                        $return .='<tr>
                                          <td>'.$qi++.'</td>
                                          <td>'.$Qdata->name_of_quotation.'</td>
                                          <td>'.$Qdata->name_of_description.'</td>
                                          <td><a href="'.url("uploads/kyc/".$Qdata->attechment).'" target="_balnk">
                                            <i class="fas fa-file-pdf" style="font-size:24px;color:red"></i></td>
                                            <td>'.$Qdata->quotation_amount.'</td>
                                          <td>'.$Qdata->remark.'</td>
                                          <td><span class="badge badge-pill badge-success">'.$Qdata->status.'</span></td>
                                          <td>'.$approval_stratus.'</td>
                                          </tr>';
                                      }
                                        
                                        
                                       $return .='</tbody>
                                    </table>
                                </div>
                            </div>

                          </div>
                        </div>';

                            $return .= '</div>';



                            return $return;

                        })



                      ->editColumn('department', function ($data) {

                        $department = Department::where(['id' => $data->department_id])->first();

                        if(!empty($department)){

                            return $department['name'];

                        }else{

                            return '';

                        }

                        

                        

                    })

                     ->addColumn('branch', function ($data) {

        $branchIds = explode(',', $data->branch);

        $branchNames = Branch::whereIn('id', $branchIds)->pluck('name')->implode(', ');

        return $branchNames;

    })

                        ->editColumn('status', function ($data) {

                            if ($data->status == 'active') {

                                return '<span class="badge badge-pill badge-success">Active</span>';

                            } else if ($data->status == 'inactive') {

                                return '<span class="badge badge-pill badge-warning">Inactive</span>';

                            } else if ($data->status == 'deleted') {

                                return '<span class="badge badge-pill badge-danger">Deleted</span>';

                            }

                        })



                        ->rawColumns(['action' ,'percentage' ,'status','branch'])

                        ->make(true);

            }

            return view('vendor.index');

        }

    /** index */



    /** create */

        public function create(Request $request){

            return view('vendor.create');

        }

    /** create */



    /** insert */

        

    public function withoutinsert(Request $request)

    {


        if ($request->ajax()) {

            return true;

        }

    

        $password = 'Abcd@123?';

    

        if ($request->password != '' && $request->password != NULL) {

            $password = $request->password;

        }

    

        $user = auth()->user();

    if(!empty($request->branch)){

                $request->branch = implode(',', $request->branch);

            }else{

                $request->branch = '';

            }

        // Fetch the department name based on the department_id from the users table

        $departmentName = Department::where('id', $user->department_id)->value('name');

        $branchName=Branch::where('id', $user->branch)->value('name');

    

        $vendor = Vendor::create([
            
            'user_id' => auth()->user()->id,

            'vendor_code' => $request->vendor_code,

            'tan_number' => $request->tan_number,

            'tally_heading' => $request->tally_heading,

            'description_goods' => $request->description_goods,

            'location' => $request->location,

            'department_id' => $user->department_id,

            'branch'=>$user->branch,

            'branch_name' => $branchName,

            'department_name' => $departmentName, // Set department_name to the department name

            'authorised_person' => $request->authorised_person,

            'person_contactno' => $request->person_contactno,

            'vendor_list' => $request->vendor_list,

            'contact_person' => $request->contact_person,
            
            'contact_per_number' => $request->contact_per_number,

            'contact_number' => $user->contact_number,

            'email' => $user->email,

            'password' => bcrypt($password),

            'name_of_company' => $user->name_of_company,

            'activity' => $request->activity,

            'msme_act' => $request->msme_act,

            'udhyom' => $request->udhyom,

            'date' => $request->date,

            'registraion_type' => $request->registraion_type,

            'gross_annual_sales' => $request->gross_annual_sales,

            'legel_structure' => $request->legel_structure,

            'business_comoddity' => $request->business_comoddity,

            'goods_supplied' => $request->goods_supplied,

            'gst_no' => $request->gst_no,

            'pan_no' => $user->pan_no,

            'address' => $request->address,

            'bank_name' => $request->bank_name,

            'account_no' => $request->account_no,

            'ifsc_code' => $request->ifsc_code,

            'acc_holder_name' => $request->acc_holder_name,

            'account_type' => $request->account_type,

           

            'district' => $request->district,

            'state' => $request->state,

            'payment_mode' => $request->payment_mode,

            'working_year' => $request->working_year,

            'remark_1' => $request->remark_1,

            'remark_2' => $request->remark_2,

            'status' => 'active',

            'created_at' => now(),

            'updated_at' => now(),

            'created_by' => $user->id,

            'updated_by' => $user->id

        ]);

    

        if ($vendor) {

            return redirect()->route('vendor.without')->with(['success' => 'Vendor Registered successfully']);

        } else {

            return redirect()->back()->with(['error' => 'Failed to Register Vendor'])->withInput();

        }

    }

    



    /** view */

        public function view(Request $request){

            $id = base64_decode($request->id);

            $data = Vendor::select('id','name_of_company',

            'vendor_code',

            'tally_heading',

            'description_goods',

            'location',

            'msme_act',

            'activity',

            'udhyom',

            'date',

            'registraion_type',

            'gross_annual_sales',

            'legel_structure',

            'business_comoddity',

            'goods_supplied',

            'department_id',

            'authorised_person',

            'person_contactno',

            'vendor_list',

            'contact_person',
            
            'contact_per_number',

            'contact_number',

            'email',

            'password',

            'gst_no',

            'pan_no',

            'branch',

            'address',

            'bank_name',

            'account_no',

            'ifsc_code',

            'acc_holder_name',

            'account_type',

            'branch',

            'district',

            'state',

            'payment_mode',

            'working_year',

            'remark_1',

            'remark_2'

            )->where(['id' => $id])->first();

                            $branch = Branch::where(['status' => 'active'])->get();



            $department = Vendor::select('vendor.department_id', 'department.name as d_name', 'department.id as d_id')

            ->leftJoin('department','department.id','=','vendor.department_id')

            ->where('vendor.status', 'active')->get();

            return view('vendor.view')->with(['data'=>$data, 'department' => $department,'branch'=>$branch]);

        }

    /** view */



    

    

    

    

    /** edit */

        public function edit(Request $request){

            $id = base64_decode($request->id);

            $department = Department::all();

            $data = Vendor::select('id','name_of_company',

            'vendor_code',

            'tally_heading',

            'description_goods',

            'location',

            'msme_act',

            'activity',

            'udhyom',

            'date',

            'registraion_type',

            'gross_annual_sales',

            'legel_structure',

            'business_comoddity',

            'goods_supplied',

            'department_id',

            'authorised_person',

            'person_contactno',

            'vendor_list',

            'contact_person',
            
            'contact_per_number',

            'contact_number',

            'email',

            'branch',

            'password',

            'gst_no',

            'pan_no',

            'address',

            'bank_name',

            'account_no',

            'ifsc_code',

            'acc_holder_name',

            'account_type',

            'branch',

            'district',

            'state',

            'payment_mode',

            'working_year',

            'remark_1',

            'remark_2'

            )->where(['id' => $id])->first();

            $branch = Branch::where(['status' => 'active'])->get();



            return view('vendor.edit')->with(['data'=>$data, 'department'=>$department, 'branch'=>$branch]);

        }

    /** edit */



    /** update */

        public function update(Request $request){

            if($request->ajax()){ return true; }

            $id = $request->id;

            

            $crud = [

              'vendor_code' => $request->vendor_code,

              'tan_number' => $request->tan_number,

              'tally_heading' => $request->tally_heading,

              'description_goods' => $request->description_goods,

              'location' => $request->location,

              'udhyom'=>$request->udhyom,

'date'=>$request->date,

'registraion_type'=>$request->registraion_type,

'gross_annual_sales'=>$request->gross_annual_sales,

'legel_structure'=>$request->legel_structure,

'business_comoddity'=>$request->business_comoddity,

'goods_supplied'=>$request->goods_supplied,

             

              'authorised_person' => $request->authorised_person,

              'person_contactno'=> $request->person_contactno,

              'vendor_list' => $request->vendor_list,

              'contact_person' => $request->contact_person,

              'contact_per_number' => $request->contact_per_number,

              'gst_no' => $request->gst_no,

              

              'address' => $request->address,

              'bank_name' => $request->bank_name,

              'account_no' => $request->account_no,

              'ifsc_code' => $request->ifsc_code,

              'acc_holder_name' => $request->acc_holder_name,

              'account_type' => $request->account_type,

              'branch' => $request->branch,

              'district' => $request->district,

              'state' => $request->state,

              'payment_mode' => $request->payment_mode,

              'working_year' => $request->working_year,

              'remark_1' => $request->remark_1,

              'remark_2' => $request->remark_2,

              'status' => 'active',

              

            ];



            if($request->password != '' && $request->password != NULL)

            $data['password'] = bcrypt($request->password);

            DB::enableQueryLog();

            $update = Vendor::where(['id' => $id])->update($crud);

            // dd(DB::getQueryLog());

            if ($update){

                return redirect()->route('vendor')->with(['success' => 'Record updated successfully']);

            }else{

                return redirect()->back()->with(['error'=>'Faild to update Record!'])->withInput();

            }

        }

    /** update */



    /** change-status */

        public function change_status(Request $request){

            if (!$request->ajax()) { exit('No direct script access allowed'); }

            $id = base64_decode($request->id);

            

            $data = Vendor::where(['id' => $id])->first();



            if (!empty($data)) {

                $update = Vendor::where(['id' => $id])->update(['status' => $request->status, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth('sanctum')->user()->id]);

                if ($update) {

                    return response()->json(['code' => 200]);

                } else {

                    return response()->json(['code' => 201]);

                }

            } else {

                return response()->json(['code' => 201]);

            }

           

        }





       public function vendorcode(Request $request)

{

    $id = base64_decode($request->id);

    $vendor = Vendor::find($id);



    if (!$vendor) {

        return redirect()->back()->with(['error' => 'Vendor not found.'])->withInput();

    }



    // Get the count of vendors for this user

    $count = Vendor::where('user_id', $vendor->user_id)->count();



    // Check if the vendor_code is NULL

    if ($vendor->vendor_code === null) {

        // Get the highest vendor code number for this user
        //DB::enableQueryLog(); 
        $highestVendorCode = Vendor::where('user_id', $vendor->user_id)

                                   ->whereNotNull('vendor_code')

                                   ->orderBy('vendor_code', 'desc')

                                   ->first();

       //dd(DB::getQueryLog());

        // Determine the next vendor code number

        if ($highestVendorCode) {

            $lastNumber = intval(substr($highestVendorCode->vendor_code, strpos($highestVendorCode->vendor_code, '/') + 1));

            $nextNumber = $lastNumber + 1;

        } else {

            $nextNumber = 1;

        }



        // Format the next vendor code

        $nextVendorCode = 'SIBAPL/' . str_pad($nextNumber, 3, '0', STR_PAD_LEFT);



        // Update the vendor code

        $vendor->vendor_code = $nextVendorCode;

        $vendor->save();



        if ($vendor) {

            return redirect()->route('vendor')->with(['success' => 'Vendor Code updated successfully']);

        } else {

            return redirect()->back()->with(['error' => 'Failed to update Record!'])->withInput();

        }

    }



    // If vendor_code is not null, check for uniqueness

    if (Vendor::where('vendor_code', $vendor->vendor_code)->exists()) {

        return redirect()->back()->with(['error' => 'Vendor Code already exists. Please choose a different code.'])->withInput();

    }



    return redirect()->route('vendor')->with(['success' => 'Vendor Code updated successfully']);

}

        



        



    /** change-status */



    /** Import */

        // public function import(Request $request){

           

        //     if(Excel::import(new ImportCarmodel, $request->file('file')->store('file'))){

        //         return redirect()->route('car_model')->with('sucess' ,'File Imported Sucessfully');

        //     }else{

        //         return redirect()->route('car_model')->with('error' ,'Faild To Import File!');

        //     }

        // }

    /** Import */

    

    /** Export */

        // public function export(Request $request){

        //     if(isset($request->slug) && $request->slug != null){

        //         $slug = $request->slug;

        //     }else{

        //         $slug = 'all';

        //     }



        //     $name = 'Carmodels_'.Date('YmdHis').'.xlsx';



        //     try {

        //         return Excel::download(new ExportCarmodel($slug), $name);

        //     }catch(\Exception $e){

        //         return redirect()->back()->with('error' ,$e->getMessage());

        //     }

        // }

    /** Export */





    public function without(Request $request)

    {



        return view('vendor.without');

    }

    

    



    public function profileview(Request $request){

       

            

    $user_id = Auth::user()->id;

 $vendor_data = Vendor::select('id','name_of_company',

            'vendor_code',

            'tally_heading',

            'description_goods',

            'location',

            'msme_act',

            'activity',

            'udhyom',

            'date',

            'registraion_type',

            'gross_annual_sales',

            'legel_structure',

            'business_comoddity',

            'goods_supplied',

            'department_id',

            'authorised_person',

            'person_contactno',

            'vendor_list',

            'contact_person',

            'contact_number',

            'email',

            'password',

            'gst_no',

            'branch',

            'pan_no',

            'address',

            'bank_name',

            'account_no',

            'ifsc_code',

            'acc_holder_name',

            'account_type',

            'branch',

            'district',

            'state',

            'payment_mode',

            'working_year',

            'remark_1',

            'remark_2'

            )->where('created_by', $user_id)->get();

                $branch = Branch::where(['status' => 'active'])->get();



            $department = Vendor::select('vendor.department_id', 'department.name as d_name', 'department.id as d_id')

            ->leftJoin('department','department.id','=','vendor.department_id')

            ->where('vendor.status', 'active')->get();

          

    return view('vendor.profile')->with(['vendor_data'=>$vendor_data, 'department' => $department,'branch' => $branch]);

    }

    

    

    public function vendorquotation(Request $request)

    {

       

            

    $user_id = Auth::user()->id;

    $quotation_data = Vendor::select('id','name_of_company')->where('created_by', $user_id)->get();

    return view('vendor.quotation')->with(['quotation_data'=>$quotation_data]);

    }

    

    

    

    

     public function quatindex(Request $request)

    {

      

    $user_id = Auth::user()->id;

     //$quotation_data = Quotation::select('id','name_of_quotation','name_of_description','attechment', 'remark')->where('vendor_id', $user_id)->where('created_by', $user_id)->get();

          if($request->ajax()){

                
                $data =  Quotation::select('*')->orderBy('id' , 'desc')->where('vendor_id', $user_id)->get();
               
                //   $data = DepartmentLogin::select('department_login.*')->where(['status' => 'active'])->orderBy('id' , 'desc')->get();

                

                    return Datatables::of($data)

                        ->addIndexColumn()

                        ->addColumn('action', function($data){

                            $return = '<div class="btn-group">';



                             if(auth()->user()->can('vendor-quotatioview')){

                                $return .= '<a href="'.route('vendor.qview', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">

                                                <i class="fa fa-eye"></i>

                                            </a> &nbsp;';

                             }   

                            

                        if(auth()->user()->can('vendor-quotatioedit')){

                                $return .= '<a href="'.route('vendor.qview', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">

                                                <i class="fa fa-pencil"></i>

                                            </a> &nbsp;';

                             }   



                            if (auth()->user()->can('vendor-quotatiodelete')) {

                                $return .= '<a href="javascript:;" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">

                                                    <i class="fa fa-bars"></i>

                                                </a> &nbsp;

                                                <ul class="dropdown-menu">

                                                    <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="active" data-id="' . base64_encode($data->id) . '">Active</a></li>

                                                    <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="inactive" data-id="' . base64_encode($data->id) . '">Inactive</a></li>

                                                    <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="deleted" data-id="' . base64_encode($data->id) . '">Delete</a></li>

                                                </ul>';

                            }



                            $return .= '</div>';



                            return $return;

                        })



                    

                        ->editColumn('status', function ($data) {

                            if ($data->status == 'active') {

                                return '<span class="badge badge-pill badge-success">Active</span>';

                            } else if ($data->status == 'inactive') {

                                return '<span class="badge badge-pill badge-warning">Inactive</span>';

                            } else if ($data->status == 'deleted') {

                                return '<span class="badge badge-pill badge-danger">Deleted</span>';

                            }else{

                                return '-';

                            }

                        })



                        ->rawColumns([ 'action' ,'status'])

                        ->make(true);

                }

                

    return view('vendor.quatindex');

    } 

    

  public function quationstore(Request $request)

{

    if ($request->ajax()) {

        return true;

    }



    $user = auth()->user();



    // Handle file upload

    $attachments = '';

    if ($request->hasFile('attechment')) {

        $attachmentFiles = $request->file('attechment');

        $attachmentNames = [];

        

        foreach ($attachmentFiles as $file) {

            // Validate the file extension

            $extension = $file->getClientOriginalExtension();

            $allowedExtensions = ['jpg', 'png', 'jpeg', 'pdf'];

            

            if (in_array($extension, $allowedExtensions)) {

                // Generate a unique filename

                $filename = 'attachment_' . time() . '_' . $file->getClientOriginalName();

                // Move the file to the uploads directory

                $file->move(public_path('/uploads/kyc/'), $filename);

                // Collect the filenames

                $attachmentNames[] = $filename;

            } else {

                return redirect()->back()->with(['error' => 'Invalid file type'])->withInput();

            }

        }



        // Convert the array of filenames to a string

        $attachments = implode(',', $attachmentNames);

    }



    // Create the Quotation

    $quotation = Quotation::create([

        'vendor_id' => $user->id, // Use vendor's ID here

        'name_of_quotation' => $request->name_of_quotation,

        'name_of_description' => $request->name_of_description,

        'attechment' => $attachments,

        'quotation_amount' => $request->quotation_amount,

        'remark' => $request->remark,

        'status' => 'active',

        'created_at' => now(),

        'updated_at' => now()

        

    ]);



    if ($quotation) {

        return redirect()->route('vendor.quotation')->with(['success' => 'Quotation added successfully']);

    } else {

        return redirect()->back()->with(['error' => 'Failed to add Quotation'])->withInput();

    }

}



    

     public function qview(Request $request){  

            $id = base64_decode($request->id);

            

            $quotation_data = Quotation::select('*')->where(['id' => $id])->first();

            

            return view('vendor.qview')->with(['data' => $quotation_data]);

        }


        public function update_approval_status(Request $request){

            if (!$request->ajax()) { exit('No direct script access allowed'); }

            $id = $request->id;

            $data = Quotation::where(['id' => $id])->first();

            if (!empty($data)) {
                
                $update = Quotation::where(['id' => $id])->update(['approval_status' => $request->approval_status, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth('sanctum')->user()->id]);
                
                 if ($update) {

                    return response()->json(['code' => 200]);

                } else {

                    return response()->json(['code' => 201]);

                }

            } else {

                return response()->json(['code' => 201]);

            }
        }


        public function update_rejected_status(Request $request){

            if (!$request->ajax()) { exit('No direct script access allowed'); }

            $id = $request->id;

            $data = Quotation::where(['id' => $id])->first();

            if (!empty($data)) {
                
                $update = Quotation::where(['id' => $id])->update(['approval_status' => $request->rejected_status, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth('sanctum')->user()->id]);
                
                 if ($update) {

                    return response()->json(['code' => 200]);

                } else {

                    return response()->json(['code' => 201]);

                }

            } else {

                return response()->json(['code' => 201]);

            }
        }













    

}

   



