<?php

namespace App\Http\Controllers\operator;

use PDF;
use \Hash;
// use DB;
 use Carbon\Carbon;
use \Crypt;
use Session;
use Validator;
use App\Models\Branch;
use App\Models\Operator;
use App\Models\Bankupload;
use Illuminate\Http\Request;
use App\Models\EnrollmentClient;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class OperatorDashboardController extends Controller
{
    //
    public function Index(Request $req){
        $data = array();
        $from_date = [];
        $to_date   = [];
        $branchData = Branch::where( 'branch_code',Session::get('operatorsession')->branch_id)->first();
        $operator_code = Session::get('operatorsession')->Operator_Code;
        // dd(Session::get('operatorsession'));
        $bankDepositAmt = Bankupload::where('Operator_Code', $operator_code);
        if(isset($req->from_date) && isset($req->to_date)){
           $bankDepositAmt = $bankDepositAmt->whereBetween('date_of_transaction', [$req->from_date, $req->to_date]);
        }
        $bankDepositAmt = $bankDepositAmt->sum('amount_credited');
        $enrData = EnrollmentClient::select('enrolment_clients.*','operators.Operator_Name','operators.Registrar_Code','operators.EA_Code','operators.State','operators.District','operators.branch_id')
        ->join('operators', 'enrolment_clients.Operator_ID','=','operators.Operator_Code')
        ->where('enrolment_clients.Operator_ID', $operator_code);
        if(isset($req->from_date) && isset($req->to_date)){
          $enrData =  $enrData->whereBetween('enrolment_clients.c_date', [$req->from_date, $req->to_date]);
          $from_date = $req->from_date;
          $to_date   = $req->to_date;

        }
        $enrData = $enrData->get();

        $AmountCollected_A = 0;
        $AmountCollected_B = 0;
        $AmountCollected_BB = 0;

        $AmountCollected_C = 0;
        $Total_Amount_X = 0;

        $Total_New_Enrollment = 0;
        $Total_Demographic_Update = 0;
        $Total_Biometric_Updates = 0;
        $Total_Mandatory_Biometric_Updates = 0;

        foreach($enrData as $key=>$val){

            if($val->Type=='U'){
                if($val->Total_amount_charged==50.0){
                    $AmountCollected_A += $val->Total_amount_charged;
                    ++$Total_Demographic_Update;
                }
                if($val->Total_amount_charged==100.0){
                    $AmountCollected_B += $val->Total_amount_charged;
                    ++$Total_Biometric_Updates;
                }
                if($val->Total_amount_charged==0.0){
                    $AmountCollected_B += $val->Total_amount_charged;
                    ++$Total_Mandatory_Biometric_Updates;
                }

            }else if($val->Type=='E' && $val->Total_amount_charged==0.0){
                ++$Total_New_Enrollment;
            }

        }

        $Total_Amount_X = ($AmountCollected_A + $AmountCollected_B + $AmountCollected_C);
        $Operator_ID   = "";
        $Operator_Name = "";
        $Station_Code  = "";
        $EA_Code       = "";
        $Registrar_Code = "";
        $state = "";
        $district = "";
        $branch_code = "";

        if(count($enrData)>0){
        $Operator_ID   = $enrData[0]['Operator_ID'];
        $Operator_Name = $enrData[0]['Operator_Name'];
        $Station_Code  = $enrData[0]['Station_ID'];
        $EA_Code       = $enrData[0]['EA_Code'];
        $Registrar_Code = $enrData[0]['Registrar_Code'];
        $state        = $enrData[0]['State'];
        $district     = $enrData[0]['District'];
        $branch_code  = $enrData[0]['branch_id'];
        }

        $data = [
            'AmountCollected_A' => $AmountCollected_A,
            'AmountCollected_B' => $AmountCollected_B,
            'AmountCollected_BB'=> $AmountCollected_BB,
            'AmountCollected_C' => 0,
            'Total_Amount_X'    => $Total_Amount_X,
            'Operator_ID'       => $Operator_ID,
            'Operator_Name'     => $Operator_Name,
            'Station_Code'      => $Station_Code,
            'Registrar_Code'    => $Registrar_Code,
            'EA_Code'           => $EA_Code,
            'New_Enrolment'     => $Total_New_Enrollment,
            'Biometric_Update'  => $Total_Biometric_Updates,
            'Mandatory_Biometric_Updates' => $Total_Mandatory_Biometric_Updates,
            'Demographic_Update'=> $Total_Demographic_Update,
            'Demographic_with_Biometric_Update'=> ($Total_Mandatory_Biometric_Updates+$Total_Demographic_Update),
            'bankDepositAmt'    => $bankDepositAmt,
            'State'             => $state,
            'District'          => $district,
            'Branch_Code'       => $branch_code
        ];

        $Total_enrollments = EnrollmentClient::select(DB::raw('COUNT(*) as number'), DB::raw('SUM(Total_amount_charged) as Total_amount_charged') )->where([['Operator_ID',$operator_code]])->get(); //dd($Total_enrollments,EnrollmentClient::where([['Operator_ID',$operator_code]])->count(),EnrollmentClient::where([['Operator_ID',$operator_code]])->sum('Total_amount_charged'));
        $new_enrollments = EnrollmentClient::where('Type','E')->select(DB::raw('COUNT(*) as number'),DB::raw('SUM(Total_amount_charged) as Total_amount_charged'))->where([['Operator_ID',$operator_code]])->get();
        $mandatory_bio_biometric_update = EnrollmentClient::where([['Total_amount_charged','0.0'],['Type','U']])->select(DB::raw('COUNT(*) as number'), DB::raw('SUM(Total_amount_charged) as Total_amount_charged') )->where([['Operator_ID',$operator_code]])->get();
        $total_demographic_update = EnrollmentClient::where([['Total_amount_charged','50.0'],['Type','U']])->select(DB::raw('COUNT(*) as number'), DB::raw('SUM(Total_amount_charged) as Total_amount_charged') )->where([['Operator_ID',$operator_code]])->get();
        $biometric_update = EnrollmentClient::where([['Total_amount_charged','100.0'],['Type','U']])->select(DB::raw('COUNT(*) as number'), DB::raw('SUM(Total_amount_charged) as Total_amount_charged') )->where([['Operator_ID',$operator_code]])->get();
        // dd(Session::get('operatorsession')->branch_id);

        $PaymentDeposited = Bankupload::where([['Operator_Code',Session::get('operatorsession')->Operator_Code]])->sum('amount_credited');
        $PaymentPending  = ($Total_enrollments[0]->Total_amount_charged - $PaymentDeposited);
        $lastMis  =  EnrollmentClient::where([['Operator_ID',$operator_code]])->orderBy('c_time','DESC')->first();
        // dd($PaymentDeposited,$PaymentPending,$bankDepositAmt,$Total_enrollments);
       

        // Assuming 132003 is a Unix timestamp
        $timestamp = $lastMis->c_time;
        
        // Create a Carbon instance from the timestamp
        $carbonDate = Carbon::createFromTimestamp($timestamp);
        
        // Format the Carbon instance as desired
        $formattedTime = $carbonDate->format('H:i:s A');
        return view('operator/dashboard',compact('data','PaymentPending','PaymentDeposited','biometric_update','lastMis','total_demographic_update','mandatory_bio_biometric_update','Total_enrollments','new_enrollments','branchData','from_date','to_date','formattedTime'));
    }
    public function ajaxDashboard(Request $req){
        $operator_code = Session::get('operatorsession')->Operator_Code;
        if($req->from_date == 'all'){
            $Total_enrollments = EnrollmentClient::select(DB::raw('COUNT(*) as number'), DB::raw('SUM(Total_amount_charged) as Total_amount_charged') )->where([['Operator_ID',$operator_code]])->get();
        $new_enrollments = EnrollmentClient::where('Type','E')->select(DB::raw('COUNT(*) as number'),DB::raw('SUM(Total_amount_charged) as Total_amount_charged'))->where([['Operator_ID',$operator_code]])->get();
        $mandatory_bio_biometric_update = EnrollmentClient::where([['Total_amount_charged','0.0'],['Type','U']])->select(DB::raw('COUNT(*) as number'), DB::raw('SUM(Total_amount_charged) as Total_amount_charged') )->where([['Operator_ID',$operator_code]])->get();
        $total_demographic_update = EnrollmentClient::where([['Total_amount_charged','50.0'],['Type','U']])->select(DB::raw('COUNT(*) as number'), DB::raw('SUM(Total_amount_charged) as Total_amount_charged') )->where([['Operator_ID',$operator_code]])->get();
        $biometric_update = EnrollmentClient::where([['Total_amount_charged','100.0'],['Type','U']])->select(DB::raw('COUNT(*) as number'), DB::raw('SUM(Total_amount_charged) as Total_amount_charged') )->where([['Operator_ID',$operator_code]])->get();


        $PaymentDeposited = Bankupload::where([['branch_code',Session::get('operatorsession')->branch_id]])->sum('amount_credited');
        $PaymentPending  = ($Total_enrollments[0]->Total_amount_charged - $PaymentDeposited);

        }else{
            $Total_enrollments = EnrollmentClient::whereBetween('enrolment_clients.c_date', [$req->from_date, $req->to_date])->select(DB::raw('COUNT(*) as number'), DB::raw('SUM(Total_amount_charged) as Total_amount_charged') )->where([['Operator_ID',$operator_code]])->get();
            $new_enrollments = EnrollmentClient::where('Type','E')->select(DB::raw('COUNT(*) as number'),DB::raw('SUM(Total_amount_charged) as Total_amount_charged'))->whereBetween('enrolment_clients.c_date', [$req->from_date, $req->to_date])->where([['Operator_ID',$operator_code]])->get();
            $mandatory_bio_biometric_update = EnrollmentClient::where([['Total_amount_charged','0.0'],['Type','U']])->whereBetween('enrolment_clients.c_date', [$req->from_date, $req->to_date])->select(DB::raw('COUNT(*) as number'), DB::raw('SUM(Total_amount_charged) as Total_amount_charged') )->where([['Operator_ID',$operator_code]])->get();
            $total_demographic_update = EnrollmentClient::where([['Total_amount_charged','50.0'],['Type','U']])->whereBetween('enrolment_clients.c_date', [$req->from_date, $req->to_date])->select(DB::raw('COUNT(*) as number'), DB::raw('SUM(Total_amount_charged) as Total_amount_charged') )->where([['Operator_ID',$operator_code]])->get();
            $biometric_update = EnrollmentClient::where([['Total_amount_charged','100.0'],['Type','U']])->whereBetween('enrolment_clients.c_date', [$req->from_date, $req->to_date])->select(DB::raw('COUNT(*) as number'), DB::raw('SUM(Total_amount_charged) as Total_amount_charged') )->where([['Operator_ID',$operator_code]])->get();


            $PaymentDeposited = Bankupload::where([['branch_code',Session::get('operatorsession')->branch_id]])->whereBetween('date_of_transaction', [$req->from_date, $req->to_date])->sum('amount_credited');
            $PaymentPending  = ($Total_enrollments[0]->Total_amount_charged - $PaymentDeposited);
        }


      $viewHtml = view('operator/dashboard_report', compact('Total_enrollments','PaymentDeposited','PaymentPending','biometric_update','total_demographic_update','new_enrollments','mandatory_bio_biometric_update'))->render();
      return \Response::json(['status'=>'success','data'=>$viewHtml]);
    }
    public function ajaxDashboardold(Request $req){

        $data = array();
        $from_date = [];
        $to_date   = [];
        $operator_code = Session::get('operatorsession')->Operator_Code;
        $bankDepositAmt = Bankupload::where('Operator_Code', $operator_code);
        if(isset($req->from_date) && isset($req->to_date)){
           $bankDepositAmt = $bankDepositAmt->whereBetween('date_of_transaction', [$req->from_date, $req->to_date]);
        }
        $bankDepositAmt = $bankDepositAmt->sum('amount_credited');
        $enrData = EnrollmentClient::select('enrolment_clients.*','operators.Operator_Name','operators.Registrar_Code','operators.EA_Code','operators.State','operators.District','operators.branch_id')
        ->join('operators', 'enrolment_clients.Operator_ID','=','operators.Operator_Code')
        ->where('enrolment_clients.Operator_ID', $operator_code);
        if(isset($req->from_date) && isset($req->to_date)){
          $enrData =  $enrData->whereBetween('enrolment_clients.c_date', [$req->from_date, $req->to_date]);
          $from_date = $req->from_date;
          $to_date   = $req->to_date;

        }
        $enrData = $enrData->get();

        $AmountCollected_A = 0;
        $AmountCollected_B = 0;
        $AmountCollected_BB = 0;

        $AmountCollected_C = 0;
        $Total_Amount_X = 0;

        $Total_New_Enrollment = 0;
        $Total_Demographic_Update = 0;
        $Total_Biometric_Updates = 0;
        $Total_Mandatory_Biometric_Updates = 0;

        foreach($enrData as $key=>$val){

            if($val->Type=='U'){
                if($val->Total_amount_charged==50.0){
                    $AmountCollected_A += $val->Total_amount_charged;
                    ++$Total_Demographic_Update;
                }
                if($val->Total_amount_charged==100.0){
                    $AmountCollected_B += $val->Total_amount_charged;
                    ++$Total_Biometric_Updates;
                }
                if($val->Total_amount_charged==0.0){
                    $AmountCollected_B += $val->Total_amount_charged;
                    ++$Total_Mandatory_Biometric_Updates;
                }

            }else if($val->Type=='E' && $val->Total_amount_charged==0.0){
                ++$Total_New_Enrollment;
            }

        }

        $Total_Amount_X = ($AmountCollected_A + $AmountCollected_B + $AmountCollected_C);
        $Operator_ID   = "";
        $Operator_Name = "";
        $Station_Code  = "";
        $EA_Code       = "";
        $Registrar_Code = "";
        $state = "";
        $district = "";
        $branch_code = "";

        if(count($enrData)>0){
        $Operator_ID   = $enrData[0]['Operator_ID'];
        $Operator_Name = $enrData[0]['Operator_Name'];
        $Station_Code  = $enrData[0]['Station_ID'];
        $EA_Code       = $enrData[0]['EA_Code'];
        $Registrar_Code = $enrData[0]['Registrar_Code'];
        $state        = $enrData[0]['State'];
        $district     = $enrData[0]['District'];
        $branch_code  = $enrData[0]['branch_id'];
        }

        $data = [
            'AmountCollected_A' => $AmountCollected_A,
            'AmountCollected_B' => $AmountCollected_B,
            'AmountCollected_BB'=> $AmountCollected_BB,
            'AmountCollected_C' => 0,
            'Total_Amount_X'    => $Total_Amount_X,
            'Operator_ID'       => $Operator_ID,
            'Operator_Name'     => $Operator_Name,
            'Station_Code'      => $Station_Code,
            'Registrar_Code'    => $Registrar_Code,
            'EA_Code'           => $EA_Code,
            'New_Enrolment'     => $Total_New_Enrollment,
            'Biometric_Update'  => $Total_Biometric_Updates,
            'Mandatory_Biometric_Updates' => $Total_Mandatory_Biometric_Updates,
            'Demographic_Update'=> $Total_Demographic_Update,
            'Demographic_with_Biometric_Update'=> ($Total_Mandatory_Biometric_Updates+$Total_Demographic_Update),
            'bankDepositAmt'    => $bankDepositAmt,
            'State'             => $state,
            'District'          => $district,
            'Branch_Code'       => $branch_code
        ];


      $viewHtml = view('operator/dashboard_report', compact('data','from_date','to_date'))->render();
      return \Response::json(['status'=>'success','data'=>$viewHtml]);
    }
    public function branchChangePassword(Request $req)
    {
        return view('operator/change_password');
    }

    public function PsswordChange(Request $req)
    {
        $user = Session::get('operatorsession');
        $validator = Validator::make($req->all(), [
            'old_password' => 'required|min:6|max:50|',
            'new_password' => 'required|min:6|max:255|',
            'confirm_password' => 'required|min:6|max:255|',
        ]);

        if ($validator->fails()) {
                return redirect()->back()->withInput($req->input())->withErrors($validator->errors());
        }

		else if ($req->new_password != $req->confirm_password) {
                return redirect()
                    ->back()
                    ->with(['message' => 'New Password and Confirm Password does not match', 'alert-type' => 'error']);
        }
		else  if (!Hash::check($req->old_password, $user->password)) {

                return redirect()
                    ->back()
                    ->with(['message' => 'Your current password does not matches with the password you provided. Please try again.', 'alert-type' => 'error']);
         }else   if ($req->old_password == $req->new_password) {

                return redirect()
                    ->back()
                    ->with(['message' => 'New Password cannot be same as your current password. Please choose a different password.', 'alert-type' => 'error']);
            } else {
                $arrayParam = [
                    'password' =>  Hash::make($req->new_password),
                    'view_password'=>$req->new_password
                ];

                DB::table('operators')
                    ->where('id', $user->id)
                    ->update($arrayParam);
					return redirect('/operator/dashboard')->with(['message' => 'Password Updated Successfully', 'alert-type' => 'success']);
            }
    }
    public function profileUpdate(Request $req){
        $user = Session::get('operatorsession');

        if($req->isMethod('post')){
            // dd($req->all());
            $validator = Validator::make($req->all(), [
                'Registrar_Code'     => 'required',
                'EA_Code'            => 'required',
                'Operator_Name'      => 'required',
                'Aadhaar_Number'     => 'required',
                //'SALARY'             => 'required',
                'PF_No'              => 'required',
                'ESI_No'             => 'required',
                'Station_Code'       => 'required',
                'NSE_IT_Certificate' => 'required',
                'VTC_Village_Town_City' => 'required',
                'Post_Office'        => 'required',
                'Block'              => 'required',
                'District'           => 'required',
                'State'              => 'required',
                'Center_Address'     => 'required',
                'Email_ID'           => 'required',
                'Mobile_No'          => 'required',
                'Any_Desk_ID'        => 'nullable',
            ]);
            
            if ($validator->fails()) {
               //  dd($req->all(),$validator->fails(),$validator->errors());
                    return redirect()->back()->withInput($req->input())->withErrors($validator->errors());
            }

           $inputArr = $req->except('_token');
         // dd($inputArr);
           Operator::where('id', $user->id)->update($inputArr);
           return redirect('operator/operator-profile-update')->with(['message'=>'Profile update successfully','alert-type'=>'success']);
        }
        $singleData = Operator::find($user->id);
        return view('operator.operator_profile', compact('singleData'));
    }
    public function operatorReport(Request $req){

        $data = array();
        if(isset($req->from_date) && isset($req->to_date)){
        $from_date = $req->from_date;
        $to_date   = $req->to_date;

        $operator_code = Session::get('operatorsession')->Operator_Code;
        $bankDepositAmt = Bankupload::where('Operator_Code', $operator_code)->sum('amount_credited');
        $enrData = EnrollmentClient::select('enrolment_clients.*','operators.Operator_Name','operators.Registrar_Code','operators.EA_Code','operators.State','operators.District','operators.branch_id')
        ->join('operators', 'enrolment_clients.Operator_ID','=','operators.Operator_Code')
        ->where('enrolment_clients.Operator_ID', $operator_code);
        if($req->from_date && $req->to_date){
            $enrData = $enrData->whereBetween('enrolment_clients.c_date', [$req->from_date, $req->to_date]);
        }
       $enrData = $enrData->get();

        $AmountCollected_A = 0;
        $AmountCollected_B = 0;
        $AmountCollected_BB = 0;

        $AmountCollected_C = 0;
        $Total_Amount_X = 0;

        $Total_New_Enrollment = 0;
        $Total_Demographic_Update = 0;
        $Total_Biometric_Updates = 0;
        $Total_Mandatory_Biometric_Updates = 0;

        foreach($enrData as $key=>$val){

        if($val->Type=='U'){
            if($val->Total_amount_charged==50.0){
                $AmountCollected_A += $val->Total_amount_charged;
                ++$Total_Demographic_Update;
            }
            if($val->Total_amount_charged==100.0){
                $AmountCollected_B += $val->Total_amount_charged;
                ++$Total_Biometric_Updates;
            }
            if($val->Total_amount_charged==0.0){
                $AmountCollected_B += $val->Total_amount_charged;
                ++$Total_Mandatory_Biometric_Updates;
            }

        }elseif($val->Type=='E' && $val->Total_amount_charged==0.0){
            ++$Total_New_Enrollment;
        }

        }

        $Total_Amount_X = ($AmountCollected_A + $AmountCollected_B + $AmountCollected_C);
        $Operator_ID   = "";
        $Operator_Name = "";
        $Station_Code  = "";
        $EA_Code       = "";
        $Registrar_Code = "";
        $state       = "";
        $branch_code = "";
        $district    = "";
        if(count($enrData)>0){
        $Operator_ID   = $enrData[0]['Operator_ID'];
        $Operator_Name = $enrData[0]['Operator_Name'];
        $Station_Code  = $enrData[0]['Station_ID'];
        $EA_Code       = $enrData[0]['EA_Code'];
        $Registrar_Code = $enrData[0]['Registrar_Code'];
        $state       = $enrData[0]['State'];
        $branch_code = $enrData[0]['branch_id'];
        $district    = $enrData[0]['District'];
        }

        $data = [
            'AmountCollected_A' => $AmountCollected_A,
            'AmountCollected_B' => $AmountCollected_B,
            'AmountCollected_BB' => $AmountCollected_BB,
            'AmountCollected_C' => 0,
            'Total_Amount_X'    => $Total_Amount_X,
            'Operator_ID'       => $Operator_ID,
            'Operator_Name'     => $Operator_Name,
            'Station_Code'      => $Station_Code,
            'Registrar_Code'    => $Registrar_Code,
            'EA_Code'           => $EA_Code,
            'New_Enrolment'     => $Total_New_Enrollment,
            'Biometric_Update'  => $Total_Biometric_Updates,
            'Mandatory_Biometric_Updates' => $Total_Mandatory_Biometric_Updates,
            'Demographic_Update' => $Total_Demographic_Update,
            'Demographic_with_Biometric_Update'=> ($Total_Mandatory_Biometric_Updates+$Total_Demographic_Update),
            'bankDepositAmt'    => $bankDepositAmt,
            'State'       => $state,
            'District'    => $district,
            'Branch_Code' => $branch_code
        ];

        if(isset($req->download_pdf) && $req->download_pdf=='download'){
            $date = date('d-m-Y');
            $pdf = \PDF::loadView('operator.download_report', compact('data','from_date','to_date'));
            return $pdf->download($date.'MIC.pdf');
        }
      }
        return view('operator.report', compact('data'));
    }
}
