<?php

namespace App\Http\Controllers\Admin;


use App\Helpers\CustomDateFilter;
use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use App\Http\Resources\CollectedResource;
use App\Http\Resources\CollectGoodLoanResource;
use App\Http\Resources\CollectLateLoanResource;
use App\Http\Resources\LoanResource;
use App\Http\Resources\OverdueResource;
use App\Http\Resources\ShowPaymentResource;
use App\Http\Resources\SummaryResource;
use App\Models\AccReceivableDetails;
use App\Models\AccReceivables;
use App\Models\Loan;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ReportController extends Controller
{

    function __construct()
    {
        $this->middleware('permission:Co Received Report|Cashier Received Report', ['only' => ['DailyPayment']]);
        $this->middleware('permission:Credit Officer Report', ['only' => ['CoReport']]);
        $this->middleware('permission:Borrow Report', ['only' => ['BorrowedReport']]);
        $this->middleware('permission:Loan Pay Off Report', ['only' => ['CompletedReport']]);
        $this->middleware('permission:Overdue Report', ['only' => ['OverdueReport']]);
        $this->middleware('permission:Loan Repayment Report', ['only' => ['CollectionReport']]);
        $this->middleware('permission:Collected Report', ['only' => ['CollectedReport']]);
        $this->middleware('permission:Summary Co Report', ['only' => ['SummaryCoReport']]);
        $this->middleware('permission:Collect Good List', ['only' => ['CollectGoodLoan']]);
        $this->middleware('permission:Collect Late List|Collect Write Off List', ['only' => ['CollectLateLoan']]);
        $this->middleware('permission:Daily Report', ['only' => ['DailyReport']]);
        $this->middleware('permission:Loan Arrear Report', ['only' => ['LateReport']]);
    }

    public function DailyPayment(Request $request)
    {
        $per_page = $request->per_page == null?25: $request->per_page;
        $data = AccReceivableDetails::where(function($query) use ($request){
            // $query->whereIn('co_id',Helper::group());
            $query->whereIn('branch_id',Helper::byBranch());
            $query->where('currency_id',Helper::byCurrency());
            $query->whereBetween(DB::raw("DATE_FORMAT(received_date, '%Y-%m-%d')"), $request->date ?? CustomDateFilter::thisDay());
            if(!$request->client_id ==[]) {
                $query->whereIn('client_id',$request->client_id);
            }
            if(!$request->co_id ==[]) {
                $query->whereIn('co_id',$request->co_id);
            }
            if(!$request->status_approve==''){
                $query->where('status',$request->status_approve);
            }
        })
        ->orderby('received_date','desc')
        ->orderby('id','desc');

        if($request->per_page=="ALL" || $request->pagin == 'true') {
            return CollectedResource::collection($data->get());
        } else{
            return CollectedResource::collection($data->paginate($per_page));
        }
    }



    public function CoReport(Request $request)
    {
        $per_page = $request->per_page == null?25: $request->per_page;
        $data = Loan::where(function($query) use ($request){
            // $query->whereIn('co_id',Helper::group());
            $query->whereIn('branch_id',Helper::byBranch());
            $query->where('currency_id',Helper::byCurrency());
            if(!$request->date==[]) {
                $query->whereBetween(DB::raw("DATE_FORMAT(installment_date, '%Y-%m-%d')"), $request->date);
            }
            if(!$request->client_id ==[]) {
                $query->whereIn('client_id',$request->client_id);
            }
            if(!$request->co_id ==[]) {
                $query->whereIn('co_id',$request->co_id);
            }
            if(!$request->loan_status_id ==[]) {
                $query->whereIn('loan_status_id',$request->loan_status_id);
            } else{
                $query->whereIn('loan_status_id',[2,3]);
            }
        });
        if($request->per_page=="ALL" || $request->pagin == 'true'){
            return LoanResource::collection($data->get());
        } else {
            return LoanResource::collection($data->paginate($per_page));
        }
    }



    public function BorrowedReport(Request $request)
    {
        $per_page = $request->per_page == null?25: $request->per_page;
        $data = Loan::where(function($query) use ($request){
            // $query->whereIn('co_id',Helper::group());
            $query->whereIn('branch_id',Helper::byBranch());
            $query->where('currency_id',Helper::byCurrency());
            $query->whereIn('loan_status_id',[2,5]);
            if(!$request->date==[]){
                $query->whereBetween(DB::raw("DATE_FORMAT(installment_date, '%Y-%m-%d')"), $request->date);
            }
            if(!$request->client_id ==[]){
                $query->whereIn('client_id',$request->client_id);
            }
            if(!$request->co_id ==[]){
                $query->whereIn('co_id',$request->co_id);
            }
        });
        if($request->per_page=="ALL" || $request->pagin == 'true') {
            return LoanResource::collection($data->get());
        } else {
            return LoanResource::collection($data->paginate($per_page));
        }
    }


    public function CompletedReport(Request $request)
    {
        $per_page = $request->per_page == null?25: $request->per_page;
        $data = Loan::where(function($query) use ($request){
            // $query->whereIn('co_id',Helper::group());
            $query->whereIn('branch_id',Helper::byBranch());
            $query->where('currency_id',Helper::byCurrency());
            $query->where('loan_status_id',3);
            if(!$request->date==[]){
                $query->whereBetween(DB::raw("DATE_FORMAT(completed_date, '%Y-%m-%d')"), $request->date);
            }
            if(!$request->client_id ==[]){
                $query->whereIn('client_id',$request->client_id);
            }
            if(!$request->co_id ==[])
            {
                $query->whereIn('co_id',$request->co_id);
            }
        });
        if($request->per_page=="ALL" || $request->pagin == 'true'){
            return LoanResource::collection($data->get());
        } else {
            return LoanResource::collection($data->paginate($per_page));
        }
    }


    public function OverdueReport(Request $request)
    {
        $per_page = $request->per_page == null?25: $request->per_page;
        $data = AccReceivables::select(
            "acc_receivables.*",
            DB::raw('Max(payment_date) as max_payment')
        )
        ->where(function($query) use ($request){
            // $query->whereIn('co_id',Helper::group());
            $query->whereIn('branch_id',Helper::byBranch());
            $query->where('currency_id',Helper::byCurrency());
            if(!$request->client_id ==[]){
                $query->whereIn('client_id',$request->client_id);
            }
            if(!$request->co_id ==[]) {
                $query->whereIn('co_id',$request->co_id);
            }
        })
        ->whereHas('loan', function ($query){
            $query->where('loan_status_id',2);
        })
        ->groupBy('loan_id')
        ->having('max_payment','<',date('Y-m-d'));
        if($request->per_page=="ALL") {
            return OverdueResource::collection($data->get());
        } else {
            return OverdueResource::collection($data->paginate($per_page));
        }
    }

    public function CollectionReport(Request $request)
    {
        $per_page = $request->per_page == null?25: $request->per_page;
        $data = AccReceivables::where(function($query) use ($request){
            // $query->whereIn('co_id',Helper::group());
            $query->whereIn('branch_id',Helper::byBranch());
            $query->where('currency_id',Helper::byCurrency());
            $query->whereIn('payment_status_id',[2,3]);
            if(!$request->date==[]) {
                $query->whereBetween(DB::raw("DATE_FORMAT(payment_date, '%Y-%m-%d')"), $request->date);
            }
            if(!$request->client_id ==[]){
                $query->whereIn('client_id',$request->client_id);
            }
            if(!$request->co_id ==[])
            {
                $query->whereIn('co_id',$request->co_id);
            }
        });
        if($request->per_page=="ALL" || $request->pagin == 'true') {
            return ShowPaymentResource::collection($data->get());
        } else{
            return ShowPaymentResource::collection($data->paginate($per_page));
        }
    }



    public function CollectedReport(Request $request)
    {
        $per_page = $request->per_page == null?25: $request->per_page;
        $data = AccReceivableDetails::where(function($query) use ($request){
            // $query->whereIn('co_id',Helper::group());
            $query->whereIn('branch_id',Helper::byBranch());
            $query->where('currency_id',Helper::byCurrency());
            if(!$request->date==[]){
                $query->whereBetween(DB::raw("DATE_FORMAT(received_date, '%Y-%m-%d')"), $request->date);
            }
            if(!$request->client_id ==[]){
                $query->whereIn('client_id',$request->client_id);
            }
            if(!$request->co_id ==[]){
                $query->whereIn('co_id',$request->co_id);
            }
        });
        if($request->per_page=="ALL" || $request->pagin == 'true') {
            return CollectedResource::collection($data->get());
        } else {
            return CollectedResource::collection($data->paginate($per_page));
        }
    }



    public function SummaryCoReport(Request $request)
    {
        $per_page = $request->per_page == null?25: $request->per_page;
        $data = User::where('type',2)
        // ->whereIn('id',Helper::group())
        ->where('status',1)
        ->where(function($query) use($request){
            if(!$request->co_id==[]){
                $query->whereIn('id',$request->co_id);
            }
        });
        if($request->per_page=="ALL" || $request->pagin == 'true') {
            return SummaryResource::collection($data->get());
        } else {
            return SummaryResource::collection($data->paginate($per_page));
        }
    }



    public function funGroupAccReceivable(Request $request)
    {
        $data = AccReceivables::where(function($query) use($request) {
            // $query->whereIn('co_id',Helper::group());
            $query->whereIn('branch_id',Helper::byBranch());
            $query->where('currency_id',Helper::byCurrency());
            $query->whereIn('payment_status_id',[2,3]);
            $query->where(DB::raw("DATE_FORMAT(payment_date, '%Y-%m-%d')"),'<=',date('Y-m-d'));
            if(!$request->co_id ==[]){
                $query->whereIn('co_id',$request->co_id);
            }
            if(!$request->client_id ==[]){
                $query->whereIn('client_id',$request->client_id);
            }
            if(!$request->village_id ==[]){
                $query->whereHas('client',function($vil) use($request){
                    $vil->whereIn('village_id',$request->village_id);
                });
            }
        })
        ->whereHas('loan',function($query) use($request) {
            $query->whereIn('loan_status_id',[2,5]);
            $query->where('client_type',$request->client_type);
        })
        ->orderBy('payment_date','asc')
        ->orderBy('id','asc')
        ->groupby('loan_id');
        return $data;
    }

    public function CollectGoodLoan(Request $request)
    {
        $per_page  = $request->per_page == null?25: $request->per_page;
        $group_acc = $this->funGroupAccReceivable($request)->get();
        $acc_today = $group_acc->where('payment_date',date('Y-m-d'))->pluck('id');
        $data = AccReceivables::whereIn('id',$acc_today);

        if($request->per_page=="ALL" || $request->pagin == 'true') {
            return CollectGoodLoanResource::collection($data->get());
        } else{
            return CollectGoodLoanResource::collection($data->paginate($per_page));
        }
    }

    public function CollectLateLoan(Request $request)
    {
        $per_page = $request->per_page == null?25: $request->per_page;
        $data = $this->funGroupAccReceivable($request)->where('payment_date','<',date('Y-m-d'));
        if($request->per_page=="ALL" || $request->pagin == 'true') {
            return CollectLateLoanResource::collection($data->get());
        } else{
            return CollectLateLoanResource::collection($data->paginate($per_page));
        }
    }

    public function DailyReport(Request $request)
    {
        return $this->CollectGoodLoan($request);
    }

    public function ExportDaily(Request $request)
    {
        // $data = $this->DailyReport($request);
        // $json_encode_lead = json_encode($data);
        // $json_decode_lead = json_decode($json_encode_lead);
        // return Excel::download(new ExportDaily($json_decode_lead),'ExportDaily.xlsx');
    }

    public function LateReport(Request $request)
    {
        return $this->CollectLateLoan($request);
    }



}
