<?php

namespace App\Http\Controllers\Nulm;

use App\Models\Status;
use Illuminate\Http\Request;
use App\Services\CommonService;
use App\Models\Nulm\HawkerRegister;
use App\Http\Controllers\Controller;
use Barryvdh\Snappy\Facades\SnappyPdf;
use App\Services\Nulm\HawkerRegisterService;
use App\Http\Requests\Nulm\HawkerRegister\CreateRequest;
use App\Http\Requests\Nulm\HawkerRegister\UpdateRequest;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;



class HawkerRegisterController extends Controller
{
    protected $commonService;
    protected $hawkerRegister;


    // Constructor for dependency injection
    public function __construct(HawkerRegisterService $hawkerRegister, CommonService $commonService)
    {
        $this->hawkerRegister = $hawkerRegister;
        $this->commonService = $commonService;
    }

    // Display the create form
    public function create()
    {
        // Get active wards and zones from CommonService
        $wards = $this->commonService->getActiveWard();
        $zones = $this->commonService->getActiveZone();

        // Return the create view with wards and zones data
        return view('nulm.hawkerregister.create')->with([
            'wards' => $wards,
            'zones' => $zones,
        ]);
    }

    // Store the newly created abattoir license
    public function store(CreateRequest $request)
    {

        // Call the store method in the service and get the response
        $hawkerRegister = $this->hawkerRegister->store($request);

        // dd($request);
        // Check if the license was successfully saved
        if ($hawkerRegister[0]) {
            return response()->json([
                'success' => 'Hawker Register saved successfully'
            ]);
        } else {
            return response()->json([
                'error' => $hawkerRegister[1]
            ]);
        }
    }



    // public function edit($id)
    // {
    //     $id = decrypt($id);
    //     $hawkerRegister = HawkerRegister::findOrFail($id);

    //     $status = Status::where('table_id', $id)
    //     ->where('service_id', $hawkerRegister->service_id)
    //     ->first();

    //     $hawkerRegister = $this->hawkerRegister->edit(decrypt($id));

    //     $wards = $this->commonService->getActiveWard();

    //     $zones = $this->commonService->getActiveZone();

    //     return view('nulm.hawkerregister.update')->with([
    //         'hawkerRegister' =>  $hawkerRegister,
    //         'wards' => $wards,
    //         'zones' => $zones,
    //         'status' => $status
    //    ]);
    // }

    public function edit($id)
    {
        try {
            // Step 1: Try to decrypt the ID safely
            try {
                $id = decrypt($id);
            } catch (DecryptException $e) {
                Log::error('Invalid encrypted ID provided: ' . $e->getMessage());
                return redirect()->back()->with('error', 'Invalid request. Please try again.');
            }

            // Step 2: Safely fetch record
            $hawkerRegister = HawkerRegister::find($id);
            if (!$hawkerRegister) {
                return redirect()->back()->with('error', 'Record not found.');
            }

            //Step 3: Try related lookups
            $status = Status::where('table_id', $id)
                ->where('service_id', $hawkerRegister->service_id ?? null)
                ->first();

            // Step 4: Call model/service safely
            try {
                $hawkerRegister = $this->hawkerRegister->edit($id);
            } catch (\Exception $e) {
                Log::error('Error calling hawkerRegister->edit(): ' . $e->getMessage());
                return redirect()->back()->with('error', 'Error loading record details. Please contact admin.');
            }

            // Step 5: Load dropdown data
            $wards = [];
            $zones = [];
            try {
                $wards = $this->commonService->getActiveWard();
                $zones = $this->commonService->getActiveZone();
            } catch (\Exception $e) {
                Log::error('Error fetching wards/zones: ' . $e->getMessage());
            }

            // Step 6: Return the view
            return view('nulm.hawkerregister.update')->with([
                'hawkerRegister' =>  $hawkerRegister,
                'wards'          =>  $wards,
                'zones'          =>  $zones,
                'status'         =>  $status
            ]);

        } catch (\Exception $e) {
            // Catch any unexpected DB or system errors
            DB::rollBack(); // just in case
            Log::error('Unexpected error in edit(): ' . $e->getMessage());
            return redirect()->back()->with('error', 'An unexpected error occurred. Please try again.');
        }
    }

    public function update(UpdateRequest $request, $id)
    {
        // dd($request->all());
        $hawkerRegister = $this->hawkerRegister->update($request, $id);
        if ($hawkerRegister) {
            return response()->json([
                'success' => 'Hawker Register updated successfully'
            ]);
        } else {
            return response()->json([
                'error' => 'Something went wrong, please try again'
            ]);
        }
    }

    public function show($id)
    {
        $data = HawkerRegister::with('user')->findOrFail(decrypt($id));

        $pdf = SnappyPdf::loadView('nulm.hawkerregister.hawkerregistercertificate', ['data' => $data]);
        $pdf->setPaper('a4')
            ->setOption('margin-top', 10)
            ->setOption('margin-bottom', 10)
            ->setOption('margin-left', 5)
            ->setOption('margin-right', 5)
            ->setOption('enable-smart-shrinking', true)
            ->setOption('disable-smart-shrinking', false)
            ->setOption('no-stop-slow-scripts', true)
             // ->setOption('footer-right', now()->format('d-m-Y h:i:s'))
            ->setOption('footer-left', 'Page: [page] of [toPage]');
        return $pdf->inline('certificate.pdf');
    }
}
