<?php

namespace App\Http\Controllers\Clients;

use App\Exports\DeactiveCloseExport;
use App\Exports\SearchResultExport;
use App\Models\Pop;
use App\Models\Client;
use App\Models\Reseller;
use Illuminate\Http\Request;
use App\Models\ClientReferer;
use App\Services\ClientServices;
use App\Http\Controllers\Controller;
use App\Models\User_log;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;

class CustomerListController extends Controller
{
    public function index($type)
    {

        // dd($type);
        $list = Client::list();
        $close = false;
        $closeTotal=0;

        if ($type == 'close-list') {
            $start  = today()->firstOfMonth();
            $end    = today();
            $closeTotal = $list->onlyTrashed()->paginate('1000')->total();
            $list   = $list->whereBetween('deleted_at', [$start, $end])->onlyTrashed();
            $title  = 'Close Customer List';
            $close  = true;
            $url    = 'closeSearch';

        } elseif ($type == 'new-join') {
            $start  = today()->firstOfMonth();
            $end    = Carbon::now();
            $list   = $list->whereBetween('created_at', [$start, $end])->orderBy('id', 'desc');
            $title  = 'New Join Customer List';
            $url    = 'newClientSearchReport';

        }elseif($type == 'active-customer'){
            $list = $list->where('clients_status', 'active');
            $title = 'Active Customer List';
            $url = 'activeCustomerSearch';
        }elseif($type == 'disable-customer'){
            $list = $list->where('clients_status', 'disable');
            // dd($list->get());
            $con_history = [];
            foreach($list->get() as $l){
                $con_history[] = User_log::where('client_id', $l->id)->where('log_type', 'id_disable')->orderBy('id', 'DESC')->first();
            }
            // dd($con_history);
            $title = 'Disable Customer List';
            $url = 'disableCustomerSearch';
        }elseif($type=='expired-Clients'){
            $list = $list->where('clients_status', 'expired');
            $title = 'Expired Customer List';
            $url = 'expiredCustomerSearch';
        }

        $export='no';


        return view('clients.list', [
            'page_title' => $title,
            'close' => $close,
            'start' => $start ?? null,
            'end' => $end ?? null,
            'search_url' => $url,
            'list' => $list->paginate(100),
            'confday' => config('app.billing_cycle'),
            'closeTotal' => $closeTotal,
            'export' => $export,
            'con_history' => $con_history ?? null,
            'client_type'=>$type,
            'multiple_client_restore' => $type == 'close-list' ? (checkSettings('multiple_client_restore') == 'enable') : false,
        ]);
    }

    public function closeSearch(Request $request)
    {
        // dd($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::poplist()->where('reseller_id', $request->reseller);
            $pop_ids = $poplist->pluck('id')->toArray();
            $list[] = '';
            $close  = true;

            if ($request->reseller != "null") {

                $list = Client::with('clientsinfo', 'packages', 'subpack', 'pop', 'customerAccount', 'pop.reseller')->where('client_approval', 'approved');

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

                        $list->where('pop_id', $request->pop)->whereBetween('deleted_at', [$start, $end])->onlyTrashed();
                    } else{

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

                        $list->whereIn('pop_id', $pop_ids)->whereBetween('deleted_at', [$start, $end])->onlyTrashed();
                    } else{

                        $list->whereIn('pop_id', $pop_ids)->onlyTrashed();
                    }
                }
            } elseif($request->reseller == "null" && $request->from_date != null && $request->to_date != null){

                $list = Client::list()->where('client_approval', 'approved')->whereBetween('deleted_at', [$start, $end])->onlyTrashed();
            } elseif($request->username != null){

                $list = Client::list()->where('client_approval', 'approved')->where('userid', 'like', '%' . $request->username . '%')->onlyTrashed();
            } elseif($request->cid != null){

                $list = Client::list()->where('client_approval', 'approved')->where('id', $request->cid)->onlyTrashed();
            } elseif($request->code != null){

                $list = Client::list()->where('client_approval', 'approved')->where('customer_code', 'like', '%' . $request->code . '%')->onlyTrashed();
            } elseif($request->contact != null){
                $list = Client::list()->when($request->contact != null, function ($q) use ($request) {

                    return $q->whereHas('clientsinfo', function ($q) use ($request) {
                        $q->where('contact_no', 'like', '%' . $request->contact . '%');
                    });
                })->onlyTrashed();
            } else {

                $list = Client::list()->where('client_approval', 'approved')->onlyTrashed();
            }
            $request->session()->put('close_customer_search_result', $list->get());
            return view('clients.customer_search', [
                'list'          =>  $list->get(),
                'close' => $close,
            ]);
        }
    }

    public function closeClientExport()
    {
        $list = Client::list()->onlyTrashed();

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

        $data[] = '';
        $data = $result;

        return Excel::download(new DeactiveCloseExport($data), 'closeCustomers.csv');

    }
}
