<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\BaseController as BaseController;
use App\Lib\Admin\App;
use App\Lib\Core\MailPS;
use App\Models\Application;
use App\Models\Registration;
use App\Models\ApplicationFormType;
use App\Models\RegistrationViolation;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class ApplicationController extends BaseController
{
    public $className;

    public function __construct()
    {
        $classNameArr = explode('\\', __CLASS__);
        $this->className = end($classNameArr);
    }
    
    public function index(Request $request)
    {
        $exportDataArr = $fltrDataArr = [];
        $perPage    = Config('commonconstants.pagination_no');
        $sortBy     = 'id';
        $orderBy    = 'DESC';
        $data       = $request->all();

        $listDataAtrArr = App::getReportListDataAtr();
        $listDataAtrArr['form_types'] = ApplicationFormType::pluck('name', 'id')->toArray();

        // dd($listDataAtrArr);

        $lstObj = new Application();

        $fltrDataArr['application_form_type_id'] = $request->has('ftyp') ? $request->query('ftyp') : '';
        $fltrDataArr['name'] = $request->has('fnm') ? $request->query('fnm') : '';
        $fltrDataArr['email'] = $request->has('fel') ? $request->query('fel') : '';
        $fltrDataArr['cell_phone'] = $request->has('fml') ? $request->query('fml') : '';
        $fltrDataArr['years_of_expirence_under_driver_class_license'] = $request->has('fex') ? $request->query('fex') : '';
        $fltrDataArr['license'] = $request->has('fdl') ? $request->query('fdl') : '';
        $fltrDataArr['status'] = $request->has('fsts') ? $request->query('fsts') : '';
        $fltrDataArr['created_at'] = $request->has('fad') ? $request->query('fad') : '';

        if ($request->has('ppage')) {
            $perPage = $request->query('ppage');
            $exportDataArr['perPage'] = $perPage;
        }

        if ($request->has('oby')) {
            $orderBy = $request->query('oby');
            $exportDataArr['orderBy'] = $orderBy;
        }
        if ($request->has('sby')) {
            $sortBy = $request->query('sby');
            if('email' == $sortBy){
                $lstObj->join('application_forms', 'application_form.application_id', '=', 'applications.id');
                $sortBy = 'application_forms.'.$sortBy;
            }
            $exportDataArr['sortBy'] = $sortBy;
        }
        if ($request->has('page')) {
            $exportDataArr['page'] = $request->query('page');
        }

        $dataListModel = $lstObj::search($fltrDataArr)->orderBy($sortBy, $orderBy)->paginate($perPage);

        // $sortbyArr = ['id' => __('admin.insertion_txt'), 'application_form_type_id' => __('application.form_type_txt'), 'name' => __('application.name_txt'),'email' => __('application.email_txt'),'contact_number' => __('application.contact_number_txt'), 'years_of_expirence_under_driver_class_license' => __('application.experience_txt'), 'license' => __('application.license_txt'), 'status' => __('admin.status_txt'), 'created_at' => __('admin.added_date_txt')];


        $sortbyArr = ['id' => __('admin.insertion_txt'), 'application_form_type_id' => __('application.form_type_txt'), 'name' => __('application.name_txt'), 'years_of_expirence_under_driver_class_license' => __('application.experience_txt'), 'license' => __('application.license_txt'), 'status' => __('admin.status_txt'), 'created_at' => __('admin.added_date_txt')];
        $orderbyArr = ['asc' => 'ASC', 'desc' => 'DESC'];

        $showEntryArr = ['value' => __('admin.sw_entry.options.value'), 'text' => __('admin.sw_entry.options.text')];

        $exportDataArr = array_merge($exportDataArr, $fltrDataArr);

        $cFilterArr = ['all_txt' => __('admin.def_drop_optn_styl3_txt')];

        $roleRights = ['edit' => App::hasAccessToMethod($this->className, 'admin.application.edit'), 'sendpdf' => App::hasAccessToMethod($this->className, 'admin.application.sendpdf'), 'delete' => App::hasAccessToMethod($this->className, 'admin.application.delete')];

        return view('themes.backend.pages.application.index', compact('dataListModel', 'listDataAtrArr', 'sortbyArr', 'orderbyArr', 'fltrDataArr', 'perPage', 'sortBy', 'orderBy', 'showEntryArr', 'cFilterArr', 'data', 'exportDataArr', 'roleRights'));
    }

    public function edit($id)
    {
        $dataArr = Application::with(['application_form_type','application_form','account_holders_disclosure','driver_claim_histories','driver_employer_histories','driver_employer_truckings','edge_benefit','motor_vehicle_drivers','multiple_employer_driver','taining_log_hskt','taining_log_vi','taining_log_ssmq','taining_log_ls'])->find($id);

        $editDataAtrArr = ["title" => __('application.edit_txt'), "route" => 'application.edit'];
        $defDataArr = array("web_lang" => __('web'));

        return view('themes.backend.pages.application.edit', compact('dataArr', 'editDataAtrArr', 'defDataArr'));
    }

    public function update(Request $request, $id)
    {
        // dd($request->all());

        $loginAdminId = self::getLoggedInAdminId();

        $commonconstants = Config('commonconstants');

        $request->validate([
            // 'applications.employment_history_name' => 'required',
            'application_form_type_id' => 'required',
            'application_forms.name' => 'required',
            'application_forms.date_of_application' => 'required',
            'application_forms.cell_phone' => 'required',
            'application_forms.email' => [
                'required',
                'email',
                Rule::unique('appl_application_forms','email')->where(function ($query) use ($request) {
                    return $query->where('application_form_type_id', $request->application_form_type_id);
                })->ignore($request->application_forms['id']),
            ],
        ], [
            'application_form_type_id.required' => 'Registration Type is required',
            'application_forms.email.required' => 'This application email is required',
            'application_forms.email.unique' => 'This application form email is already registered, please use another one',
            'application_forms.name.required' => 'This application name is required',
            'application_forms.date_of_application.required' => 'This Date of application is required',
            'application_forms.cell_phone.required' => 'This application cell phone is required',
        ]);
        
        DB::beginTransaction();
        try {
            $input = $request->except('_method', '_token', 'submit');

            $applications = $request->applications ?? null;
            $driver_employer_histories = $request->driver_employer_histories ?? null;
            $driver_claim_histories = $request->driver_claim_histories ?? null;
            $application_forms = $request->application_forms ?? null;
            $motor_vehicle_drivers = $request->motor_vehicle_drivers ?? null;
            $multiple_employer_drivers = $request->multiple_employer_drivers ?? null;
            $account_holders_disclosures = $request->account_holders_disclosures ?? null;
            $edge_benefits = $request->edge_benefits ?? null;
            $training_logs = $request->training_logs ?? null;

            $store = Application::find($id);

            foreach ($applications as $key => $value) 
            {
                if(is_array($value)) {
                    $store->$key = json_encode($value);
                }else if(!empty($value)){
                    $store->$key = trim($value);
                }
            }

            $store->updated_by = $commonconstants['cu_by_val'][1];
            $store->updated_id = $loginAdminId;
            if($store->save()){
                $store_by_arr = ['store_by'=>$commonconstants['cu_by_val'][1], 'store_by_id'=>$loginAdminId];
                //save Trucking data
                if(isset($driver_employer_histories['trucking']) && $driver_employer_histories['trucking']){
                    $store->saveDriverEmployerHistories('trucking' , $driver_employer_histories['trucking'], $store_by_arr);
                }
                //save Employer History data
                if(isset($driver_employer_histories['history']) && $driver_employer_histories['history']){
                    $store->saveDriverEmployerHistories('history',$driver_employer_histories['history'], $store_by_arr);
                }
                //Save Claim history
                if(!empty($driver_claim_histories) && $driver_claim_histories){
                    $store->saveDriverClaimHistories($driver_claim_histories, $store_by_arr);
                }

                //Save Application form
                if(!empty($application_forms) && $application_forms){
                  $store->saveApplicationForm($application_forms, $store_by_arr);
                }

                //Save Motor Vehicle Driver Data
                if(!empty($motor_vehicle_drivers) && $motor_vehicle_drivers){
                    $store->saveMotorVehicleDriverData($motor_vehicle_drivers, $store_by_arr);
                }

                //Save Multiple Employer Driver Data
                if(!empty($multiple_employer_drivers) && $multiple_employer_drivers){
                    $store->saveMultipleEmployerDriverData($multiple_employer_drivers, $store_by_arr);
                }

                //Save account holders disclosures Data
                if(!empty($account_holders_disclosures) && $account_holders_disclosures){
                    $store->saveAccountHoldersDisclosureData($account_holders_disclosures, $store_by_arr);
                }

                //Save edge benefits Data
                if(!empty($edge_benefits) && $edge_benefits){
                    $store->saveEdgeBenefitData($edge_benefits, $store_by_arr);
                }

                //Save training logs Data
                if(!empty($training_logs) && $training_logs){
                    $store->saveTrainingDataLogs($training_logs, $store_by_arr);
                }

                DB::commit();
            }

        } catch (QueryException $exception) {
            DB::rollBack();
            if ($loginAdminId == $commonconstants['def_super_admin_id']) {
                return back()->with('alert', Config('adminconstants.alert_css.2'))->with('message', $exception->getMessage())->with('title', __('admin.error_ttl'))->withInput();
            } else {
                return back()->with('alert', Config('adminconstants.alert_css.2'))->with('message', __('message.error.update'))->with('title', __('admin.error_ttl'));
            }
        }

        return back()->with('alert', Config('adminconstants.alert_css.1'))->with('message', __('message.success.update'))->with('title', __('admin.success_ttl'));
    }


    public function approve(Request $request, $id)
    {
        $loginAdminId = self::getLoggedInAdminId();        
        $commonconstants = Config('commonconstants');

        $application = Application::find($id);
        if($application && $application->status ==0 ){
            $application->status = 1 ;
            $application->status_date = date('Y-m-d H:i:s');
            $application->updated_by = $commonconstants['cu_by_val'][1];
            $application->updated_id = $loginAdminId;
            if($application->save()){
                $mailPSObj = new MailPS();
                $mailResp = $mailPSObj->sendTemplateMail(6, $application);        
                if ($mailResp) {
                    return back()->with('alert', Config('adminconstants.alert_css.1'))->with('message', __('message.success.approved'))->with('title', __('admin.success_ttl'));
                } else {
                    return back()->with('alert', Config('adminconstants.alert_css.2'))->with('message', __('message.warning.approved'))->with('title', __('admin.error_ttl'));
                }
            }else{
                return back()->with('alert', Config('adminconstants.alert_css.2'))->with('message', __('message.error.approved'))->with('title', __('admin.error_ttl'));
            }
        }
        abort(404);
    }

    public function decline(Request $request, $id)
    {
        $loginAdminId = self::getLoggedInAdminId();        
        $commonconstants = Config('commonconstants');

        $application = Application::find($id);
        if($application && $application->status ==0 ){
            $application->status = 2 ;
            $application->status_date = date('Y-m-d H:i:s');
            $application->updated_by = $commonconstants['cu_by_val'][1];
            $application->updated_id = $loginAdminId;
            if($application->save()){
                $mailPSObj = new MailPS();
                $mailResp = $mailPSObj->sendTemplateMail(7, $application);
        
                if ($mailResp) {
                    return back()->with('alert', Config('adminconstants.alert_css.1'))->with('message', __('message.success.declined'))->with('title', __('admin.success_ttl'));
                } else {
                    return back()->with('alert', Config('adminconstants.alert_css.2'))->with('message', __('message.warning.declined'))->with('title', __('admin.error_ttl'));
                }
            }else{
                return back()->with('alert', Config('adminconstants.alert_css.2'))->with('message', __('message.error.declined'))->with('title', __('admin.error_ttl'));
            }
        }
        abort(404);
    }


    public function sendPdf(Request $request, $id)
    {
        $registration = Registration::find($id);
        if($registration){
            $mailPSObj = new MailPS();
            $mailResp = $mailPSObj->sendTemplateMail(6, $registration);
    
            if ($mailResp) {
                return back()->with('alert', Config('adminconstants.alert_css.1'))->with('message', __('message.success.email_send'))->with('title', __('admin.success_ttl'));
            } else {
                return back()->with('alert', Config('adminconstants.alert_css.2'))->with('message', __('message.error.email_send'))->with('title', __('admin.error_ttl'));
            }
        }
        abort(404);
    }

    public function deletedata(Request $request)
    {
        $loginAdminId = self::getLoggedInAdminId();
        try {
            $checkboxArr = $request->get('checkbox');
            if($request->ajax()){
                Application::destroy($checkboxArr);
            }else{
                if(count($checkboxArr)>0)
                {
                    foreach ($checkboxArr as $key => $applicationId) {
                        Application::deleteData($applicationId);
                    }
                }
            }
        } catch (QueryException $exception) {
            if($request->ajax()){
                return response()->json(['result' => false,'redirect_url' => '','message' =>  __('message.error.delete') ]);
            }else{
                if($loginAdminId == Config('commonconstants.def_super_admin_id')){
                    return back()->with('alert', Config('adminconstants.alert_css.2'))->with('message', $exception->getMessage())->with('title', __('admin.error_ttl'))->withInput();
                }
                else{
                    return back()->with('alert', Config('adminconstants.alert_css.2'))->with('message', __('message.error.delete'))->with('title', __('admin.error_ttl'));
                }
            }
        }
        
        if($request->ajax()){
            return response()->json(['result' => true,'redirect_url' => '','message' =>  __('message.success.delete')]);
        }else{
            return back()->with('alert', Config('adminconstants.alert_css.1'))->with('message', __('message.success.delete'))->with('title', __('admin.success_ttl'));
        }
    }

}
