<?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()) {
            $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 != null) {
                foreach ($pops as $key => $pop) {

                    $list = Client::list()->where('clients_status', 'disable')->where('pop_id', $pop->id)->get();
                }
            }
            if ($request->reseller != null && $request->pop == 'all') {

                $list = Client::list()->where('clients_status', 'disable')->whereIn('pop_id', $pop_ids)->get();
            }

            $con_history = [];
            foreach($list as $l){
                $con_history[] = User_log::where('client_id', $l->id)->where('log_type', 'id_disable')->orderBy('id', 'DESC')->first();
            }



            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)->startOfDay();
            $end = Carbon::parse($request->to_date)->endOfDay();

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

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

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

            $deactive_from_users_log = User_log::selectRaw('MAX(id),client_id,created_at,log_type,user_id')
                ->where('log_type', 'id_deactive')
                ->when($request->from_date && $request->to_date, function ($query) use ($start, $end) {
                    $query->whereBetween('created_at', [$start, $end]);
                })
                ->groupBy('client_id')
                ->get();

            $deactive_user = $deactive_from_users_log->keyBy('client_id')->all();
            $deactive_log_check = $request->filled('from_date') && $request->filled('to_date');

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

            $con_history = User_log::whereIn('client_id', $list->pluck('id'))
                ->where('log_type', 'id_deactive')
                ->orderBy('id', 'DESC')
                ->get()
                ->keyBy('client_id')
                ->all();

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