<?php

namespace App\Http\Controllers\branch;


use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
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 BranchDashboardController extends Controller
{
    //
    public function Index(Request $req)
    {
        $branch_code = Session::get('branchsession')->branch_code;
        $operator = Operator::where([['branch_id',$branch_code]])->get();

        //Top 5 Operators (Daily Enrolment Wise)
        $currrentDate = date('Y-m-d');
        $currentDatelast30day= date('Y-m-d', strtotime('-30 days'));
       $enrollmentListTopDailyWise = EnrollmentClient::join('operators', 'enrolment_clients.Operator_ID', '=', 'operators.Operator_Code')
       ->whereBetween('enrolment_clients.c_date',[$currentDatelast30day,$currrentDate])
       ->select('operators.Operator_Name',DB::raw('COUNT(*) as number') )
       ->groupBy('enrolment_clients.Operator_ID', 'operators.Operator_Name')
       ->orderBy('number', 'DESC')
       ->where([['enrolment_clients.branch_code',$branch_code]])
       ->limit(5)
       ->get()->toArray();

        $pendingTopPaymentOperator =
        EnrollmentClient::select('Operator_ID', DB::raw('COUNT(*) as number'),DB::raw('SUM(Total_amount_charged) as Total_amount_charged') )->groupBy('Operator_ID')
        ->orderBy('Total_amount_charged', 'DESC')
        ->with(['BankUpload' => function ($query)  {
            $query->select('Operator_Code', DB::raw('SUM(amount_credited) as amount_credited'))
            ->groupBy('Operator_Code');
        },'Operator'=>function($q){
            $q->select('Operator_Code','Operator_Name');
        }])
        ->where([['enrolment_clients.branch_code',$branch_code]])
       ->limit(5)
       ->get();
       $pendingTopPaymentBranch =
       EnrollmentClient::select('branch_code', DB::raw('COUNT(*) as number'),DB::raw('SUM(Total_amount_charged) as Total_amount_charged') )->groupBy('branch_code')
       ->orderBy('Total_amount_charged', 'DESC')
        ->with(['Branch'=>function($q){
            $q->select('branch_code','branch_name');
        },'BankUploadBranch'])
        ->where([['enrolment_clients.branch_code',$branch_code]])
      ->limit(5)
      ->get();

        $Total_enrollments = EnrollmentClient::select(DB::raw('COUNT(*) as number'), DB::raw('SUM(Total_amount_charged) as Total_amount_charged') )->where([['enrolment_clients.branch_code',$branch_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([['enrolment_clients.branch_code',$branch_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([['enrolment_clients.branch_code',$branch_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([['enrolment_clients.branch_code',$branch_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([['enrolment_clients.branch_code',$branch_code]])->get();


        $PaymentDeposited = Bankupload::where([['branch_code',$branch_code]])->sum('amount_credited');
        $PaymentPending  = ($Total_enrollments[0]->Total_amount_charged - $PaymentDeposited);
        $lastMisDate  =  EnrollmentClient::where([['branch_code',$branch_code]])->orderBy('id','DESC')->first()->c_date;
        $lastUpdateOperatorsCount  =  EnrollmentClient::select('Operator_ID')->where('branch_code',$branch_code)->whereDate('c_date', $lastMisDate)->groupBy('Operator_ID')->get()->toArray();
        // dd();
        $lastUpdateOperatorsCount = count($lastUpdateOperatorsCount);
        $allOperator_Code = Operator::where([['branch_id',$branch_code]])->count();
        // dd($lastUpdateOperatorsCount,$allOperator_Code);
        // dd($Total_enrollments ,$new_enrollments,$mandatory_bio_biometric_update,$total_demographic_update,$biometric_update);
      return view('branch/dashboard', compact('PaymentPending','lastUpdateOperatorsCount','allOperator_Code','PaymentDeposited','lastMisDate','Total_enrollments','new_enrollments','mandatory_bio_biometric_update','total_demographic_update','biometric_update','operator','enrollmentListTopDailyWise','pendingTopPaymentOperator','pendingTopPaymentBranch'));
    }
    public function NotOperatorsMis()
    {
        $branch_code = Session::get('branchsession')->branch_code;
        $lastMisDate  =  EnrollmentClient::where([['branch_code',$branch_code]])->orderBy('id','DESC')->first()->c_date;
        $lastUpdateOperatorsCount  =  EnrollmentClient::select('Operator_ID')->whereDate('c_date', $lastMisDate)->groupBy('Operator_ID')->pluck('Operator_ID');

        $operatorList = Operator::where('branch_id',$branch_code)->whereNotIn('Operator_Code', $lastUpdateOperatorsCount)->paginate();

        return view('branch.not-upload-mis-operator', compact('operatorList'));
    }
    public function dashboardAjax(Request $req){
        // dd($req->all());
        $branch_code = Session::get('branchsession')->branch_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([['enrolment_clients.branch_code',$branch_code]])->get();
            $new_enrollments = EnrollmentClient::where('Type','E')->select(DB::raw('COUNT(*) as number'), DB::raw('SUM(Total_amount_charged) as Total_amount_charged'))->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([['enrolment_clients.branch_code',$branch_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([['enrolment_clients.branch_code',$branch_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([['enrolment_clients.branch_code',$branch_code]])->get();
            // dd($Total_enrollments,$biometric_update , $total_demographic_update,$mandatory_bio_biometric_update);

            $PaymentDeposited = Bankupload::where([['branch_code',$branch_code]])->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([['enrolment_clients.branch_code',$branch_code]])->get();
            $new_enrollments = EnrollmentClient::where('Type','E')->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([['enrolment_clients.branch_code',$branch_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([['enrolment_clients.branch_code',$branch_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([['enrolment_clients.branch_code',$branch_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([['enrolment_clients.branch_code',$branch_code]])->get();
            // dd($Total_enrollments,$biometric_update , $total_demographic_update,$mandatory_bio_biometric_update);

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


        $html =  view('admin.dashboard-ajax',compact('Total_enrollments','PaymentDeposited','PaymentPending','biometric_update','total_demographic_update','new_enrollments','mandatory_bio_biometric_update'))->render();
       //dd($html); // return \Response::json(['status'=>'success','data'=>$viewHtml]);
        return response()->json(['data'=>$html, 'status'=>'success']);
    }

    public function branchChangePassword(Request $req)
    {
        return view('branch/change_password');
    }

    public function PsswordChange(Request $req)
    {

        $user = Session::get('branchsession');

        $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)) {
                // The passwords matches

                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) {
                //Current password and new password are same
                // return redirect()
                //     ->back()
                //     ->with('error', 'New Password cannot be same as your current password. Please choose a different 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('branches')
                    ->where('id', $user->id)
                    ->update($arrayParam);
					return redirect('/branch/dashboard')->with(['message' => 'Password Updated Successfully', 'alert-type' => 'success']);
            }
            //Change Password
    }

    public function branchAjaxReport(Request $req){
        $data = array();
        $branch_code = Session::get('branchsession')->branch_code;

        $enrData = EnrollmentClient::select('enrolment_clients.*','operators.Operator_Name','operators.Registrar_Code','operators.EA_Code')
        ->join('operators', 'enrolment_clients.Operator_ID','=','operators.Operator_Code')
        ->where('operators.branch_id', $branch_code);
        $enrData = $enrData->get();

        $bankDepositAmt =  Bankupload::join('operators', 'bankuplods.Operator_Code', '=', 'operators.Operator_Code')
                            ->where('operators.branch_id', $branch_code)
                            ->select('bankuplods.amount_credited')
                            ->sum('bankuplods.amount_credited');


        $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);

        $data = [
            'AmountCollected_A' => $AmountCollected_A,
            'AmountCollected_B' => $AmountCollected_B,
            'AmountCollected_BB' => $AmountCollected_BB,
            'AmountCollected_C' => 0,
            'Total_Amount_X'    => $Total_Amount_X,
            '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
        ];

        $viewHtml = view('branch/brachreport_ajax', compact('data'))->render();
        return \Response::json(['status'=>'success','data'=>$viewHtml]);

    }
}
