<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\Pop;
use Brian2694\Toastr\Facades\Toastr;
use Carbon\Carbon;
use Illuminate\Http\Request;

class CRMClientController extends Controller
{
    public function crmcClients()
    {

        $list = Client::list();

        $pop = Pop::all();

        $crm_status = [];
        //check permission
        if (auth()->user()->can('crm_marketing')) {
            array_push($crm_status, 'Marketing');
        }

        if (auth()->user()->can('crm_crm')) {
            array_push($crm_status, 'CRM');
        }

        if (auth()->user()->can('crm_support')) {
            array_push($crm_status, 'Support');
        }

        if (auth()->user()->can('crm_account')) {
            array_push($crm_status, 'Account');
        }

        if (auth()->user()->can('crm_fiber')) {
            array_push($crm_status, 'Fiber');
        }

        if (auth()->user()->can('crm_store')) {
            array_push($crm_status, 'Store');
        }



        $data = [
            'list' => $list->where('clients_status', '!=', 'active')->where('clients_status', '!=', 'disable')->whereIn('crm_status', $crm_status)->paginate(100),
            'type' => "",
            'pop' => $pop,
        ];
        // dd($data);

        return view('crm.client.list', $data);
    }

    public function crmcClientsByTpye($type)
    {


        $permission =  "crm_" . strtolower($type);
        if (!auth()->user()->can($permission)) {
            Toastr::error('You do not have permission to access this', 'Error');
            return redirect()->back();
        }

        $list = Client::list();


        $data = [
            'list' => $list->where('clients_status', '!=', 'active')->where('clients_status', '!=', 'disable')->where('crm_status', $type)->paginate(100),
            'type' => $type,
            'pop' => Pop::all(),
        ];


        return view('crm.client.list', $data);
    }

    public function crmCustomerSearch(Request $request)
    {
        if (request()->ajax()) {
            // dd($request->all());
            $uid = auth()->user()->id;
            $con = $request->search;
            $pop_ids = Client::pop_ids();
            $permissions = auth()->user()->getAllPermissions()->pluck('name')->toArray();

            if ($request->type) {
                $list = Client::list()->where('clients_status', '!=', 'active')->where('clients_status', '!=', 'disable')->where('crm_status', $request->type);
            } else {
                $crm_status = [];
                if (auth()->user()->can('crm_marketing')) {
                    array_push($crm_status, 'Marketing');
                }

                if (auth()->user()->can('crm_crm')) {
                    array_push($crm_status, 'CRM');
                }

                if (auth()->user()->can('crm_support')) {
                    array_push($crm_status, 'Support');
                }

                if (auth()->user()->can('crm_account')) {
                    array_push($crm_status, 'Account');
                }

                if (auth()->user()->can('crm_fiber')) {
                    array_push($crm_status, 'Fiber');
                }

                if (auth()->user()->can('crm_store')) {
                    array_push($crm_status, 'Store');
                }
                $list = Client::list()->where('clients_status', '!=', 'active')->where('clients_status', '!=', 'disable')->whereIn('crm_status', $crm_status);
            }
            // dd("comes");
            if ($request->crm_check_date) {

                $list->where('crm_check_date', $request->crm_check_date);
            }

            if ($request->crm_client_expire_date) {
                $expireDate = Carbon::parse($request->crm_client_expire_date);

                $firstDateOfMonth = $expireDate->startOfMonth()->toDateString();
                $lastDateOfMonth = $expireDate->endOfMonth()->toDateString();

                $list->whereBetween('expire_date', [$firstDateOfMonth, $lastDateOfMonth]);
            }


            if ($request->id) {
                $list->where('id', $request->id);
            }

            if ($request->username) {
                $list->where('userid', 'like', '%' . $request->username . '%');
            }

            if ($request->pop_id_crm) {
                $list->where('pop_id', $request->pop_id_crm);
            }

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

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

            if ($request->area) {
                $list->whereHas('clientsinfo', function ($q) use ($request) {
                    $q->where('area', 'like', '%' . $request->area . '%');
                });
            }
            if ($request->customername) {
                $list->whereHas('clientsinfo', function ($q) use ($request) {
                    $q->where('clients_name', 'like', '%' . $request->customername . '%')
                        ->orWhere('father_name', 'like', '%' . $request->customername . '%')
                        ->orWhere('mother_name', 'like', '%' . $request->customername . '%')
                        ->orWhere('flat_no', 'like', '%' . $request->customername . '%')
                        ->orWhere('building_no', 'like', '%' . $request->customername . '%')
                        ->orWhere('building_name', 'like', '%' . $request->customername . '%')
                        ->orWhere('other_contact', 'like', '%' . $request->customername . '%')
                        ->orWhere('road_no', 'like', '%' . $request->customername . '%');
                });
            }


            // dd($list);

            $list = $list->take(100)->get();


            if (checkAPI()) {
                $online = mikrotikOnlineAndOfflineUsers();
            } else {
                $online = Client::online($list->pluck('userid'));
            }

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

    public function crmClientListCsv(Request $request)
    {
        session(['crm_search_filters' => $request->all()]);
        $uid = auth()->user()->id;
        $pop_ids = Client::pop_ids();

        // Get filters from session if not in request
        $filters = session('crm_search_filters', []);

        // Merge session filters with request (request takes priority)
        $type = $request->type ?? $filters['type'] ?? null;
        $crm_check_date = $request->crm_check_date ?? $filters['crm_check_date'] ?? null;
        $crm_client_expire_date = $request->crm_client_expire_date ?? $filters['crm_client_expire_date'] ?? null;
        $id = $request->id ?? $filters['id'] ?? null;
        $username = $request->username ?? $filters['username'] ?? null;
        $pop_id_crm = $request->pop_id_crm ?? $filters['pop_id_crm'] ?? null;
        $contact = $request->contact ?? $filters['contact'] ?? null;
        $box = $request->box ?? $filters['box'] ?? null;
        $area = $request->area ?? $filters['area'] ?? null;
        $customername = $request->customername ?? $filters['customername'] ?? null;

        // Determine which CRM statuses the user can access
        if ($type) {
            $list = Client::list()
                ->where('clients_status', '!=', 'active')
                ->where('clients_status', '!=', 'disable')
                ->where('crm_status', $type);
        } else {
            $crm_status = [];

            if (auth()->user()->can('crm_marketing')) {
                array_push($crm_status, 'Marketing');
            }
            if (auth()->user()->can('crm_crm')) {
                array_push($crm_status, 'CRM');
            }
            if (auth()->user()->can('crm_support')) {
                array_push($crm_status, 'Support');
            }
            if (auth()->user()->can('crm_account')) {
                array_push($crm_status, 'Account');
            }
            if (auth()->user()->can('crm_fiber')) {
                array_push($crm_status, 'Fiber');
            }
            if (auth()->user()->can('crm_store')) {
                array_push($crm_status, 'Store');
            }

            $list = Client::list()
                ->where('clients_status', '!=', 'active')
                ->where('clients_status', '!=', 'disable')
                ->whereIn('crm_status', $crm_status);
        }

        // Apply filters
        if ($crm_check_date) {
            $list->where('crm_check_date', $crm_check_date);
        }

        if ($crm_client_expire_date) {
            $expireDate = Carbon::parse($crm_client_expire_date);
            $firstDateOfMonth = $expireDate->startOfMonth()->toDateString();
            $lastDateOfMonth = $expireDate->endOfMonth()->toDateString();
            $list->whereBetween('expire_date', [$firstDateOfMonth, $lastDateOfMonth]);
        }

        if ($id) {
            $list->where('id', $id);
        }

        if ($username) {
            $list->where('userid', 'like', '%' . $username . '%');
        }

        if ($pop_id_crm) {
            $list->where('pop_id', $pop_id_crm);
        }

        if ($contact) {
            $list->whereHas('clientsinfo', function ($q) use ($contact) {
                $q->where('contact_no', 'like', '%' . $contact . '%');
            });
        }

        if ($box) {
            $list->whereHas('clientsinfo', function ($q) use ($box) {
                $q->where('box', 'like', '%' . $box . '%');
            });
        }

        if ($area) {
            $list->whereHas('clientsinfo', function ($q) use ($area) {
                $q->where('area', 'like', '%' . $area . '%');
            });
        }

        if ($customername) {
            $list->whereHas('clientsinfo', function ($q) use ($customername) {
                $q->where('clients_name', 'like', '%' . $customername . '%')
                    ->orWhere('father_name', 'like', '%' . $customername . '%')
                    ->orWhere('mother_name', 'like', '%' . $customername . '%')
                    ->orWhere('flat_no', 'like', '%' . $customername . '%')
                    ->orWhere('building_no', 'like', '%' . $customername . '%')
                    ->orWhere('building_name', 'like', '%' . $customername . '%')
                    ->orWhere('other_contact', 'like', '%' . $customername . '%')
                    ->orWhere('road_no', 'like', '%' . $customername . '%');
            });
        }

        // Get all matching records for CSV export
        $clients = $list->get();



        // Prepare CSV data
        $filename = 'crm_clients_' . date('Y-m-d_His') . '.csv';

        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ];

        $callback = function () use ($clients) {
            $file = fopen('php://output', 'w');

            // CSV Headers
            fputcsv($file, [
                'Serial',
                'ID',
                'Username',
                'Password',
                'Status',
                'CRM Status',
                'Expire Date',
                'Bill Date',
                'Package',
                'Package Rate',
                'Discount',
                'Monthly Bill',
                'POP',
                'Name',
                'Contact',
                'Father Name',
                'Mother Name',
                'NID',
                'Division',
                'District',
                'Upazila',
                'Area',
                'Box',
                'Road Name',
                'Road No',
                'Building Name',
                'Building No',
                'Flat No',
                'House Owner',
                'Owner Contact',
                'Email',
                'IP Address',
                'MAC',
                'Connection Type',
                'Customer Type',
                'Cable Type',
                'Required Cable (Meter)',
                'OLT/PON',
                'Cable ID',
                'ONU Serial',
                'Created Date',
                'Join Date',
                'CRM Check Date',
                'Remarks',
            ]);

            // CSV Data
            $count = 0;
            foreach ($clients as $client) {
                $packageRate = $client->packages->package_rate ?? 0;
                $discount = $client->parmanent_discount ?? 0;
                $monthlyBill = $packageRate - $discount >= 0 ? $packageRate - $discount : 0;

                fputcsv($file, [
                    ++$count,
                    $client->id,
                    $client->isStatic ? $client->ip_address : $client->userid,
                    $client->password ?? '',
                    $client->clients_status,
                    $client->crm_status,
                    date('d-M-Y', strtotime($client->expire_date)),
                    $client->billing_cycle,
                    $client->packages->package_name ?? '',
                    $packageRate,
                    $discount,
                    $monthlyBill,
                    $client->pops->popname ?? '',
                    $client->clientsinfo->clients_name ?? '',
                    $client->clientsinfo->contact_no ?? '',
                    $client->clientsinfo->father_name ?? '',
                    $client->clientsinfo->mother_name ?? '',
                    $client->clientsinfo->national_id ?? '',
                    $client->clientsinfo->divisions->name ?? '',
                    $client->clientsinfo->districts->name ?? '',
                    $client->clientsinfo->thanas->name ?? '',
                    $client->clientsinfo->area ?? '',
                    $client->clientsinfo->box ?? '',
                    $client->clientsinfo->road_name ?? '',
                    $client->clientsinfo->road_no ?? '',
                    $client->clientsinfo->building_name ?? '',
                    $client->clientsinfo->building_no ?? '',
                    $client->clientsinfo->flat_no ?? '',
                    $client->clientsinfo->owner_name ?? '',
                    $client->clientsinfo->owner_number ?? '',
                    $client->clientsinfo->email ?? '',
                    $client->ip_address ?? '',
                    $client->mac ?? '',
                    $client->connection_type ?? '',
                    $client->customer_type ?? '',
                    $client->clientsinfo->cable_type ?? '',
                    $client->required_cable ?? '',
                    $client->clientsinfo->olt_pon ?? '',
                    $client->clientsinfo->cable_id ?? '',
                    $client->clientsinfo->onu_serial ?? '',
                    date('d-M-Y h:i:sa', strtotime($client->created_at)),
                    $client->clientsinfo->joinDate ? date('d-M-Y', strtotime($client->clientsinfo->joinDate)) : '',
                    $client->crm_check_date ? date('d-M-Y', strtotime($client->crm_check_date)) : '',
                    $client->clientsinfo->remarks ?? ''
                ]);
            }

            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }
}
