<?php

namespace App\Http\Controllers\admin;

use DB;
use Session;
use Exception;
use Validator;
use App\Models\Operator;
use App\Models\Registrar;
use App\Imports\UsersImport;
use Illuminate\Http\Request;
use App\Models\EnrollmentClient;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class AdminOperatorContoller extends Controller
{
    //


    public function Index(Request $request){

        if($request->isMethod('post')){

            // dd($request->all());

            $validator = Validator::make($request->all(), [
                'Email_ID' => 'required|email|unique:operators',
                'password' => 'required',
            ]);
            if ($validator->fails()) {
                return redirect()
                    ->back()
                    ->withInput($request->input())
                    ->withErrors($validator->errors());
            }

            $branch_id = Session::get('branchsession')->id;

            $operatorObj = new Operator();

            $operatorObj->Registrar_Code = $request->Registrar_Code;
            $operatorObj->EA_Code = $request->EA_Code;
            $operatorObj->Operator_Code = $request->Operator_Code;
            $operatorObj->Operator_Name = $request->Operator_Name;
            $operatorObj->Aadhaar_Number = $request->Aadhaar_Number;
            $operatorObj->SALARY = $request->SALARY;
            $operatorObj->PF_No = $request->PF_No;
            $operatorObj->ESI_No = $request->ESI_No;
            $operatorObj->Station_Code = $request->Station_Code;
            $operatorObj->NSE_IT_Certificate = $request->NSE_IT_Certificate;
            $operatorObj->VTC_Village_Town_City = $request->VTC_Village_Town_City;
            $operatorObj->Post_Office = $request->Post_Office;
            $operatorObj->Block = $request->Block;
            $operatorObj->District = $request->District;
            $operatorObj->State = $request->State;
            $operatorObj->Center_Address = $request->Center_Address;
            $operatorObj->Email_ID = $request->Email_ID;
            $operatorObj->Mobile_No = $request->Mobile_No;
            $operatorObj->Any_Desk_ID = $request->Any_Desk_ID;
            $operatorObj->password = Hash::make($request->password);
            $operatorObj->view_passsword = $request->password;

            $operatorObj->status = !empty($request->status) ? 1 : 0;

            $operatorObj->branch_id = $branch_id;
            $res =  $operatorObj->save();

            if($res){
                return redirect('branch/view-operators')->with(['message'=>'Operators Added Successfully !','alert-type'=>'success']);
            }
        }
        return view('admin.add-operator');
    }

    public function ViewOperator(Request $request){
        // dd($request->all(),$request->status);
        $statusCode = false;
        if($request->status){
            // dd('kk');
        if($request->status == 1){
            $statusCode = '1';
        }
         if($request->status == 2){
            $statusCode = '2';
        }
        if($request->status == 3){
            $statusCode = '3';
        }
        if($request->status == 4){
            $statusCode = '0';
        }
    }
        // dd($statusCode,$request->status);
        if(Session::has('adminsession')){
            $operatorList = Operator::orderBy('id','DESC')->When($request->status, function ($query) use($statusCode) {
                return $query->where('status',$statusCode);
            });
            if(isset($request->from_date) && isset($request->to_date)){
                $operatorList = $operatorList->whereBetween('created_at', [$request->from_date, $request->to_date]);
           }

         $operatorList =  $operatorList->paginate(50);
            return view('admin.view-operator',compact('operatorList'));
        }
        if(Session::has('branchsession')){
            $branch_id = Session::get('branchsession')->branch_code;

            $operatorList = Operator::where('branch_id', $branch_id)->When($request->status, function ($query) use($statusCode) {
                return $query->where('status',$statusCode);
            });
            if(isset($request->from_date) && isset($request->to_date)){
                $operatorList = $operatorList->whereBetween('created_at', [$request->from_date, $request->to_date]);
           }
           $operatorList = $operatorList->orderBy('id','DESC')->paginate(50);
            return view('branch.view-operator',compact('operatorList'));
        }
    }
    public function ViewOperatorStatus($status){
        if($status == 'active'){
            $statusCode = '1';
        }
         if($status == 'inactive'){
            $statusCode = '2';
        }
        if($status == 'disassociated'){
            $statusCode = '3';
        }
        if($status == 'blacklisted'){
            $statusCode = '0';
        }
        if(Session::has('adminsession')){
            $operatorList = Operator::where('status',$statusCode)->orderBy('id','DESC')->paginate(50);
            return view('admin.view-operator',compact('operatorList','statusCode','status'));
        }

    }


    public function ExcelUpload(Request $request){

        if($request->isMethod('post')){

            if ($request->hasFile('excel_file')) {
                try{
                    $import = new UsersImport;
                    Excel::import($import, request()->file('excel_file'));

                    $notification = array(
                        'message' => 'Excel upload Successfully!',
                        'alert-type' => 'success'
                    );

                return redirect('admin/view-operator')->with($notification);

                }catch (\Exception $e) {
                    $notification = array(
                        'message' => $e,
                        'alert-type' => 'error'
                    );
                    return back()->with($notification);
                }
            }
        }
        if(Session::has('branchsession')){
            return view('branch.upload-operator-excel');
        }else if(Session::has('adminsession')){
            return view('admin.upload-operator-excel');
        }

    }
    public function uploadEnrollment(Request $req){
        if($req->isMethod('post')){
            $validator = Validator::make($req->all(), [
                'excel_file' => 'required|mimes:html,htm',
            ]);
            if ($validator->fails()) {
                return redirect()
                    ->back()
                    ->withInput($req->input())
                    ->withErrors($validator->errors());
            }


            $file = $req->file('excel_file');
            $tempPath = $file->store('temp', 'public');
            $htmlContent = file_get_contents(storage_path('app/public/' . $tempPath));
             // Extract student records from the HTML content (assuming a specific format)
            $reD = $this->extractStudentRecords($htmlContent);
            // Optionally, delete the temporary file
            // dd($reD);
            unlink(storage_path('app/public/' . $tempPath));

            if($reD=='notExistOperator'){
                return back()->with(['message'=>"Operator doesn't exists",'alert-type'=>'error']);
            }
            if($reD=='notMatchSerial'){
                return back()->with(['message'=>"Operator doesn't match serial no.",'alert-type'=>'error']);
            }
            if($reD=='Invalid_Operator'){
                return back()->with(['message'=>"Invalid Operator.",'alert-type'=>'error']);
            }
            if($reD=='Invalid_branch'){
                return back()->with(['message'=>"Invalid Branch Operator.",'alert-type'=>'error']);
            }
            if($reD=='Invalid_admin_operator'){
                return back()->with(['message'=>"Invalid Admin Operator.",'alert-type'=>'error']);
            }
            if($reD == 'Invalid_registrar_code'){
                return back()->with(['message'=>'Invalid_registrar_code dose not Exists','alert-type'=>'error']);
            }
            if($reD!=='success'){
                return back()->with(['message'=>'Enrolment_No_and_Date already Exists','alert-type'=>'error']);
            }

        }
        if(Session::has('adminsession')){
            return redirect('/admin/enrollment-client-view')->with(['message'=>'Upload file successfully','alert-type'=>'success']);
        }else if(Session::has('operatorsession')){
            return redirect('/operator/enrollment-client-view')->with(['message'=>'Upload file successfully','alert-type'=>'success']);
        }else if(Session::has('branchsession')){
            return redirect('/branch/enrollment-client-view')->with(['message'=>'Upload file successfully','alert-type'=>'success']);
        }
    }
    private function extractStudentRecords($htmlContent)
    {
           // dd('hvhj');
        /** @var UploadedFile $file */
        // Create a DomCrawler instance to parse the HTML content
        $crawler = new Crawler($htmlContent);
        // Filter all rows inside the table
        $allRows = $crawler->filter('table tr');
        // Process rows starting from the 16th row (skip the first 15 rows)
        $startRow = 1; // Change this number to skip a different number of rows
        $studentRecords = [];
        $j = 0;

        for ($i = $startRow; $i < $allRows->count(); $i++) {
             $row = $allRows->eq($i);
             // Customize this logic to match the structure of your HTML
            if($row->filter('td:nth-child(1)')->text()=='1'){
                ++$j;
            }
            if($j==0){
                continue;
            }
            $Enrolment_No_And_Date	      = $row->filter('td:nth-child(2)')->text();
            $Appointment_Id		          = $row->filter('td:nth-child(3)')->text();
            $Type	                      = $row->filter('td:nth-child(4)')->text();
            $Mandatory_Biometric_Update	  = $row->filter('td:nth-child(5)')->text();
            $IS_NRI	                      = $row->filter('td:nth-child(6)')->text();
            $Tin_Number		              = $row->filter('td:nth-child(7)')->text();
            $Operator_ID		          = $row->filter('td:nth-child(8)')->text();
            $Reviewer_ID		          = $row->filter('td:nth-child(9)')->text();
            $Introducer	                  = $row->filter('td:nth-child(10)')->text();
            $Proof	                      = $row->filter('td:nth-child(11)')->text();
            $Resident	                  = $row->filter('td:nth-child(12)')->text();
            $Status	                      = $row->filter('td:nth-child(13)')->text();
            $Introducer_Review_Status     = $row->filter('td:nth-child(14)')->text();
            $User_Review_Status		      = $row->filter('td:nth-child(15)')->text();
            $GST_Applied	              = $row->filter('td:nth-child(16)')->text();
            $Amount_Charged_For_New_Enrolment    = $row->filter('td:nth-child(17)')->text();
            $Amount_Charged_For_Update_Enrolment = $row->filter('td:nth-child(18)')->text();
            $Total_Amount_Charged         = $row->filter('td:nth-child(19)')->text();
            $Registrar                    = substr($Enrolment_No_And_Date, 1,3);
            $Station_ID                   = substr($Enrolment_No_And_Date, 4,5);
            $Enrolment_Agency             = substr($Enrolment_No_And_Date, 0, 4);
            $admin_id ="";

            // dd($Registrar,Registrar::where('code',$Registrar)->first());
            if(Session::has('adminsession')){
                $admin_id                     = Session::get('adminsession')->id;
            }

            $aadhar_uid                   = substr($Enrolment_No_And_Date, 9, 5);
            $c_date                       = substr($Enrolment_No_And_Date, 14, 4).'-'.substr($Enrolment_No_And_Date, 18, 2).'-'.substr($Enrolment_No_And_Date, 20, 2);
            $c_time                       = substr($Enrolment_No_And_Date, 22, 6);

            if(Operator::where('Operator_Code', $Operator_ID)->doesntExist()){
                return 'notExistOperator';
            }
            if(Session::has('operatorsession')){

                $oplData = Session::get('operatorsession');

                if($oplData->Operator_Code != $Operator_ID){
                    return 'Invalid_Operator';
                }
                $branch_code = $oplData->branch_id;
            }
            if(Session::has('branchsession')){
                $branch_code = Session::get('branchsession')->branch_code;
                $branchData = Operator::select('branch_id')->where('Operator_Code', $Operator_ID)->where('branch_code', $branch_code)->first();
                if($branchData->branch_id != $branch_code){
                    return 'Invalid_branch';
                }
            }
            if(Session::has('adminsession')){
                $adminData = Operator::select('branch_id')->where('Operator_Code', $Operator_ID)->first();
                if($adminData){
                    $branch_code = $adminData->branch_id;
                }else{
                    return 'Invalid_admin_operator';
                }
            }
            // dd($Registrar);
            if(Registrar::where('Registrar_code',$Registrar)->doesntExist()){
                return 'Invalid_registrar_code';
            }
            #check
            if(EnrollmentClient::where('Enrolment_No_And_Date',$Enrolment_No_And_Date)->exists()){
                continue;
            }
            if($opData = EnrollmentClient::where('Operator_ID',$Operator_ID)->where('Station_ID',$Station_ID)->latest()->first()){
                $poSRno = $opData->aadhar_uid;
                // if($poSRno != ($aadhar_uid-1)){
                //    return 'notMatchSerial';
                // }
            }
            // $codeExists = ;
           // dd( $codeExists);


            #store in array

             $studentRecords[] = [
                'Enrolment_No_and_Date'   => $Enrolment_No_And_Date,
                'Appointment_Id'          => $Appointment_Id,
                'Type'                    => $Type,
                'Mandatory_biometric_update' => $Mandatory_Biometric_Update,
                'IS_NRI'                  => $IS_NRI,
                'Tin_Number'              => $Tin_Number,
                'Operator_ID'             => $Operator_ID,
                'Reviewer_ID'             => $Reviewer_ID,
                'Introducer'              => $Introducer,
                'Proof'                   => $Proof,
                'Resident'                => $Resident,
                'Status'                  => $Status,
                'Introducer_Review_Status'=> $Introducer_Review_Status,
                'User_Review_Status'      => $User_Review_Status,
                'GSApplied_Percentage'    => $GST_Applied,
                'Amount_charged_for_New_Enrolment'    => $Amount_Charged_For_New_Enrolment,
                'Amount_charged_for_Update_Enrolment' => $Amount_Charged_For_Update_Enrolment,
                'Total_amount_charged'    => $Total_Amount_Charged,
                'Registrar'               => $Registrar,
                'Station_ID'              => $Station_ID,
                'Enrolment_Agency'        => $Enrolment_Agency,
                'admin_id'                => $admin_id,
                'aadhar_uid'              => $aadhar_uid,
                'c_date'                  => $c_date,
                'c_time'                  => $c_time,
                'branch_code'             => $branch_code,
                // Add other columns as needed
            ];
        }

        try {
            DB::beginTransaction();
            EnrollmentClient::insert($studentRecords);
            DB::commit();

        } catch (Exception $e) {
            DB::rollBack();
            return $e->getMessage();
        }

     return "success";

    }
}

