<?php

namespace App\Http\Controllers;

use App\Models\Area;
use App\Models\BillGenerate;
use App\Models\Client;
use App\Models\CustomerAccount;
use App\Models\Pop;
use App\Models\Reseller;
use App\Models\ResellerArea;
use Carbon\Carbon;
use Illuminate\Http\Request;

class DueClientController extends Controller
{

    public function dueCustomer()
    {
        $resellers = Reseller::list()->where('reseller_type', 'own');
        $start = Carbon::now()->startOfMonth();
        $end = today();
        $yearMonth = getAllMonthAndYearOfBillGenerate();



        $data=[
            'resellers' => $resellers,
            'confday' => config('app.billing_cycle'),
            'start' => $start,
            'end' => $end,
            'yearMonth' => $yearMonth
        ];

        if(globalPermission('payment-bill-by-bill')){
            return view('clients.dueCustomer.monthWisePaymentDue', $data);
        }

        return view('clients.dueCustomer.search', $data);
    }

    public function dueCustomerSearch(Request $request)
    {
        // $clients = Client::with('packages','pop','clientsinfo','customerAccount')->get();

        if($request->from_date != null && $request->to_date != null){
            $start = Carbon::parse($request->from_date)->format('Y-m-d 00:00:00');
            $end = Carbon::parse($request->to_date)->format('Y-m-d 23:59:59');

            if($request->reseller == "all"){
                $resellers = Reseller::list()->where('reseller_type', 'own');
            }else{
                $resellers = Reseller::list()->where('id', $request->reseller);
            }
            if($request->pop == "all"){
                $popes = Pop::whereIn('reseller_id', $resellers->pluck('id'))->get();

                if($request->close_status == 'closed'){
                    $clients  = Client::withTrashed()->with('packages','pop','clientsinfo','customerAccount','subpack','generatedBill')
                                        ->with(['generatedBill' => function ($query) use ($start, $end) {
                                            $query->where('bill_amount','!=','paid_amount')->whereBetween('created_at', [$start, $end]);
                                        }])
                                        ->whereHas('generatedBill', function ($query) use ($start, $end) {
                                            $query->whereBetween('created_at', [$start, $end]);
                                        })
                                        ->whereIn('pop_id', $popes->pluck('id'));
                }else{
                    $clients  = Client::with('packages','pop','clientsinfo','customerAccount','subpack','generatedBill')
                                        ->with(['generatedBill' => function ($query) use ($start, $end) {
                                            $query->where('bill_amount','!=','paid_amount')->whereBetween('created_at', [$start, $end]);
                                        }])
                                        ->whereHas('generatedBill', function ($query) use ($start, $end) {
                                            $query->whereBetween('created_at', [$start, $end]);
                                        })
                                        ->whereIn('pop_id', $popes->pluck('id'));
                }
                // dd($clients->get());
            }else{
                $popes = Pop::where('id',$request->pop)->get();
                if($request->close_status == 'closed'){

                    $clients  = Client::withTrashed()->with('packages','pop','clientsinfo','customerAccount','subpack','generatedBill')
                                        ->with(['generatedBill' => function ($query) use ($start, $end) {
                                            $query->where('bill_amount','!=','paid_amount')->whereBetween('created_at', [$start, $end]);
                                        }])
                                        ->whereHas('generatedBill', function ($query) use ($start, $end) {
                                            $query->whereBetween('created_at', [$start, $end]);
                                        })
                                        ->whereIn('pop_id', $popes->pluck('id'));
                }else{
                    $clients  = Client::with('packages','pop','clientsinfo','customerAccount','subpack','generatedBill')
                                        ->with(['generatedBill' => function ($query) use ($start, $end) {
                                            $query->where('bill_amount','!=','paid_amount')->whereBetween('created_at', [$start, $end]);
                                        }])
                                        ->whereHas('generatedBill', function ($query) use ($start, $end) {
                                            $query->whereBetween('created_at', [$start, $end]);
                                        })
                                        ->whereIn('pop_id', $popes->pluck('id'));
                }
            }
            if($request->billing_cycle != "all"){
                $clients = $clients->where('billing_cycle', $request->billing_cycle);
            }else{
                $clients = $clients;
            }

            if($request->due_type == 'partial_due'){
                $clients = $clients->with(['generatedBill' => function ($query) use ($start, $end) {
                    $query->where('paid_amount', '!=', 0)->whereBetween('created_at', [$start, $end]);
                }]);
                // dd($clients);
            }


            // $clients = $clients->whereIn('id', $due_customer_list->pluck('client_id'))->get();
            $mother_packge_permissin = false;
            if (auth()->user()->hasPermissionTo('show-mother-package')) {
                $mother_packge_permissin = true;
            }

            $sub_package_permission = false;
            if(auth()->user()->hasPermissionTo('show-sub-package')){
                $sub_package_permission = true;
            }
            $new_clients = [];
            if(in_array("all",$request->area) || $request->area == null){

                $new_clients = $clients->get();
            }else{
                $new_clients = $clients->whereHas('clientsinfo', function($q) use($request){
                    $q->whereIn('area', $request->area);
                })->get();
            }
            $type = '';
            if($request->type == 'month'){
                $type = 'month';
            }

            $data=[
                'clients' => $new_clients,
                'areas' => $request->area,
                'sub_package_permission' => $sub_package_permission,
                'mother_packge_permissin' => $mother_packge_permissin,
                'type' => $type
            ];

            return $data;

        }else{

            if($request->reseller == "all"){
                $resellers = Reseller::list()->where('reseller_type', 'own');
            }else{
                $resellers = Reseller::list()->where('id', $request->reseller);
            }
            if($request->pop == "all"){
                $popes = Pop::whereIn('reseller_id', $resellers->pluck('id'))->get();

                if($request->close_status == 'closed'){

                    $clients  = Client::withTrashed()->with('packages','pop','clientsinfo','customerAccount','subpack','generatedBill')
                                     ->whereIn('pop_id', $popes->pluck('id'));
                }else{
                    $clients  = Client::with('packages','pop','clientsinfo','customerAccount','subpack','generatedBill')
                                    ->whereIn('pop_id', $popes->pluck('id'));
                }
                // dd($clients->get());
            }else{
                $popes = Pop::where('id',$request->pop)->get();
                if($request->close_status == 'closed'){

                    $clients  = Client::withTrashed()->with('packages','pop','clientsinfo','customerAccount','subpack','generatedBill')
                                        ->whereIn('pop_id', $popes->pluck('id'));
                }else{
                    $clients  = Client::with('packages','pop','clientsinfo','customerAccount','subpack','generatedBill')
                                        ->whereIn('pop_id', $popes->pluck('id'));
                }
            }
            if($request->billing_cycle != "all"){
                $clients = $clients->where('billing_cycle', $request->billing_cycle);
            }else{
                $clients = $clients;
            }


            // $clients = $clients->whereIn('id', $due_customer_list->pluck('client_id'))->get();
            $mother_packge_permissin = false;
            if (auth()->user()->hasPermissionTo('show-mother-package')) {
                $mother_packge_permissin = true;
            }

            if($request->due_type == 'partial_due'){
                $clients = $clients->where(function ($query) {
                    $query->whereHas('generatedBill', function ($subQuery) {
                        $subQuery->where('paid_amount', '!=', 0);
                    });
                });
                // dd($clients);
            }

            $sub_package_permission = false;
            if(auth()->user()->hasPermissionTo('show-sub-package')){
                $sub_package_permission = true;
            }
            $new_clients = [];
            if(in_array("all",$request->area) || $request->area == null){

                $new_clients = $clients->get();
            }else{
                $new_clients = $clients->whereHas('clientsinfo', function($q) use($request){
                    $q->whereIn('area', $request->area);
                })->get();
            }
            $type = '';
            if($request->type == 'month'){
                $type = 'month';
            }

            $data=[
                'clients' => $new_clients,
                'areas' => $request->area,
                'sub_package_permission' => $sub_package_permission,
                'mother_packge_permissin' => $mother_packge_permissin,
                'type' => $type
            ];

            return $data;
        }


    }

    public function dueCustomerSearchForInvoiceWisePayment(Request $request)
    {

        if($request->month != "all"){
            $start = Carbon::parse($request->month)->startOfMonth()->format('Y-m-d 00:00:00');
            $end = Carbon::parse($request->month)->endOfMonth()->format('Y-m-d 23:59:59');
        }

        if($request->from_date != null && $request->to_date != null){

            $start = Carbon::parse($request->from_date)->format("Y-m-d 00:00:00");
            $end = Carbon::parse($request->to_date)->format("Y-m-d 23:59:59");

        }

        if(!(isset($start) && isset($end))){
            $fist_bill_generate_date = BillGenerate::select('created_at')->orderBy('created_at', 'asc')->limit(1)->first();
            $start = Carbon::parse($fist_bill_generate_date)->startOfMonth()->format('Y-m-d 00:00:00');
            $end = Carbon::parse(today())->endOfMonth()->format('Y-m-d 23:59:59');
        }


        // Fetch resellers
        $resellerQuery = Reseller::query()->where('reseller_type', 'own');
        if ($request->reseller != "all") {
            $resellerQuery->where('id', $request->reseller);
        }
        $resellers = $resellerQuery->pluck('id');

        // Fetch POPs
        $popQuery = Pop::query()->whereIn('reseller_id', $resellers);
        if ($request->pop != "all") {
            $popQuery->where('id', $request->pop);
        }
        $popIds = $popQuery->pluck('id');

        // Fetch clients
        $clientQuery = Client::query()->whereIn('pop_id', $popIds);
        if ($request->close_status == 'closed') {
            $clientQuery->withTrashed();
        }

        if ($request->billing_cycle != "all") {
            $clientQuery->where('billing_cycle', $request->billing_cycle);
        }


        // if (!empty($request->area) && !in_array("all", $request->area)) {
        //     $clientQuery->whereHas('clientsinfo', function ($query) use ($request) {
        //         $query->whereIn('area', $request->area);
        //     });
        // }

        $clientIds = $clientQuery->pluck('id');

        // Fetch bills
        $billGenerate = BillGenerate::with('clients.pops','clientsinfo')->whereBetween('created_at', [$start, $end])
            ->whereIn('client_id', $clientIds)
            ->orderBy('client_id', 'asc')
            ->get();
        $data = [
            'billGenerates' => $billGenerate
        ];

        return view('clients.dueCustomer.resultMonthWisePaymentDue', $data);


    }





}
