<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\Pop;
use App\Models\Client;
use Illuminate\Http\Request;
use App\Models\ClientRegister;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use App\Http\Controllers\CompanyInfoController;
use Barryvdh\DomPDF\Facade\Pdf;

class ClientRegisterController extends Controller
{
    public function index()
    {
        $data = [
            'list' => ClientRegister::all(),
            'page_title' => 'Registered Client List',
        ];

        return view('clientRegister.index', $data);
    }

    public function create()
    {
        return view('clientRegister.register');
    }

    public function store(Request $request)
    {
        // dd($request->all());
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:client_registers',
            'phone' => 'digits:11',
        ]);

        $clientRegister = new ClientRegister();
        $clientRegister->fill($request->all());
        $clientRegister->status = 'Pending';
        $clientRegister->save();

        return redirect()->back()->with('success_message', 'Info added successfully!');
    }

    public function show($id)
    {
        //
    }

    public function clientEdit($id)
    {
        $data = [
            'register' => ClientRegister::find($id),
            'page_title' => 'Registered Client Edit',
        ];

        return view('clientRegister.edit', $data);
    }

    public function clientUpdate(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email|unique:client_registers,email,' . $id,
            'phone' => 'digits:11',
        ]);

        $clientRegister = ClientRegister::find($id);
        $clientRegister->fill($request->all());
        $clientRegister->status = $request->status;
        $clientRegister->update();

        toastr()->success('Info updated successfully!');
        return redirect()->route('clientRegisterList');
    }

    public function clientDestroy($id)
    {
        //
    }

    public function bulkQrCodeGenerate(Request $request)
    {
        try {
            $r = $request->session()->get('customer_search_result');
            // dd($r);
            $pop = Pop::poplist();
            $pop_ids = $pop->pluck('id')->toArray();

            $list = Client::list();

            if ($r['value'] != '') {
                $list->where('userid', 'like', '%' . $r['value'] . '%')->whereIn('pop_id', $pop_ids);
            } else {

                $list->when($r['contact'] != null, function ($q) use ($r) {

                    return $q->whereHas('clientsinfo', function ($q) use ($r) {
                        $q->where('contact_no', 'like', '%' . $r['contact'] . '%');
                    });
                });


                if ($r['billing_cycle'] != 'all') {
                    $list->where('billing_cycle', $r['billing_cycle']);
                }

                if ($r['user_state']) {
                    $list->where('clients_status', $r['user_state']);
                }

                if (isset($r['area'])) {
                    $list->whereHas('clientsinfo', function ($q) use ($r) {
                        $q->where('area',  $r['area']);
                    });
                }

                if (isset($r['user_id'])) {
                    $list->where('id', $r['user_id']);
                }

                if (isset($r['static_ip'])) {
                    $list->where('ip_address', $r['static_ip']);
                }

                if (isset($r['check_ip'])) {
                    $list->whereNotNull('ip_address')
                        ->where('ip_address', '!=', '');
                }


                if ($r['reseller'] != 'all') {

                    if ($r['pop'] != 'all') {
                        $pop_ids = $pop->where('id', $r['pop'])->where('reseller_id', $r['reseller'])->pluck('id')->toArray();
                        $list->whereIn('pop_id', $pop_ids);
                    } else {
                        $pop_ids = $pop->where('reseller_id', $r['reseller'])->pluck('id')->toArray();
                        $list->whereIn('pop_id', $pop_ids);
                    }
                }

                if ($r['expire_date_from'] && $r['expire_date_to']) {
                    $start = Carbon::parse($r['expire_date_from'])->startOfDay();
                    $end   = Carbon::parse($r['expire_date_to'])->endOfDay();

                    $list->whereBetween('expire_date', [$start, $end]);
                } else if ($r['expire_date_from']) {
                    $list->whereDate('expire_date', Carbon::parse($r['expire_date_from'])->format('Y-m-d'));
                } else if ($r['expire_date_to']) {
                    $list->whereDate('expire_date', Carbon::parse($r['expire_date_to'])->format('Y-m-d'));
                }
                
                if (isset($r['mother_package'])) {
                    $list->when($r['mother_package'] != null, function ($q) use ($r) {
                        return $q->where('package_id', $r['mother_package']);
                    });
                }

                if($r['finance'] == 'withDue'){
                    $list->whereHas('customerAccount', function ($q) use ($r) {
                        $q->where('dueAmount', '>', 0);
                    });
                } else if($r['finance'] == 'withoutDue'){
                    $list->whereHas('customerAccount', function ($q) use ($r) {
                        $q->where('dueAmount', '<=', 0);
                    });
                }

                // $list->when($r['mother_package'] != null, function ($q) use ($r) {
                //     return $q->where('package_id', $r['mother_package']);
                // });
            }

            $list = $list->get();

            if ($list->isEmpty()) {
                return redirect()->back()->with('error_message', 'No clients found to generate QR codes.');
            }

            $clientsWithQrCodes = [];
            foreach ($list as $client) {
                // dd($client);
                if ($client->slug) {
                    $link = CompanyInfoController::baseUrl() . $client->slug;
                    $qrCode = QrCode::size(200)->generate($link);

                    $clientsWithQrCodes[] = [
                        'client' => $client,
                        'qrCode' => $qrCode
                    ];
                }
            }

            if (empty($clientsWithQrCodes)) {
                return redirect()->back()->with('error_message', 'No clients with valid slugs found.');
            }

            return view('clients.bulk-qrcode', [
                'clients' => $clientsWithQrCodes
            ]);
        } catch (\Exception $e) {
            return redirect()->back()->with('error_message', 'Error generating QR codes: ' . $e->getMessage());
        }
    }

    public function qrCodeGenerate($id)
    {
        $client = Client::with('clientsinfo')->findOrFail($id);
        // dd($client);
        $link = CompanyInfoController::baseUrl() . $client->slug;

        // return \QrCode::size(200)->generate($link);

        $qrCode = QrCode::size(200)->generate($link);

        return view('clients.qrcode', [
            'client' => $client,
            'qrCode' => $qrCode
        ]);
    }
}
