<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\Pop;
use App\Models\User;
use App\Models\Client;
use App\Models\Reseller;
use App\Models\User_log;
use App\Models\DeviceType;
use App\Models\StoreReturn;
use Illuminate\Http\Request;
use App\Services\ClientServices;
use Illuminate\Support\Facades\DB;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Support\Facades\Auth;
use App\Classes\ExpireCustomerDeactive;
use App\Exports\SearchResultExport;
use App\Jobs\ExpireCustomerDeactiveJob;
use Brian2694\Toastr\Toastr as ToastrToastr;
use App\Jobs\ExpireCustomerDeactiveByListJob;
use Illuminate\Database\Eloquent\Collection;
use Maatwebsite\Excel\Facades\Excel;

class ExpiredCustomerController extends Controller
{
    //

    public function disableCustomer()
    {

        $list = Client::list()->where('clients_status', 'disable');

        return view('disableList.disable', [
            'page_title' => 'Disable Customer List',
            'list' => $list->paginate(100),
            'reseller'   =>  Reseller::resellerList()->get(),
        ]);
    }


    public function disableCustomerSearch(Request $request)
    {
        if ($request->ajax()) {
            // Get pop IDs for selected reseller

            if ($request->reseller == 'all') {
                $pop_ids = Pop::poplist()->pluck('id')->toArray();
            } else {

                $pop_ids = Pop::where('reseller_id', $request->reseller)->pluck('id')->toArray();
            }

            // Base Query
            $query = Client::list()->where('clients_status', 'disable');

            // If specific POP selected
            if ($request->reseller != null && $request->pop != null && $request->pop != 'all') {
                $query->where('pop_id', $request->pop);
            }

            // If POP = All
            if ($request->reseller != null && $request->pop == 'all') {
                $query->whereIn('pop_id', $pop_ids);
            }

            // Final list
            $list = $query->get();

            // ------------ Fetch logs for all clients ---------------
            $clientIds = $list->pluck('id');

            $con_history = User_log::whereIn('client_id', $clientIds)
                ->where('log_type', 'id_disable')
                ->orderBy('id', 'DESC')
                ->get()
                ->groupBy('client_id')
                ->map(function ($items) {
                    return $items->first();
                });

            // ------------ If exclude limit over disable ------------
            if (!empty($request->include_temp_disable)) {

                $list = $list->filter(function ($client) use ($con_history) {

                    $log = $con_history[$client->id] ?? null;

                    // KEEP ONLY clients where details = 'limit over'
                    return ($log && $log->details == 'limit over');
                });
            }





            return view('clients.customer_search', [
                'list'       =>  $list,
                'con_history' => $con_history,
            ]);
        }
    }



    public function expiredCustomer()
    {
        // $list = ClientServices::customerList('expired');
        $data = Client::list();
        $list = $data->where('clients_status', 'expired');

        return view('expireList.expire', [
            'page_title' => 'Expired Customer List',
            'list' => $list->paginate(100),
            'reseller'   =>  Reseller::resellerList()->get(),
        ]);
    }

    public function expireCommonSearch($request)
    {
        $start = Carbon::parse($request->from_date)->startOfDay();
        $end = Carbon::parse($request->to_date)->endOfDay();
        $poplist = Pop::with('reseller')->where('reseller_id', $request->reseller)->get();
        $pop_ids = $poplist->pluck('id')->toArray();
        $pops = Pop::where('id', $request->pop)->get();
        $list[] = '';

        if ($request->from_date != null && $request->to_date != null) {
            $data = Client::list()->whereBetween('expire_date', [$start, $end]);
        } else {
            $data = Client::list();
        }
        if ($request->reseller != null && $request->pop != null) {
            foreach ($pops as $key => $pop) {
                $list = $data->where('clients_status', 'expired')->where('pop_id', $pop->id);
            }
        }
        if ($request->reseller != null && $request->pop == "all") {
            if ($request->reseller != "all") {
                $list = $data->where('clients_status', 'expired')->whereIn('pop_id', $pop_ids);
            } else {
                $list = $data->where('clients_status', 'expired');
            }
        }
        return $list;
    }

    public function expiredCustomerSearch(Request $request)
    {
        if ($request->ajax()) {
            session()->put('expireClientSearchArgument', $request->all());
            $list = $this->expireCommonSearch($request);

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

    public function expireClientExport(Request $request)
    {
        $r = $request->session()->get('expireClientSearchArgument');
        if ($r) {
            $list = $this->expireCommonSearch((object)$r);
            $list->get();

            $result = new Collection();
            $list->orderBy('id')->chunk(500, function ($list) use (&$result) {
                foreach ($list as $l) {
                    $result->push((object)$l);
                }
            });

            $fileName = 'Expired_Customer_List_' . date('Y-m-d_H-i-s') . '.xlsx';
            return Excel::download(new SearchResultExport($result), $fileName);
        }
    }



    public function deactiveCustomer()
    {
        $list = Client::list()->where('clients_status', 'deactive');
        $start = Carbon::now()->startOfMonth();
        $end = today();
        if (checkSettings('deactive-custome-datatable') == 'enable') {
            $deactiveCustomer = $list->get();
        } else {
            $deactiveCustomer = $list->paginate(100);
        }

        return view('deactiveList.deactive', [
            'page_title' => 'Deactive Customer List',
            'list' => $deactiveCustomer,
            'reseller'   =>  Reseller::resellerList()->get(),
            'start' => $start,
            'end' => $end,
        ]);
    }

    public function deactiveAllExpiredCustomer()
    {
        if (auth()->user()->can('deactive-all-expired-customer')) {
            // ExpireCustomerDeactiveJob::dispatch();

            DB::table('clients')
                ->leftJoin('pops', 'clients.pop_id', '=', 'pops.id')
                ->whereRaw("DATE_ADD(expire_date,INTERVAL payment_dadeline DAY) < DATE_SUB(CURDATE() , interval 0 day) ")
                ->select('clients.id', 'clients.expire_date', 'clients.clients_status')
                ->where('pops.bill_generate', 'yes')
                ->where('pops.experity_check', 'No')
                ->where('clients.clients_status', 'expired')
                ->whereNull('clients.deleted_at')
                ->orderBy('clients.id', 'asc')
                ->chunk(100, function ($clients) {
                    dispatch(new ExpireCustomerDeactiveByListJob($clients, auth()->user()->id));
                });


            Toastr::success('Process Started');
            return redirect()->back();
        } else {
            abort(403);
        }
    }

    public function deactiveCustomerSearch(Request $request)
    {
        // // $request->session()->put('deactive_customer_search_result', $request->all());
        // if ($request->ajax()) {

        //     $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');
        //     $poplist = Pop::with('reseller')->where('reseller_id', $request->reseller)->get();
        //     $pop_ids = $poplist->pluck('id')->toArray();
        //     $pops = Pop::where('id', $request->pop)->get();
        //     $list[] = '';
        //     if ($request->reseller != null && $request->pop == 'all') {
        //         //for all pop of a reseller

        //         $data = Client::list();
        //         $list = $data->where('clients_status', 'deactive')->whereIn('pop_id', $pop_ids)->get();
        //     } else if ($request->reseller != null && $request->pop != null) {
        //         //for single pop

        //         foreach ($pops as $key => $pop) {

        //             $data = Client::list();
        //             $list = $data->where('clients_status', 'deactive')->where('pop_id', $pop->id)->get();
        //         }
        //     } else {

        //         //for all pop of all reseller
        //         $data = Client::list();
        //         $list = $data->where('clients_status', 'deactive')->get();
        //     }

        //     $deactive_from_users_log = User_log::selectRaw('MAX(id),client_id,created_at,log_type,user_id')
        //         ->where('log_type', 'id_deactive')
        //         ->whereBetween('created_at', [$start, $end])
        //         ->groupBy('client_id')
        //         ->get();

        //     $deactive_user = [];
        //     $deactive_log_check = true;
        //     foreach ($deactive_from_users_log as $key => $value) {
        //         $deactive_user[$value->client_id] = $value;
        //     }
        //     if ($request->from_date == null || $request->to_date == null) {
        //         $deactive_log_check = false;
        //     }
        //     $users = User::where('id', '!=', 1)->get();
        //     $user_list[] = [];
        //     foreach ($users as $key => $value) {
        //         $user_list[$value->id] = $value->name;
        //     }

        //     // dd($list);
        //     $con_history = [];
        //     foreach($list as $l){
        //         $con_history[] = User_log::where('client_id', $l->id)->where('log_type', 'id_deactive')->orderBy('id', 'DESC')->first();
        //     }
        //     // dd($con_history);
        //     // dd($deactive_from_users_log->toArray());
        //     // $total
        //     // $request->session()->put('deactive_customer_search_result', $list, $deactive_user);
        //     $request->session()->put('deactive_customer_search_result', ['list' => $list, 'deactive_user' => $deactive_user]);

        //     $data = [
        //         'list'  =>  $list,
        //         'deactive_users' => $deactive_user,
        //         'deactive_log_check' => $deactive_log_check,
        //         'user_list' => $user_list,
        //         'con_history' => $con_history,
        //     ];
        //     // return $data;
        //     return view('deactiveList.result', $data);
        // }

        if ($request->ajax()) {
            $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');

            // Get POPs
            $poplist = Pop::with('reseller')->where('reseller_id', $request->reseller)->get();
            $pop_ids = $poplist->pluck('id')->toArray();

            // Get deactive clients
            $data = Client::list()->where('clients_status', 'deactive');

            if ($request->reseller != null && $request->pop != "all") {
                $data->where('pop_id', $request->pop);
            } elseif ($request->reseller != null) {
                $data->whereIn('pop_id', $pop_ids);
            }

            $list = $data->get();

            // Check if date filter is applied
            $deactive_log_check = $request->filled('from_date') && $request->filled('to_date');

            if ($deactive_log_check) {
                // Get the LATEST log for each client
                $latest_logs = User_log::where('log_type', 'id_deactive')
                    ->whereIn('id', function ($q) {
                        $q->selectRaw('MAX(id)')
                            ->from('user_log')
                            ->where('log_type', 'id_deactive')
                            ->groupBy('client_id');
                    })
                    ->select('id', 'client_id', 'created_at', 'log_type', 'user_id')
                    ->get();

                // Filter: Keep only logs where created_at is within date range
                $deactive_from_users_log = $latest_logs->filter(function ($log) use ($start, $end) {
                    return $log->created_at >= $start && $log->created_at <= $end;
                });
            } else {
                // No date filter: Get absolute latest deactivation for all
                $deactive_from_users_log = User_log::where('log_type', 'id_deactive')
                    ->whereIn('id', function ($q) {
                        $q->selectRaw('MAX(id)')
                            ->from('user_log')
                            ->where('log_type', 'id_deactive')
                            ->groupBy('client_id');
                    })
                    ->select('id', 'client_id', 'created_at', 'log_type', 'user_id')
                    ->get();
            }

            $deactive_user = $deactive_from_users_log->keyBy('client_id')->all();

            // Get connection history (latest for each client in list)
            $con_history = User_log::whereIn('client_id', $list->pluck('id'))
                ->where('log_type', 'id_deactive')
                ->whereIn('id', function ($q) {
                    $q->selectRaw('MAX(id)')
                        ->from('user_log')
                        ->where('log_type', 'id_deactive')
                        ->groupBy('client_id');
                })
                ->orderBy('id', 'DESC')
                ->get()
                ->keyBy('client_id')
                ->all();

            $users = User::where('id', '!=', 1)->pluck('name', 'id')->toArray();

            $request->session()->put('deactive_customer_search_result', [
                'list' => $list,
                'deactive_user' => $deactive_user,
            ]);

            $data = [
                'list' => $list,
                'deactive_users' => $deactive_user,
                'deactive_log_check' => $deactive_log_check,
                'user_list' => $users,
                'con_history' => $con_history,
            ];

            return view('deactiveList.result', $data);
        }
    }

    public function stockReturn($id)
    {
        // dd($id);
        $data = [
            'deviceType' => DeviceType::all(),
            'clientId' => $id,
            // 'list' => StoreReturn::where('clientId', $id)->get()
        ];

        // dd($data['list']);

        return view('deactiveList.stockReturn', $data);
    }

    public function returnStore(Request $request)
    {
        // dd($request->all());
        DB::beginTransaction();
        try {

            $arrayLength = sizeof($request->device_id);

            for ($i = 0; $i < $arrayLength; $i++) {
                $stock = new StoreReturn();
                $stock->clientId = $request->clientId;
                $stock->device_id = $request->device_id[$i];
                $stock->status = $request->status[$i];
                $stock->mack = $request->mack[$i];
                $stock->serial = $request->serial[$i];
                $stock->remark = $request->remark[$i];
                $stock->save();
            }

            DB::commit();
            Toastr::success('Information Added Successfully', '', ["progressBar" => true]);
            return back();
        } catch (\Exception $ex) {
            DB::rollback();
            Toastr::error('Some Problem Happen', '', ["progressBar" => true]);
            dd($ex);
            return back();
        }
    }
}
