<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\TemplateMaster;
use App\Models\ObfInsurance;
use App\Models\RenewalInsurance;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use DB, Validator ,DataTables;


class PolicyListController extends Controller{
    /** construct */
        public function __construct(){
            $this->middleware('permission:policy_list-create', ['only' => ['create']]);
            $this->middleware('permission:policy_list-edit', ['only' => ['edit']]);
            $this->middleware('permission:policy_list-view', ['only' => ['view']]);
            $this->middleware('permission:policy_list-delete', ['only' => ['delete']]);
        }
    /** construct */
    /** index */
        public function index(Request $request){
            
            $id = $request->id;

            
            if($request->ajax()){
                $obf_id = $request->id;

                 $data = ObfInsurance::select('obf_insurance.*','obf.customer_name as o_customer_name','obf.product_id as o_product_id','car_model.name as car_name','car_varient.name as v_name','orders.order_id')
                    ->leftJoin('obf','obf.id','=','obf_insurance.obf_id')
                    ->leftJoin('products','products.id','=','obf.product_id')
                    ->leftJoin('car_model','car_model.id','=','products.car_model')
                    ->leftJoin('car_varient','car_varient.id','=','products.veriant')
                    ->leftJoin('orders','orders.obf_id','=','obf.id')
                    ->where('obf_insurance.status', '1')
                    ->where('obf_insurance.is_delete', 0);

                    if($obf_id != '')
                        $data = $data->where('obf_insurance.obf_id', $obf_id);

                    $data = $data->orderBy('id' , 'desc')->get();


                

                return Datatables::of($data)
                        ->addIndexColumn()
                        ->addColumn('o_customer_name', function($data) {
                            $return = '';
                                $return .= $data->o_customer_name."<br>".$data->order_id;
                            return $return;
                        })
                        
                        ->addColumn('policy_number', function($data) {
                            $return = '';
                                $return .= $data->policy_number."<br>".$data->car_name. ' - '.$data->v_name;
                            return $return;
                        })
                        
                        ->addColumn('action', function($data){
                            $return = '<div class="btn-group">';
                            
                            if(auth()->user()->can('policy_list-edit')){
                                $return .= '<a href="'.route('policy_list.edit', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                                <i class="fa fa-pencil"></i>
                                            </a> &nbsp;';

                            $return .= '<a onclick="change_status(this);" data-id="' . base64_encode($data->id) . '" class="btn btn-default btn-xs">
                                            <i class="fa fa-trash-can"></i>
                                        </a> &nbsp;';
                            }   
                            $return .= '</div>';

                            return $return;
                        })

                        
                        ->editColumn('date_of_insurance', function ($data) {
                            if($data->date_of_insurance != null)
                                return date("d/m/Y",strtotime($data->date_of_insurance));
                            else
                                return '-';
                        })

                        ->editColumn('last_time_of_insurance', function ($data) {
                            if($data->last_time_of_insurance != null)
                                return date("d/m/Y",strtotime($data->last_time_of_insurance));
                            else
                                return '-';
                        })

                        ->rawColumns(['o_customer_name','policy_number', 'action' ,'date_of_insurance','last_time_of_insurance'])
                        ->make(true);
            }
            return view('policy_list.index')->with(['id' => $id]);
        }
    /** index */
    
   /** Edit */
        public function edit(Request $request){
             $id = base64_decode($request->id);

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

            return view('policy_list.edit')->with(['data' => $data]);
        }
    /** Edit */

    /** update */
        public function insert(Request $request)
        {   

             /*  die('ss*----');
               die('ss');*/
            if($request->ajax()) { return true; }

            $insurance = [
                'obf_id' => $request->obf_id,
                'ncb' => $request->ncb ?? null,
                'date_of_insurance' => $request->ri_date_of_insurance,
                'time_of_insurance' => $request->ri_time_of_insurance,
                'last_time_of_insurance' => $request->ri_last_time_of_insurance,
                'company_name' => $request->ri_company_name,
                'ncb_amount' => $request->ri_ncb_amount,
                'policy_number' => $request->ri_policy_number,
                'status' => $request->status, 
                'created_at' => date('Y-m-d H:i:s'),                
            ];

            if(!empty($request->file('documents'))){
                $documents = '';
                $documents_name_arr = [];

                $documents_arr = $request->file('documents');
                foreach($documents_arr as $key => $file_value){
                    $filenameWithExtension_three = $file_value->getClientOriginalName();
                    $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                    $extension_three = $file_value->getClientOriginalExtension();
                    $filenameToStore_three_new = "documents_".time()."_".$filename_three.'.'.$extension_three;

                    array_push($documents_name_arr, $filenameToStore_three_new);                        
                    $folder_to_upload_sn = public_path().'/uploads/kyc/';
                    
                    if(!\File::exists($folder_to_upload_sn))
                        \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                     $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
                }
                if(!empty($documents_name_arr)){
                    $documents = implode(",",$documents_name_arr);
                }
                $insurance['documents'] = $documents;
            }
            $last_id = ObfInsurance::insertGetId($insurance);
            $update = DB::table('obf_insurance')->where(['id' => $request->id])->update($insurance);

            if ($update) {

                return redirect()->route('policy_list/',['id'=>$request->obf_id])->with(['success' => 'Policy update successfully']);
            } else {
                return redirect()->back()->with(['error'=>'Faild to Policy Renew!'])->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 = TemplateMaster::where(['id' => $id])->first();

            if(!empty($data)){
                $update = TemplateMaster::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]);
            }
        }
    /** change-status */
}
