<?php

namespace App\Http\Controllers;

use App\DataTables\AuditTrailClientDatatable;
use App\DataTables\CreditAnalyst\ApplicantOverviewDataTable;
use App\DataTables\InitialRejectDatatable;
use App\DataTables\AuditTrailDatatable;
use App\NewFinancialPerformance;
use App\UserDetails;
use App\Users;
use App\OperationsModel;
use App\MachineUsedModel;
use App\AddtionalMachineModel;
use App\ProductionLevelsModel;
use App\DirectorsModel;
use App\IssuesResponse;
use App\CreditHistoryModel;
use Illuminate\Support\Facades\Hash;
use App\ProductPackagingModel;
use App\RejectedAppMove;
use App\KpiModel;
use App\AdminModel;
use App\DataTables\ApplicationAssignments;
use App\DataTables\AllReject;
use App\DataTables\PaletteCompletedDataTable;
use App\DataTables\ApprovedAppDataTable;
use App\AcceptedOfferLetter;
use App\DirectionalSketch;
use App\EsrmReport;
use App\FyepApplication;
use App\IrrevocableInstruction;
use App\OperatingPermit;
use App\RequestFacility;
use App\UpfrontPayment;
use App\FinancialRatios;
use App\AppReview;
use http\Client\Curl\User;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
use App\Mail\RejectApplicationMail;
use App\Mail\QualifiedApplicationMail;
use App\Mail\ApprovedApplicationMail;
use App\Mail\RejectedApplicationMail;
use App\Mail\FYEIApplicationAssignment;
use App\Mail\FYEIApplicationAssignments;
use App\BankMomo;
use App\BusRegs;
use App\HistoricalFinancial;
use App\License;
use App\Pitchdeck;
use App\FinancialPerformanceModel;
use App\OperatingPersonnelModel;
use App\EvaluationSheet;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\DataTables\DashboardTableDataTable;
use App\DataTables\StartedApplicationDataTable;
use App\DataTables\CompletedApplicationDataTable;
use App\DataTables\UnderReviewApplicationDataTable;
use App\DataTables\RejectedDataTable;
use App\DataTables\ReviewedApplicationDataTable;
use App\DataTables\CreditAnalyst\CreditUnderAsess;
use App\DataTables\CreditAnalyst\CreditUnderInterview;
use App\DataTables\CreditAnalyst\CreditAnalystDashboard;
use App\DataTables\ProjectAsistant\ProjectAnalystDashboard;
use App\DataTables\ProjectAsistant\ProjectUnderAsess;
use App\DataTables\ProjectAnalystEvaluation;
use App\DataTables\CreditAnalystAssessment;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
// use PDF;

class AdminController extends Controller
{
    public function index()
    {
        return view('admin.index');
    }


    public function login(Request $r)
    {
        $email = $r->email;
        $password = $r->password;

        $credentials = $r->only('email', 'password');
        Auth::shouldUse('adminguard');
        $login = Auth::attempt($credentials);
        if ($login) {
            $rr = AdminModel::where('email', $email)->first();
            session(['adminid' => $rr->id]);
            session(['adminname' => $rr->name]);

            session(['adminrole' => $rr->role]);

            $role = '';

            if ($rr->role === '1') {
                $role = 'Super Admin';
            }

            if ($rr->role === '2') {
                $role = 'Project Analyst';
            }

            if ($rr->role === '3') {
                $role = 'Credit Analyst';
            }

            $this->logActivity('Login', $role, 'Login', $rr->name . ' Logged In', '', $rr->id);

            if ($rr->role == 1) {
                return redirect()->route('admin.dashboard');
            } elseif ($rr->role == 2) {
                return redirect()->route('admin.projectanalyst.dashboard');
            } elseif ($rr->role == 3) {
                return redirect()->route('admin.creditanalyst.dashboard');
            }



            // return redirect()->route('admin.dashboard');
        } else {
            return redirect()->back()->with('error', 'Invalid Email/Password!');
        }
    }

    public function dashboard(DashboardTableDataTable $dt)
    {
        $totalapp = Users::count();
        $totalstarttt = Users::whereNull('is_disqualified')->count();
        $totalstartt = Users::where('is_disqualified', 0)->where('is_application_complete', 0)->count();
        $totalcomp = Users::where('is_disqualified', 0)->where('is_application_complete', 1)->count();
        $totalrev = Users::where('is_disqualified', 2)->count();
        $totalrevi = Users::where('application_status', 'Completed Review')->count();
        $totalrej = Users::where('is_disqualified', 1)->count();
        $totalrejected = RejectedAppMove::where('is_disqualified', '3')->count();
        $totalstart = $totalstarttt + $totalstartt;
        $countqa = 0;
        $countunrev = 0;
        $countcomrev = 0;

        $data = [
            'totalapp' => $totalapp,
            'totalstart' => $totalstart,
            'totalcomp' => $totalcomp,
            'totalrevi' => $totalrevi,
            'totalrev' => $totalrev,
            'qb' => $countqa,
            'totalrejected' => $totalrejected,
        ];

        // session(['start' => $totalstart]);
        session(['comp' => $countqa]);
        session(['rev' => $totalrev]);
        session(['revi' => $totalrevi]);
        session(['rej' => $totalrej]);


        return $dt->render('admin.dashboard', $data);
    }

    public function startreview($id)
    {
        // auth()->guard('adminguard')->user()->logAdmin("Started Evaluating Applicant", 'Started Evaluation', 'Evaluating applicant: '.$userstat->name);

        return redirect()->route('admin.evaluate.app', $id);
        // return back()->with('success','Applicant Review Started');
    }


    public function allreject(AllReject $dt)
    {
        return $dt->render('admin.viewallreject');
    }

    public function viewapplication($id)
    {
        $userdetails = DB::table('users')->where('user_id', $id)->first();
        Log::info('user app: ' . json_encode($userdetails));
        $cash_collaterals = DB::table('cash_collaterals')->where('user_id', $id)->get();
        $credit_facility_details = DB::table('credit_facility_details')->where('user_id', $id)->get();
        $credit_facility_other_details = DB::table('credit_facility_other_details')->where('user_id', $id)->get();
        $facility_requests = DB::table('facility_requests')->where('user_id', $id)->get();
        $key_management_personnels = DB::table('key_management_personnels')->where('user_id', $id)->get();
        $major_product_lines = DB::table('major_product_lines')->where('user_id', $id)->get();
        $non_cash_collaterals = DB::table('non_cash_collaterals')->where('user_id', $id)->get();
        $ownership_applicants = DB::table('ownership_applicants')->where('user_id', $id)->get();
        $historical_financial = DB::table('historical_financial')->where('user_id', $id)->get();
        $industrytype = DB::table('business_types')->where('id', $userdetails->business_type)->first();
        Log::info('user industry: ' . json_encode($industrytype));
        $interview = DB::table('application_review')->where('app_id', $id)->latest()->first();

        $application_fund = $userdetails->application_funds ? $userdetails->application_funds : null;

        $financial_data = NewFinancialPerformance::query()->where('user_id', $id)->first();

        $id_cards = $financial_data == null ? null : $financial_data->getIDCards($id);

        $management_account = $financial_data == null ? null : $financial_data->getManagementAccount($id);

        $permits = $financial_data == null ? null : $financial_data->getPermits($id);

        $business_registration_documents = $financial_data == null ? null : $financial_data->getBusinessRegistrationDocuments($id);

        $bank_statements = $financial_data == null ? null : $financial_data->getBankStatements($id);

        $log_user = UserDetails::query()->where('id', $userdetails->user_id)->first();

        auth()->guard('adminguard')->user()->logAdmin("View Application Form", 'View Application Form', 'Viewed application form of Applicant: ' . $log_user->name, $log_user->id);


        $data = [
            'log_user' => $log_user,
            'userdetails' => $userdetails,
            'cash_collaterals' => $cash_collaterals,
            'credit_facility_details' => $credit_facility_details,
            'credit_facility_other_details' => $credit_facility_other_details,
            'facility_requests' => $facility_requests,
            'key_management_personnels' => $key_management_personnels,
            'major_product_lines' => $major_product_lines,
            'non_cash_collaterals' => $non_cash_collaterals,
            'ownership_applicants' => $ownership_applicants,
            'industrytype' => $industrytype->name,
            'application_fund' => $application_fund,
            'financial_data' => $financial_data ?? null,
            'id_cards' => $id_cards ?? null,
            'management_account' => $management_account ?? null,
            'permits' => $permits ?? null,
            'bank_registration_documents' => $business_registration_documents ?? null,
            'bank_statements' => $bank_statements ?? null,
            'historical_financial' => $historical_financial ?? null,
            'interview' => $interview->interviewtime ?? null,

        ];
        return view('admin.viewapplication', $data);
    }

    public function printApplication($id)
    {
        $userdetails = DB::table('users')->where('user_id', $id)->first();
        Log::info('user app: ' . json_encode($userdetails));
        $cash_collaterals = DB::table('cash_collaterals')->where('user_id', $id)->get();
        $credit_facility_details = DB::table('credit_facility_details')->where('user_id', $id)->get();
        $credit_facility_other_details = DB::table('credit_facility_other_details')->where('user_id', $id)->get();
        $facility_requests = DB::table('facility_requests')->where('user_id', $id)->get();
        $key_management_personnels = DB::table('key_management_personnels')->where('user_id', $id)->get();
        $major_product_lines = DB::table('major_product_lines')->where('user_id', $id)->get();
        $non_cash_collaterals = DB::table('non_cash_collaterals')->where('user_id', $id)->get();
        $ownership_applicants = DB::table('ownership_applicants')->where('user_id', $id)->get();
        $historical_financial = DB::table('historical_financial')->where('user_id', $id)->get();
        $industrytype = DB::table('business_types')->where('id', $userdetails->business_type)->first();
        Log::info('user industry: ' . json_encode($industrytype));
        $interview = DB::table('application_review')->where('app_id', $id)->latest()->first();

        $application_fund = $userdetails->application_funds ? $userdetails->application_funds : null;

        $financial_data = NewFinancialPerformance::query()->where('user_id', $id)->first();

        $id_cards = $financial_data == null ? null : $financial_data->getIDCards($id);

        $management_account = $financial_data == null ? null : $financial_data->getManagementAccount($id);

        $permits = $financial_data == null ? null : $financial_data->getPermits($id);

        $business_registration_documents = $financial_data == null ? null : $financial_data->getBusinessRegistrationDocuments($id);

        $bank_statements = $financial_data == null ? null : $financial_data->getBankStatements($id);

        $log_user = UserDetails::query()->where('id', $userdetails->user_id)->first();

        auth()->guard('adminguard')->user()->logAdmin("Print Application Form", 'Print Application Form', 'Printed application form of Applicant: ' . $log_user->name, $log_user->id);


        $data = [
            'log_user' => $log_user,
            'userdetails' => $userdetails,
            'cash_collaterals' => $cash_collaterals,
            'credit_facility_details' => $credit_facility_details,
            'credit_facility_other_details' => $credit_facility_other_details,
            'facility_requests' => $facility_requests,
            'key_management_personnels' => $key_management_personnels,
            'major_product_lines' => $major_product_lines,
            'non_cash_collaterals' => $non_cash_collaterals,
            'ownership_applicants' => $ownership_applicants,
            'industrytype' => $industrytype->name,
            'application_fund' => $application_fund,
            'financial_data' => $financial_data ?? null,
            'id_cards' => $id_cards ?? null,
            'management_account' => $management_account ?? null,
            'permits' => $permits ?? null,
            'bank_registration_documents' => $business_registration_documents ?? null,
            'bank_statements' => $bank_statements ?? null,
            'historical_financial' => $historical_financial ?? null,
            'interview' => $interview->interviewtime ?? null,

        ];
        $dfname = 'FYEI_Application_' . Str::slug($userdetails->applicant_name, '_') . '_' . time() . '.pdf';


        $pdf = \PDF::loadView('admin.print-application', $data);

        return $pdf->stream($dfname);
        // return view('admin.print-application', $data);
    }


    public function startedapp(StartedApplicationDataTable $dt)
    {
        return $dt->render('admin.startedapplication');
    }

    public function completedapp(CompletedApplicationDataTable $dt)
    {
        auth()->guard('adminguard')->user()->logAdmin("View Qualified Applicant Table", 'View Qualified Applicant Table', 'Viewing all Qualified Applicant datatable');

        return $dt->render('admin.completedapplication');
    }

    public function underreviewapp(UnderReviewApplicationDataTable $dt)
    {
        auth()->guard('adminguard')->user()->logAdmin("View Under Review Applicant Table", 'View Under Review Applicant Table', 'Viewing all Under Review Applicant datatable');

        return $dt->render('admin.underreviewappapplication');
    }

    public function reviewedapp(ReviewedApplicationDataTable $dt)
    {
        return $dt->render('admin.reviewedappapplication');
    }


    public function completereview($id, Request $r)
    {
        $userstat = UserDetails::where('id', $id)->first();
        $comment = $r->comment;
        $time = $r->interviewtime;
        $data = [
            'name' => $userstat->name,
            'comment' => $comment,
            'time' => $time
        ];
        $adminidd = Session::get('adminid');
        $rev = AppReview::create([
            'adminid' => $adminidd,
            'app_id' => $id,
            'comment' => $comment,
            'interviewtime' => $time,
            'status' => 'Qualified for Interview Stage',
        ]);
        Mail::to($userstat->email)->send(new QualifiedApplicationMail($data));
        $changestatus = UserDetails::where('id', $id)->update([
            'application_status' => 'Completed Review',
        ]);

        return redirect()->route('admin.underreview.app');
    }


    public function logout()
    {

        auth()->guard('adminguard')->user()->logAdmin("Log Out", 'Log Out', 'Logged Out');

        Auth::guard('adminguard')->logout();

        return redirect()->route('admin.index');
    }

    public function grantapp(DashboardTableDataTable $dt)
    {

        return $dt->render('admin.grantapp');
    }

    public function pageanalytics()
    {
        return view('admin.analytics');
    }

    public function rejectapp($id, Request $r)
    {
        $comment = $r->comment;
        $getapp = UserDetails::where('id', $id)->first();
        $data = [
            'name' => $getapp->name,
            'comment' => $comment,
        ];
        $adminidd = Session::get('adminid');
        $rev = AppReview::create([
            'adminid' => $adminidd,
            'app_id' => $id,
            'comment' => $comment,
            'status' => 'Rejected on Stage 1',
        ]);
        Mail::to($getapp->email)->send(new RejectedApplicationMail($data));

        $getapp->application_status = 'Rejected';
        $getapp->save();
        return redirect()->route('admin.underreview.app');
    }

    public function showreject(RejectedDatatable $dt)
    {

        auth()->guard('adminguard')->user()->logAdmin("View Rejected Applicant Table", 'View Rejected Applicant Table', 'Viewing all Rejected Applicant datatable');
        return $dt->render('admin.adminrejectedapplication');
    }


    public function paleteCompleted(PaletteCompletedDataTable $dt)
    {
        return $dt->render('admin.palette.completedpalette');
    }



    public function approvegrant($id, Request $r)
    {
        $userstat = UserDetails::where('id', $id)->first();
        $comment = $r->comment;
        $data = [
            'name' => $userstat->name,
            'comment' => $comment,
        ];
        $adminidd = Session::get('adminid');
        $rev = AppReview::create([
            'adminid' => $adminidd,
            'app_id' => $id,
            'comment' => $comment,
            'status' => 'Final Approval: Approved',
        ]);
        Mail::to($userstat->email)->send(new ApprovedApplicationMail($data));
        $changestatus = UserDetails::where('id', $id)->update([
            'application_status' => 'Approved Application',
        ]);
        return back()->with('success', 'Application Approved successfully');
    }

    public function rejectgrant($id, Request $r)
    {
        $userstat = UserDetails::where('id', $id)->first();
        $comment = $r->comment;
        $data = [
            'name' => $userstat->name,
            'comment' => $comment,
        ];
        $adminidd = Session::get('adminid');
        $rev = AppReview::create([
            'adminid' => $adminidd,
            'app_id' => $id,
            'comment' => $comment,
            'status' => 'Final Approval: Rejected',
        ]);
        Mail::to($userstat->email)->send(new RejectApplicationMail($data));
        $changestatus = UserDetails::where('id', $id)->update([
            'application_status' => 'Rejected',
        ]);
        return back()->with('success', 'Application Rejected successfully');
    }

    public function approvedapp(ApprovedAppDataTable $dt)
    {
        return $dt->render('admin.approvedappapplication');
    }


    public function edituser($id)
    {
        $user = AdminModel::where('id', $id)->first();

        $data = [
            'user' => $user,
        ];

        return view('admin.users.edit', $data);
    }


    public function showcreditdash(CreditAnalystDashboard $dt)
    {
        // return 'lolo';
        $totalapp = Users::where('creditanalyst_id', auth()->guard('adminguard')->user()->id)->count();
        $totalstart = Users::whereNull('is_disqualified')->count();
        $totalcomp = Users::where('is_disqualified', 0)->count();
        $totalrev = Users::where('application_status', 'Under Assessment')->where('creditanalyst_id', auth()->guard('adminguard')->user()->id)->orWhere('application_status', 'Issues Detected')->count();
        $totalrevi = Users::where('application_status', 'Completed Review')->where('creditanalyst_id', auth()->guard('adminguard')->user()->id)->count();
        $totalrej = Users::where('is_disqualified', 1)->count();
        $intercount = Users::where('creditanalyst_id', auth()->guard('adminguard')->user()->id)->where('application_status', 'Moved To Interview Stage')->count();
        $countqa = 0;

        $data = [
            'intercount' => $intercount,
            'totalapp' => $totalapp,
            'totalstart' => $totalstart,
            'totalcomp' => $totalcomp,
            'totalrevi' => $totalrevi,
            'totalrev' => $totalrev,
            'qb' => $countqa
        ];

        // session(['start' => $totalstart]);
        session(['comp' => $countqa]);
        session(['rev' => $totalrev]);
        session(['revi' => $totalrevi]);
        session(['rej' => $totalrej]);


        return $dt->render('admin.creditanalyst.dashboard', $data);
    }

    // applicant overview page
    public function  applicantOverview(ApplicantOverviewDataTable  $dt)
    {
        $totalapp = Users::where('creditanalyst_id', auth()->guard('adminguard')->user()->id)->count();
        $totalstart = Users::whereNull('is_disqualified')->count();
        $totalcomp = Users::where('is_disqualified', 0)->count();
        $totalrev = Users::where('application_status', 'Under Assessment')->where('creditanalyst_id', auth()->guard('adminguard')->user()->id)->orWhere('application_status', 'Issues Detected')->count();
        $totalrevi = Users::where('application_status', 'Completed Review')->where('creditanalyst_id', auth()->guard('adminguard')->user()->id)->count();
        $totalrej = Users::where('is_disqualified', 1)->count();
        $intercount = Users::where('creditanalyst_id', auth()->guard('adminguard')->user()->id)->where('application_status', 'Moved To Interview Stage')->count();
        $countqa = 0;

        $data =
            [
                'intercount' => $intercount,
                'totalapp' => $totalapp,
                'totalstart' => $totalstart,
                'totalcomp' => $totalcomp,
                'totalrevi' => $totalrevi,
                'totalrev' => $totalrev,
                'qb' => $countqa
            ];

        // session(['start' => $totalstart]);
        session(['comp' => $countqa]);
        session(['rev' => $totalrev]);
        session(['revi' => $totalrevi]);
        session(['rej' => $totalrej]);

        return $dt->render('admin.creditanalyst.applicantoverview', $data);
    }

    //edit applicant overview
    public function editOver($id)
    {
        $user = Users::where('user_id', $id)->first();
        $oppe = OperationsModel::where('user_id', $id)->first();
        $score = EvaluationSheet::where('user_id', $id)->first();
        $assess = IssuesResponse::where('user_id', $id)->get();
        $industrytype = DB::table('business_types')->where('id', $user->business_type)->first();
        $reason = AppReview::where('app_id', $id)->first();


        $userdetails = DB::table('users')->where('user_id', $id)->first();
        $cash_collaterals = DB::table('cash_collaterals')->where('user_id', $id)->get();
        $credit_facility_details = DB::table('credit_facility_details')->where('user_id', $id)->get();
        $credit_facility_other_details = DB::table('credit_facility_other_details')->where('user_id', $id)->get();
        $facility_requests = DB::table('facility_requests')->where('user_id', $id)->get();
        $key_management_personnels = DB::table('key_management_personnels')->where('user_id', $id)->get();
        $major_product_lines = DB::table('major_product_lines')->where('user_id', $id)->get();
        $non_cash_collaterals = DB::table('non_cash_collaterals')->where('user_id', $id)->get();
        $ownership_applicants = DB::table('ownership_applicants')->where('user_id', $id)->get();
        $historical_financial = DB::table('historical_financial')->where('user_id', $id)->get();

        $application_fund = $userdetails->application_funds ? $userdetails->application_funds : null;

        $financial_data = NewFinancialPerformance::query()->where('user_id', $id)->first();

        $id_cards = $financial_data == null ? null : $financial_data->getIDCards($id);

        $management_account = $financial_data == null ? null : $financial_data->getManagementAccount($id);

        $permits = $financial_data == null ? null : $financial_data->getPermits($id);

        $business_registration_documents = $financial_data == null ? null : $financial_data->getBusinessRegistrationDocuments($id);

        $bank_statements = $financial_data == null ? null : $financial_data->getBankStatements($id);

        $log_user = UserDetails::query()->where('id', $userdetails->user_id)->first();

        $data =
            [
                'assess' => $assess,
                'user' => $user,
                'oppe' => $oppe,
                'reason' => $reason,
                'score' => $score->total,
                'eva' => $score,
                'log_user' => $log_user,
                'industrytype' => $industrytype->name,
                'userdetails' => $userdetails,
                'cash_collaterals' => $cash_collaterals,
                'credit_facility_details' => $credit_facility_details,
                'credit_facility_other_details' => $credit_facility_other_details,
                'facility_requests' => $facility_requests,
                'key_management_personnels' => $key_management_personnels,
                'major_product_lines' => $major_product_lines,
                'non_cash_collaterals' => $non_cash_collaterals,
                'ownership_applicants' => $ownership_applicants,
                'application_fund' => $application_fund,
                'financial_data' => $financial_data ?? null,
                'id_cards' => $id_cards ?? null,
                'management_account' => $management_account ?? null,
                'permits' => $permits ?? null,
                'bank_registration_documents' => $business_registration_documents ?? null,
                'bank_statements' => $bank_statements ?? null,
                'historical_financial' => $historical_financial ?? null
            ];
        return view('admin.evaluation.editover', $data);
    }

    // update applicant overview
    public function updateApplicantOverview(Request $r, $id)
    {
        Users::find($id)->update([
            "background" => $r->background,
            "customer_base" => $r->customer_base,
            "investment_plan" => $r->investment_plan,
        ]);
        return back()->with('success', 'Application overview update');
    }
    // View applicant overview
    public function viewApplicantOverview($id)
    {
        $userdetails = DB::table('users')->where('user_id', $id)->first();

        $log_user = UserDetails::query()->where('id', $userdetails->user_id)->first();

        auth()->guard('adminguard')->user()->logAdmin("View Application Form", 'View Application Form', 'Viewed application form of Applicant: ' . $log_user->name, $log_user->id);


        $data = [
            'log_user' => $log_user,
            'userdetails' => $userdetails
        ];
        return view('admin.creditanalyst.viewapplicantoverview', $data);
    }
    // download applicant overview
    public function downloadApplicantOverview(Request $r, $id)
    {
        $userdetails = DB::table('users')->where('user_id', $id)->first();
        $data = [
            'userdetails' => $userdetails
        ];
        $pdf = \PDF::loadView('admin.creditanalyst.downloadoverview', $data);
        return $pdf->download('user_' . $id . '_overview.pdf');
    }

    public function showprojectdash(ProjectAnalystDashboard $dt)
    {
        // return 'lolo';
        $totalapp = Users::where('projectanalyst_id', auth()->guard('adminguard')->user()->id)->count();
        $totalstart = Users::whereNull('is_disqualified')->count();
        $totalcomp = Users::where('is_disqualified', 0)->count();
        $totalrev = Users::where('application_status', 'Under Review')->orWhere('application_status', 'Under Assessment')->orWhere('application_status', 'Issues Detected')->count();
        $totalrevi = Users::where('application_status', 'Completed Review')->count();
        $totalrej = Users::where('is_disqualified', 1)->count();
        $intercount = Users::where('projectanalyst_id', auth()->guard('adminguard')->user()->id)->where('application_status', 'Moved To Interview Stage')->count();

        $countqa = 0;
        $countunrev = 0;
        $countcomrev = 0;

        $data = [
            'intercount' => $intercount,
            'totalapp' => $totalapp,
            'totalstart' => $totalstart,
            'totalcomp' => $totalcomp,
            'totalrevi' => $totalrevi,
            'totalrev' => $totalrev,
            'qb' => $countqa
        ];

        // session(['start' => $totalstart]);
        session(['comp' => $countqa]);
        session(['rev' => $totalrev]);
        session(['revi' => $totalrevi]);
        session(['rej' => $totalrej]);


        return $dt->render('admin.projectanalyst.dashboard', $data);
    }


    public function showprojectevalution(ProjectAnalystEvaluation $dt)
    {
        return $dt->render('admin.projectanalyst.evaluation');
    }


    public function showcreditassessment(CreditAnalystAssessment $dt)
    {
        return $dt->render('admin.creditanalyst.assessindex');
    }


    public function auditTrails(AuditTrailDatatable $datatable)
    {
        auth()->guard('adminguard')->user()->logAdmin("View Admin Audit Trail Table", 'View Admin Audit Trail Table', 'Viewing Admin Audit Trail datatable');
        return $datatable->render('admin.audit');
    }


    public function auditTrailsClients(AuditTrailClientDatatable $datatable)
    {
        auth()->guard('adminguard')->user()->logAdmin("View Client Audit Trail Table", 'View Client Audit Trail Table', 'Viewing Client Audit Trail datatable');
        return $datatable->render('admin.audit_client');
    }

    public function showchange()
    {
        // $id = Session::get('adminid');
        // $rr = AdminModel::where('id',$id)->first();
        // $data =[
        //   'admin'=>$rr
        // ];
        auth()->guard('adminguard')->user()->logAdmin("View change password Table", 'View change password page', 'Viewing change password page');
        return view('admin.changepass');
    }

    public function passwordchange(Request $r)
    {
        $curr = $r->cur_pass;
        $new = $r->new_pass;
        $con = $r->con_pass;
        $id = Session::get('adminid');
        $rr = AdminModel::where('id', $id)->first();

        $cc = Hash::check($curr, $rr->password);
        if ($cc == false) {
            return back()->with('error', 'Current Password Did not match our records!');
        }

        if ($new !== $con) {
            return back()->with('error', 'New Passwords Do not match!');
        }

        if ($cc == true && $new == $con) {
            // change password
            $rr->password = bcrypt($new);
            $rr->save();
            return redirect()->route('admin.dashboard')->with('success', 'Password Changed successfully');
        }
    }


    public function initialreject(InitialRejectDatatable $dt)
    {
        auth()->guard('adminguard')->user()->logAdmin("View Initial Reject Table", 'View Initial Reject', 'Admin is View Initial Reject Table');
        return $dt->render('admin.initialreject');
    }

    public function logexport()
    {
        auth()->guard('adminguard')->user()->logAdmin("Export table", 'Exporting table', 'Admin is exporting table content');
        return 'success';
    }



    public function showrejectedappl($id)
    {
        $userdetails = DB::table('rejected_application')->where('userid', $id)->first();
        $cash_collaterals = DB::table('cash_collaterals')->where('user_id', $id)->get();
        $credit_facility_details = DB::table('credit_facility_details')->where('user_id', $id)->get();
        $credit_facility_other_details = DB::table('credit_facility_other_details')->where('user_id', $id)->get();
        $facility_requests = DB::table('facility_requests')->where('user_id', $id)->get();
        $key_management_personnels = DB::table('key_management_personnels')->where('user_id', $id)->get();
        $major_product_lines = DB::table('major_product_lines')->where('user_id', $id)->get();
        $non_cash_collaterals = DB::table('non_cash_collaterals')->where('user_id', $id)->get();
        $ownership_applicants = DB::table('ownership_applicants')->where('user_id', $id)->get();
        $historical_financial = DB::table('historical_financial')->where('user_id', $id)->get();
        $industrytype = DB::table('business_types')->where('id', $userdetails->business_type)->first();

        $application_fund = $userdetails->application_funds ? $userdetails->application_funds : null;

        $financial_data = NewFinancialPerformance::query()->where('user_id', $id)->first();

        $id_cards = $financial_data == null ? null : $financial_data->getIDCards($id);

        $management_account = $financial_data == null ? null : $financial_data->getManagementAccount($id);

        $permits = $financial_data == null ? null : $financial_data->getPermits($id);

        $business_registration_documents = $financial_data == null ? null : $financial_data->getBusinessRegistrationDocuments($id);

        $bank_statements = $financial_data == null ? null : $financial_data->getBankStatements($id);

        $log_user = RejectedAppMove::query()->where('userid', $userdetails->userid)->first();

        auth()->guard('adminguard')->user()->logAdmin("View Application Form", 'View Application Form', 'Viewed application form of Applicant: ' . $log_user->name, $log_user->id);


        $data = [
            'log_user' => $log_user,
            'userdetails' => $userdetails,
            'cash_collaterals' => $cash_collaterals,
            'credit_facility_details' => $credit_facility_details,
            'credit_facility_other_details' => $credit_facility_other_details,
            'facility_requests' => $facility_requests,
            'key_management_personnels' => $key_management_personnels,
            'major_product_lines' => $major_product_lines,
            'non_cash_collaterals' => $non_cash_collaterals,
            'ownership_applicants' => $ownership_applicants,
            'industrytype' => $industrytype->name,
            'application_fund' => $application_fund,
            'financial_data' => $financial_data ?? null,
            'id_cards' => $id_cards ?? null,
            'management_account' => $management_account ?? null,
            'permits' => $permits ?? null,
            'bank_registration_documents' => $business_registration_documents ?? null,
            'bank_statements' => $bank_statements ?? null,
            'historical_financial' => $historical_financial ?? null,
            'interview' => null

        ];
        // return $data;
        return view('admin.rejectviewapplication', $data);
    }



    public function fyeiassignments(ApplicationAssignments $dt)
    {
        return $dt->render('admin.assignments.index');
    }


    public function reassign(Users $id, Request $r)
    {
        if ($r->proj !== $id->projectanalyst_id) {
            if ($id->projectanalyst_id == null) {
                // increment new admin count
                $admin = AdminModel::where('id', $r->proj)->first();
                // $newcount = $admin->appcount + 1;
                // $admin->update([
                //   'appcount'=>$newcount
                // ]);

                $id->update([
                    'projectanalyst_id' => $r->proj
                ]);
                $data = [
                    'proj' => $admin->name ?? null,
                    'appname' => $id->applicant_name,
                    'company_name' => $id->company_name,
                ];
                Mail::to($admin->email)->send(new FYEIApplicationAssignment($data));
            } else {
                // reduce count for admin
                $admin = AdminModel::where('id', $id->projectanalyst_id)->first();
                // $newcount = $admin->appcount ==null - 1;
                // $admin->update([
                //   'appcount'=>$newcount
                // ]);


                // // change proj in assess
                // $assess = Assess::where('id',$id->projectanalyst_id)->first();
                // $newcount = $admin->appcount ==null - 1;
                // $admin->update([
                //   'appcount'=>$newcount
                // ]);

                // update proj in issues
                IssuesResponse::where('user_id', $id->user_id)->update([
                    'proj_id' => $r->proj,
                ]);

                // increment new admin count
                // $admin = AdminModel::where('id',$r->proj)->first();
                // $newcount = $admin->appcount + 1;
                // $admin->update([
                //   'appcount'=>$newcount
                // ]);

                $id->update([
                    'projectanalyst_id' => $r->proj
                ]);
                $data = [
                    'proj' => $admin->name ?? null,
                    'appname' => $id->applicant_name,
                    'company_name' => $id->company_name,
                ];
                Mail::to($admin->email)->send(new FYEIApplicationAssignment($data));
            }
        }

        if ($r->credit !== $id->creditanalyst_id) {

            if ($id->creditanalyst_id == null) {
                // increment new admin count
                $admin = AdminModel::where('id', $r->credit)->first();
                // $newcount = $admin->appcount + 1;
                // $admin->update([
                //   'appcount'=>$newcount
                // ]);

                $id->update([
                    'creditanalyst_id' => $r->credit
                ]);

                $data = [
                    'credit' => $admin->name,
                    'appname' => $id->applicant_name,
                    'company_name' => $id->company_name,
                ];



                Mail::to($admin->email)->send(new FYEIApplicationAssignments($data));
            } else {
                // return " reduce count for admin";
                $admin = AdminModel::where('id', $r->credit)->first();
                // $newcount = $admin->appcount - 1;
                // $admin->update([
                //   'appcount'=>$newcount
                // ]);
                // increment new admin count
                // $admin = AdminModel::where('id',$r->credit)->first();
                // $newcount = $admin->appcount + 1;
                // $admin->update([
                //   'appcount'=>$newcount
                // ]);

                $id->update([
                    'creditanalyst_id' => $r->credit
                ]);

                IssuesResponse::where('user_id', $id->user_id)->update([
                    'credit_id' => $r->credit,
                ]);
                // return 'should update';
                $data = [
                    'credit' => $admin->name ?? null,
                    'appname' => $id->applicant_name,
                    'company_name' => $id->company_name,
                ];



                Mail::to($admin->email)->send(new FYEIApplicationAssignments($data));
            }
        }







        return back()->with('success', 'Applicant Ressigned');
    }



    public function creditunderassess(CreditUnderAsess $dt)
    {
        return $dt->render('admin.creditanalyst.underassess');
    }
    public function projunderassess(ProjectUnderAsess $dt)
    {
        return $dt->render('admin.projectanalyst.underassess');
    }

    public function underinterview(CreditUnderInterview $dt)
    {
        return $dt->render('admin.creditanalyst.underinterview');
    }
}
