<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\Pop;
use App\Models\Reseller;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class RecentClientController extends Controller
{
    public function recentCustomerAccount()
    {
        $start = Carbon::now()->startOfMonth();
        $end = today();
        $resellers = Reseller::list()->where('reseller_type', 'own');

        return view('recentClients.account', [
            'start' => $start,
            'end'   => $end,
            'resellers' => $resellers,
            'confday' => config('app.billing_cycle'),
        ]);

    }

    public function recentCustomerAccountSearch(Request $request)
    {
        $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();
            $clients = Client::with('packages','pop','clientsinfo','customerAccount','subpack')
                            ->whereIn('pop_id', $popes->pluck('id'))
                            ->whereBetween('created_at', [$start, $end]);
        }else{
            $popes = Pop::where('id',$request->pop)->get();
            $clients = Client::with('packages','pop','clientsinfo','customerAccount','subpack')
                            ->whereIn('pop_id', $popes->pluck('id'))
                            ->whereBetween('created_at', [$start, $end]);
        }


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

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



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

        return $data;
    }
}
