<?php

namespace App\Http\Controllers\Administrator;


use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\ClientRelationshipModel;
use App\ProvinceModel;
use App\CommuneModel;
use App\VillageModel;
use App\DistrictModel;
use DB;
use DataTables;
use Image;
use Gate;
use Illuminate\Support\Facades\Crypt;
class ClientRelationshipController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
     function __construct()
     {
          $this->middleware('permission:Relationship-List');
          $this->middleware('permission:Relationship-Create', ['only' => ['create','store']]);
          $this->middleware('permission:Relationship-Edit', ['only' => ['edit','update']]);
          $this->middleware('permission:Relationship-Delete', ['only' => ['destroy']]);
          $this->middleware('permission:Deposit-Add-Edit-Client-Relationship',['only'=>['post_sale_client_relationship']]);
     }
    
    public function index()
    {
        return view('administrator.client-relationship.index');
    }
    public function datatable_get_client_relationship(Request $request)
    {
        $client_name = $request->client_name;
        $client_phone = $request->client_phone;
        $clients = ClientRelationshipModel::with(['get_province','get_district','get_commune','get_village'])
                    ->when(request('client_name'),function($query) use ($client_name){
                        $query->where("nso007_client_relationship.clientship_fullname","LIKE","%".$client_name."%");
                    })
                    ->when(request('client_phone'),function($query) use ($client_phone){
                        $query->where("nso007_client_relationship.clientship_phone1",$client_phone);
                    })
                    ->get();
        return Datatables::of($clients)
        ->addIndexColumn()
        ->editColumn('address', function($clients) {
            return  (!empty($clients->house)?("ផ្ទះលេខ".$clients->house.","):"").(!empty($clients->street)?("ផ្លូវ".$clients->street.","):"").'ភូមិ'. $clients->villages->village_km.',​ ឃុំ/សំងាត់'.$clients->communes->commune_km.', ស្រុក/ខ័ណ្ឌ'. $clients->districts->district_km.' ,ខេត្ត/ក្រុង'.$clients->provices->province_km;
        })
        ->editColumn('action', function ($clients) {
            $edits='';
            if(Gate::check('Relationship-Edit')) {
                $edits = '<a href="' . Route("clients-relationship.edit", Crypt::encrypt($clients->id)) . '" class="button_success btn-xs fa fa-edit"></a>';
            }
            $delete='';
            if(Gate::check('Relationship-Delete')) {
                if($clients->clientship_loanid==0){
                    $delete = '<a href="' . Route("client-relationship.delete", Crypt::encrypt($clients->id)) . '" class="button_danger btn-xs fa fa-trash"></a>';
                }
            }
            return $edits.$delete;
        })
        ->editColumn('clientship_phone1',function($clients){
            $phone = $clients->clientship_phone1;
            if(!empty($clients->clientship_phone2))
                $phone.=" ,".$clients->clientship_phone2;
            // $phone = str_replace(' ', '', $phone);
            // $phone = chunk_split($phone, 3, ' ');
            return $phone;
        })
        ->make(true);
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $provinces = ProvinceModel::select(
            DB::raw('CONCAT(province_id," ",province_en," ",province_km) AS province_mixed'),'province_id')
            ->pluck('province_mixed','province_id')
            ->prepend('Please Select', '');

        return view('administrator.client-relationship.create', compact('provinces'));
    }
    public function store(Request $request)
    {
        $this->validate($request, [
            'clientship_fullname' => 'required',
            'clientship_dob'      => 'required',
            // 'clientship_phone1'   => 'required',
            // 'clientship_cardid'   => 'required',
//            'p_province'          => 'required',
//            'p_district'          => 'required',
//            'p_commune'           => 'required',
//            'p_village'           => 'required',

        ]);
        
        $client_re = new ClientRelationshipModel;
        $client_re->clientship_fullname     = $request->clientship_fullname;
        $client_re->clientship_dob          = $request->clientship_dob;
        $client_re->clientship_gender       = $request->clientship_gender;

        if(isset($request->clientship_phone1)){
            $phone="";$phone_insert="";
            preg_match_all('!\d+!', $request->clientship_phone1, $phone);
            foreach($phone[0] as $key=>$value)
            {
                if($key==0) $phone_insert.=$value;
                else $phone_insert.="-".$value;
            }

            $client_re->clientship_phone1       =  $phone_insert;
        }
        if(isset($request->clientship_phone2)){
            $phone="";$phone_insert="";
            preg_match_all('!\d+!', $request->clientship_phone2, $phone);
            foreach($phone[0] as $key=>$value)
            {
                if($key==0) $phone_insert.=$value;
                else $phone_insert.="-".$value;
            }
            
            $client_re->clientship_phone2       =  $phone_insert;
        }

        $client_re->clientship_national     = $request->clientship_national;
        if($request->personal_type==1){
            $client_re->clientship_cardid       = $request->clientship_cardid;
            $client_re->clientship_datecard     = isset($request->clientship_datecard)?date("Y-m-d",strtotime($request->clientship_datecard)):null;
            $client_re->clientship_cardvalid    = isset($request->clientship_cardvalid)?date("Y-m-d",strtotime($request->clientship_cardvalid)):null;
        }
        else{
            $client_re->passport_number = $request->passport_number;
            $client_re->passport_date_issue = isset($request->passport_date_issue)?date("Y-m-d",strtotime($request->passport_date_issue)):null;
            $client_re->passport_expiry_date = isset($request->passport_expiry_date)?date("Y-m-d",strtotime($request->passport_expiry_date)):null;
            $client_re->country_of_passport = $request->country_of_passport;
            $client_re->visa_type = $request->visa_type;
            $client_re->intended_date_of_entry = isset($request->intended_date_of_entry)?date("Y-m-d",strtotime($request->intended_date_of_entry)):null;
            $client_re->port_of_entry = $request->port_of_entry;
        }

        $client_re->personal_type = $request->personal_type;
        
        $client_re->p_village               = $request->p_village;
        $client_re->p_commune               = $request->p_commune;
        $client_re->p_district              = $request->p_district;
        $client_re->p_province              = $request->p_province;
        $client_re->house              = $request->house;
        $client_re->street              = $request->street;
        $client_re->save();

        \LogActivity::addToLog('Clients Relationship created successfully!');
        return redirect()->route('clients-relationship.index');
    }
    public function edit($id)
    {
        $decrypt_id = Crypt::decrypt($id);
        $client_re = ClientRelationshipModel::find($decrypt_id);
        $provinces = ProvinceModel::select(
            DB::raw('CONCAT(province_id," ",province_en," ",province_km) AS province_mixed'),'province_id')
            ->pluck('province_mixed','province_id')
            ->prepend('Please Select', '');
        $districts = DistrictModel::select(
            DB::raw('CONCAT(district_id," ",district_en," ",district_km) AS district_mixed'),'district_id')
            ->pluck('district_mixed','district_id')
            ->prepend('Please Select', '');

        $communes = CommuneModel::select(
            DB::raw('CONCAT(commune_id," ",commune_en," ",commune_km) AS commune_mixed'),'commune_id')
            ->pluck('commune_mixed','commune_id')
            ->prepend('Please Select', '');
        $villages = VillageModel::select(
            DB::raw('CONCAT(village_id," ",village_en," ",village_km) AS village_mixed'),'village_id')
            ->pluck('village_mixed','village_id')
            ->prepend('Please Select', '');

        return view('administrator.client-relationship.edit',compact('client_re','provinces','districts','communes','villages'));
    }
    public function client_prefixaddress(Request $request){
        $p_village = $request->p_village;
        $p_commune = $request->p_commune;
        $p_district = $request->p_district;
        $p_province = $request->p_province;

        $province = ProvinceModel::select('province_km')
       ->where('province_id',$p_province)
       ->get();
       $district = DistrictModel::select('district_km')
       ->where('district_id',$p_district)
       ->get();
       $commune = CommuneModel::select('commune_km')
       ->where('commune_id',$p_commune)
       ->get();
       $village = VillageModel::select('village_km')
       ->where('village_id',$p_village)
       ->get();

       $data = array(
            'province' => $province,
            'district' => $district,
            'commune' => $commune,
            'village' => $village
        );
    
        echo json_encode($data);

    }
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $client_re =ClientRelationshipModel::find($id);
       
        $this->validate($request, [
            'clientship_fullname' => 'required',
            'clientship_dob'      => 'required',
            // 'clientship_phone1'   => 'required',
            // 'clientship_cardid'   => 'required',
//            'p_province'          => 'required',
//            'p_district'          => 'required',
//            'p_commune'           => 'required',
//            'p_village'           => 'required',
        
        ]);
        $client_re->clientship_fullname     = $request->clientship_fullname;
        $client_re->clientship_dob          = $request->clientship_dob;
        $client_re->clientship_gender       = $request->clientship_gender;
        if(isset($request->clientship_phone1)){
            $phone="";$phone_insert="";
            preg_match_all('!\d+!', $request->clientship_phone1, $phone);
            foreach($phone[0] as $key=>$value)
            {
                if($key==0) $phone_insert.=$value;
                else $phone_insert.="-".$value;
            }

            $client_re->clientship_phone1       =  $phone_insert;
        }
        if(isset($request->clientship_phone2)){
            $phone="";$phone_insert="";
            preg_match_all('!\d+!', $request->clientship_phone2, $phone);
            foreach($phone[0] as $key=>$value)
            {
                if($key==0) $phone_insert.=$value;
                else $phone_insert.="-".$value;
            }
            
            $client_re->clientship_phone2       =  $phone_insert;
        }
        $client_re->clientship_national     = $request->clientship_national;
        $client_re->personal_type = $request->personal_type;

        if($request->personal_type==1){
            $client_re->clientship_cardid       = $request->clientship_cardid;
            $client_re->clientship_datecard     = isset($request->clientship_datecard)?date("Y-m-d",strtotime($request->clientship_datecard)):null;
            $client_re->clientship_cardvalid    = isset($request->clientship_cardvalid)?date("Y-m-d",strtotime($request->clientship_cardvalid)):null;

            $client_re->passport_number = null;
            $client_re->passport_date_issue = null;
            $client_re->passport_expiry_date = null;
            $client_re->country_of_passport = null;
            $client_re->visa_type = null;
            $client_re->intended_date_of_entry = null;
            $client_re->port_of_entry =null;
        }
        else{
            $client_re->passport_number = $request->passport_number;
            $client_re->passport_date_issue = isset($request->passport_date_issue)?date("Y-m-d",strtotime($request->passport_date_issue)):null;
            $client_re->passport_expiry_date = isset($request->passport_expiry_date)?date("Y-m-d",strtotime($request->passport_expiry_date)):null;
            $client_re->country_of_passport = $request->country_of_passport;
            $client_re->visa_type = $request->visa_type;
            $client_re->intended_date_of_entry = isset($request->intended_date_of_entry)?date("Y-m-d",strtotime($request->intended_date_of_entry)):null;
            $client_re->port_of_entry = $request->port_of_entry;

            $client_re->clientship_cardid       = null;
            $client_re->clientship_datecard     = null;
            $client_re->clientship_cardvalid    = null;
        }

        $client_re->p_village               = $request->p_village;
        $client_re->p_commune               = $request->p_commune;
        $client_re->p_district              = $request->p_district;
        $client_re->p_province              = $request->p_province;
        $client_re->house                   = $request->house;
        $client_re->street                  = $request->street;
        $client_re->update();


        \LogActivity::addToLog('Client Relationship Update successfully!');
        return redirect()->route('clients-relationship.index')
                        ->with('success','Client Relationship updated successfully !');
    }
    public function destroy(Request $request, $id)
    {
        ClientRelationshipModel::destroy(Crypt::decrypt($id));
        \LogActivity::addToLog('Client Relationship deleted successfully!');
        return redirect()->back()->with('success','Client Relationship Deleted Sucessfully');
    }
    public function get_sale_client_relationship($id)
    {
        return json_encode(DB::table('nso007_relationship_status')->select("clientship_id","relationship_status")->where("sale_id",$id)->get());
    }
    public function post_sale_client_relationship(Request $request)
    {
        DB::table('nso007_relationship_status')->where('sale_id',$request->sale_id)->delete();
        foreach($request->client_relationship as $key=>$value){
            DB::table("nso007_relationship_status")->insert(['clientship_id'=>$value,'relationship_status'=>$request->relation_type[$key],"sale_id"=>$request->sale_id]);
        }
        \LogActivity::addToLog('Client Relationship Create successfully!');
        return redirect()->back()->with('success','Client Relationship Create Sucessfully');
    }

}
