<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\Reseller;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Models\Pop;
use App\Models\ReselleBalanceLogReport;
use Doctrine\DBAL\Driver\Middleware;

class ReselleBalanceLogReportController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:reseller-balance-log-report',['only' => 'index']);
    }

    public function index()
    {
        $start = Carbon::now()->today();

        // dd($start);
        $end = today();
        return view('resellerBalanceLog.index', [
            'page_title' => 'Manager Balance Log Report',
            'start'      => $start,
            'end'        => $end,
            'reseller'   =>  Reseller::resellerList()->get()
        ]);
    }


    public function resellerBalanceLogReport(Request $request)
    {
        // dd($request->all());
        if ($request->ajax()) {

            $from = $request->from_date == '' ? today() : Carbon::parse($request->from_date);
            $to   = $request->to_date == '' ? today() : Carbon::parse($request->to_date);

            $from = Carbon::parse($from)->format('Y-m-d 00:00:00');
            $to   = Carbon::parse($to)->format('Y-m-d 23:59:59');

            $resellerlist = Reseller::resellerList()->get();
            $reseller_ids = $resellerlist->pluck('id')->toArray();

            $list = ReselleBalanceLogReport::with('reseller', 'client', 'pop')
                                            ->whereBetween('created_at', [$from, $to]);

            if($request->username){
                $list->whereHas('client',function($q) use($request){
                    $q->where('userid','like','%'.$request->username.'%');
                });

            }

            // if ($request->reseller_id == 'all' || $request->reseller_id == '') {
            if ($request->reseller_id != null) {
                $list->where('reseller_id', $request->reseller_id);

                // $list->whereIn('reseller_id', $reseller_ids);
            }else {
                $list->whereIn('reseller_id', $reseller_ids);
                //  $list->where('reseller_id', $request->reseller_id);
            }

            if($request->pop != null && $request->pop != 'all'){
                $list->where('pop_id', $request->pop);
            }


            return view('resellerBalanceLog.result', [
                'list'       =>  $list->get()
            ]);
        }
    }


    public function resellerBalanceLogCheck()
    {



        $pop = Pop::where('reseller_id','5')->pluck('id');
        $clients = Client::whereIn('pop_id',$pop)->pluck('id');


        $list = ReselleBalanceLogReport::query()
        ->whereBetween('created_at', ['2022-11-20 00:03:03.000000', '2022-11-25 00:03:03.000000'])
        ->where('amount', '>', 0)
        ->where('action','like','%'.'Billing Cycle Changed'.'%')
        ->whereIn('client_id',$clients)
        ->selectRaw('id,reseller_id,client_id,amount,action,DATE(created_at) as date')
        ->get()
        ->groupBy('client_id')
        ->map(function($item, $key){
            if($item->count() > 1){

                $val = $item->groupBy('amount');


                foreach($val as $key => $v){
                    if($v->count() <= 1){
                        $val->forget($key);
                    }else{
                        $v->shift();
                    }
                }

                return $val;
            }
        })
        ->filter(function($q){
            return $q != null;
        });

        $list = $list->flatten();

        echo 'Total Amount: '.$list->sum('amount');
        echo '<br>';

        foreach($list as $a){
            echo $a->id . '- User Id: <b>'. $a->client_id.'</b> - Amount: '.$a->amount;
            echo '<br>';
            if(request()->delete == 'true'){
                echo 'access ok';
                echo '<br>';
                ReselleBalanceLogReport::where('id',$a->id)->delete();
            }
        }
    }

    public function resellerWiseTotalCost()
    {
        $start = Carbon::now()->today();
        $end = today();

        return view('resellerBalanceLog.costIndex', [
            'page_title' => 'Manager Balance Log Report',
            'start'      => $start,
            'end'        => $end,
            'reseller'   =>  Reseller::resellerList()->get()
        ]);
    }

    public function resellerWiseTotalCostResult(Request $request)
    {
        if ($request->ajax()) {

            $from = $request->from_date == '' ? today() : Carbon::parse($request->from_date);
            $to   = $request->to_date == '' ? today() : Carbon::parse($request->to_date);

            $from = Carbon::parse($from)->format('Y-m-d 00:00:00');
            $to   = Carbon::parse($to)->format('Y-m-d 23:59:59');

            $resellerlist = Reseller::resellerList()->get();
            $reseller_ids = $resellerlist->pluck('id')->toArray();

            $list = ReselleBalanceLogReport::with('reseller')
                        ->selectRaw('reseller_id, SUM(amount) as total_amount') // <-- replace `amount` if needed
                        ->whereBetween('created_at', [$from, $to]);

            if ($request->reseller_id != null) {
                $list->where('reseller_id', $request->reseller_id);
            } else {
                $list->whereIn('reseller_id', $reseller_ids);
            }

            $list = $list->groupBy('reseller_id')->get();

            return view('resellerBalanceLog.totalCostresult', [
                'list' => $list
            ]);
        }
    }
}
