<?php

namespace App\Http\Controllers\Administrator;


use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\ClientModel;
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 ClientControler extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    function __construct()
    {
        $this->middleware('permission:Client-List');
        $this->middleware('permission:Client-Create', ['only' => ['create', 'store']]);
        $this->middleware('permission:Client-Edit', ['only' => ['edit', 'update']]);
        $this->middleware('permission:Client-Delete', ['only' => ['destroy']]);
        $this->middleware('permission:Client-View', ['only' => ['view_client']]);
    }

    public function index()
    {
        return view('administrator.clients.index');
    }
    public function datatable_get_report_client(Request $request)
    {
        $client_name = $request->client_name;
        $client_phone = $request->client_phone;
        $clients = ClientModel::with(['get_province', 'get_district', 'get_commune', 'get_village'])
                ->select('nso007_client.*')
                ->where('status', 1)
                ->when(request('client_name'),function($query) use ($client_name){
                    $query->where("nso007_client.client_fullname","LIKE","%".$client_name."%");
                })
                ->when(request('client_phone'),function($query) use ($client_phone){
                    $query->where("nso007_client.client_phone1",$client_phone);
                })
                ->get();
        return Datatables::of($clients)
            ->addIndexColumn()
            ->addColumn('client_gender', function ($clients) {

                return $clients->client_gender;
            })
            ->editColumn('client_dob', function ($clients) {
                if(empty($clients->client_dob)) return "";
                else return date('d-m-Y', strtotime($clients->client_dob));
            })
            ->editColumn('client_phone1', function ($clients) {
                $phone = $clients->client_phone1;
                if (!empty($clients->client_phone2)) $phone .= " ," . $clients->client_phone2;
                // $phone = str_replace(' ', '', $phone);
                // $phone = chunk_split($phone, 3, ' ');
                return $phone;
            })
            ->editColumn('client_fullname', function ($client) {
                return $client->client_firstname . ' ' . $client->client_lastname;
            })
            ->editColumn('image', function ($clients) {
                if (!empty($clients->client_img) && $clients->client_img != 'none') {
                    $url = asset('assets/images/resize/' . $clients->client_img);
                } else {
                    $url = asset('assets/images/default.png');
                }

                return $url;
            })
            ->editColumn('address', function ($client) {
                if(!empty($client->p_village)){
                    return optional(VillageModel::find($client->p_village))->address();
                }
            })
            ->editColumn('action', function ($user) {
                $view = '';
                $edits = '';
                $delete = '';
                if (Gate::check('Client-View')) {
                    $view  = '<a class="button_primary fa fa-eye viewclient btn-view" role="button" data-id="' . $user->id . '" data-toggle="modal tooltip" data-target="#viewModal" data-placement="bottom" title="view"></a>';
                }
                if (Gate::check('Client-Edit')) {
                    $edits = '<a href="' . Route("clients.edit", Crypt::encrypt($user->id)) . '" class="button_success btn-xs fa fa-edit"></a>';
                }
                if (Gate::check('Client-Delete') && $user->status_delete == 1) {
                    $delete = '<a href="' . Route("clients.delete", Crypt::encrypt($user->id)) . '" class="button_danger btn-xs fa fa-trash"></a>';
                }
                return $view . $edits . $delete;
            })
            ->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.clients.create', compact('provinces'));
    }
    public function store(Request $request)
    {
        $this->validate($request, [
            'client_firstname'      => 'required',
            'client_lastname'       => 'required',
            'client_gender'         => 'required',
            'client_dob'            => 'required',
            'client_national'       => 'required',
            'client_phone1'         => 'required|unique:nso007_client',
            //            'client_cardid'         => 'required|unique:nso007_client',
            'p_province'            => 'required',
            'p_district'            => 'required',
            'p_commune'             => 'required',
            'p_village'             => 'required',

        ]);

        $client = new ClientModel;

        $file       = $request->file('client_feature');
        if ($request->file('client_feature') == null) {
            $original_name = "none";
        } else {
            $original_name = $file->getClientOriginalName();
            $original_name = date('ymdhis') . $original_name;
            $destinationPath = 'assets/images/resize';
            $thum = Image::make($file->getRealPath())->resize(150, 150);
            $thum->save($destinationPath . '/' . $original_name, 80);
        }
        $client->client_fullname = $request->client_firstname . ' ' . $request->client_lastname;
        $client->client_firstname = $request->client_firstname;
        $client->client_lastname = $request->client_lastname;
        $client->client_gender = $request->client_gender;
        if (isset($request->client_phone1)) {
            $phone = "";
            $phone_insert = "";
            preg_match_all('!\d+!', $request->client_phone1, $phone);
            foreach ($phone[0] as $key => $value) {
                if ($key == 0) $phone_insert .= $value;
                else $phone_insert .= "-" . $value;
            }

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

            $client->client_phone2       =  $phone_insert;
        }
        $client->client_nickname = $request->client_nickname;
        $client->client_img = $original_name;
        $client->p_village     = $request->p_village;
        $client->p_commune     = $request->p_commune;
        $client->p_district    = $request->p_district;
        $client->p_province    = $request->p_province;
        $client->client_national = $request->client_national;
        $client->client_dob = date('Y-m-d', strtotime($request->client_dob));
        $client->client_job = $request->client_job;
        $client->client_workplace = $request->client_workplace;
        $client->client_cardid = $request->client_cardid;
        $client->client_cardvalid = isset($request->client_cardvalid) ? date('Y-m-d', strtotime($request->client_cardvalid)) : null;
        $client->client_datecard = isset($request->client_datecard) ? date('Y-m-d', strtotime($request->client_datecard)) : null;
        $client->house = $request->house;
        $client->street = $request->street;
        $client->passport_number = $request->passport_number;
        $client->passport_date_issue = isset($request->passport_date_issue) ? date('Y-m-d', strtotime($request->passport_date_issue)) : null;
        $client->passport_expiry_date = isset($request->passport_expiry_date) ? date('Y-m-d', strtotime($request->passport_expiry_date)) : null;
        $client->country_of_passport = $request->country_of_passport;
        $client->visa_type = $request->visa_type;
        $client->intended_date_of_entry = isset($request->intended_date_of_entry) ? date('Y-m-d', strtotime($request->intended_date_of_entry)) : null;
        $client->port_of_entry = $request->port_of_entry;
        $client->personal_type = $request->personal_type;

        $client->save();

        \LogActivity::addToLog('Income createted successfully!');
        return redirect()->route('clients.index');
    }
    public function show($id)
    {
        $client = ClientModel::find($id);
        $client->address= '';
        if(!empty($client->p_village)){
            $client->address = VillageModel::find($client->p_village)->address();
        }
        return response()->json(['success' => true, 'data' => $client]);
    }
    public function edit($id)
    {
        $decrypt_id = Crypt::decrypt($id);
        $client = ClientModel::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.clients.edit', compact('client', '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 = ClientModel::find($id);
        $this->validate($request, [
            'client_firstname'      => 'required',
            'client_lastname'       => 'required',
            'client_gender'         => 'required',
            'client_dob'            => 'required',
            'client_national'       => 'required',
            'client_phone1'         => 'required|unique:nso007_client,client_phone1,' . $id,
            //            'client_cardid'         => 'required|unique:nso007_client,client_cardid,'.$id,
            'p_province'            => 'required',
            'p_district'            => 'required',
            'p_commune'             => 'required',
            'p_village'             => 'required',

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

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

            $client->client_phone2       =  $phone_insert;
        }
        $client->client_nickname = $request->client_nickname;
        $client->client_address = $request->client_address;
        $client->client_national = $request->client_national;
        $client->client_dob = date('Y-m-d', strtotime($request->client_dob));
        $client->client_job = $request->client_job;
        $client->p_village     = $request->p_village;
        $client->p_commune     = $request->p_commune;
        $client->p_district    = $request->p_district;
        $client->p_province    = $request->p_province;
        $client->client_workplace = $request->client_workplace;

        $client->house = $request->house;
        $client->street = $request->street;
        if ($request->personal_type == 1) {
            $client->client_cardid = $request->client_cardid;
            $client->client_cardvalid = isset($request->client_cardvalid) ? date('Y-m-d', strtotime($request->client_cardvalid)) : null;
            $client->client_datecard = isset($request->client_datecard) ? date('Y-m-d', strtotime($request->client_datecard)) : null;

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

            $client->client_cardid = null;
            $client->client_cardvalid = null;
            $client->client_datecard = null;
        }

        $client->personal_type = $request->personal_type;

        $file       = $request->file('image');
        if ($request->file('image') == null) {
            $original_name = "none";
        } else {
            $original_name = $file->getClientOriginalName();
            $original_name = date('ymdhis') . $original_name;
            $destinationPath = 'assets/images/resize';
            $thum = Image::make($file->getRealPath())->resize(150, 150);
            $thum->save($destinationPath . '/' . $original_name, 80);
        }

        $client->client_img  = $original_name;
        $client->update();

        \LogActivity::addToLog('Client updated successfully !');
        return redirect()->route('clients.index')
            ->with('success', 'Client updated successfully !');
    }
    public function destroy($id)
    {
        \LogActivity::addToLog('Client deleted successfully!');
        ClientModel::destroy(Crypt::decrypt($id));
        return redirect()->route('clients.index')->with('success', 'Deleted Successful!');
    }
    public function view_client()
    {
        $client = ClientModel::find($_GET['id']);
        $data = [
            'firstname' => $client->client_firstname,
            'lastname'  => $client->client_lastname,
            'nickname'  => $client->client_nickname,
            'gender'    => $client->client_gender,
            'dob'       => $client->client_dob,
            'national'  => $client->client_national,
            'phone1'    => $client->client_phone1,
            'phone2'    => $client->client_phone2,
            'job'       => $client->client_job,
            'profile'   => $client->client_img,
            'workplace' => $client->client_workplace,
            'card_id'   => $client->client_cardid,
            'date_card' => $client->client_datecard,
            'card_valid' => $client->client_cardvalid,
            'address'   => optional($client->get_province)->province_km . ', ' .
                optional($client->get_district)->district_km . ', ' .
                optional($client->get_commune)->commune_km . ', ' .
                optional($client->get_village)->village_km . ', ' .
                $client->house . ', ' . $client->street,


        ];
        return response()->json(['datas' => $data]);
    }
}
