<?php

namespace App\Livewire\QrCode;

use App\Helper\Files;
use App\Models\Area;
use Livewire\Component;
use App\Models\Table;
use App\Models\FileStorage;

class QrCodes extends Component
{

    public $areaID = null;

    public function downloadQrCode($tableCode, $branchId)
    {
        $filename = 'qrcode-' . $branchId . '-' . str()->slug($tableCode, '-', (auth()->user() ? auth()->user()->locale : 'en')) . '.png';

        $file = FileStorage::where('filename', $filename)->first();

        return download_local_s3($file, 'qrcodes/' . $filename);
    }

    public function downloadBranchQrCode()
    {
        $branch = branch();
        
        if (!$branch) {
            session()->flash('error', __('messages.branchNotFound'));
            return;
        }

        $filename = 'qrcode-branch-' . $branch->id . '-' . $branch->restaurant->id . '.png';

        $file = FileStorage::where('filename', $filename)->first();
        
        if (!$file) {
            session()->flash('error', __('QR code file not found'));
            return;
        }

        return download_local_s3($file, 'qrcodes/' . $filename);
    }

    public function generateQrCode($tableId = null)
    {
        if (!extension_loaded('gd')) {
            session()->flash('error', __('GD extension is not enabled. Please enable GD extension to generate QR codes.'));
            return;
        }

        try {
            if ($tableId) {
                $table = Table::find($tableId);
                if (!$table) {
                    session()->flash('error', __('Table not found'));
                    return;
                }
            } else {
                $table = branch();
                if (!$table) {
                    session()->flash('error', __('messages.branchNotFound'));
                    return;
                }
            }

            $table->generateQrCode();
            session()->flash('success', __('QR code generated successfully'));
        } catch (\Exception $e) {
            session()->flash('error', __('Failed to generate QR code: ') . $e->getMessage());
        }

        $this->redirect(route('qrcodes.index'));
    }

    public function render()
    {
        $branch = branch();
        
        if (!$branch) {
            return view('livewire.qr-code.qr-codes', [
                'tables' => collect(),
                'areas' => collect(),
            ]);
        }

        $query = Area::with(['tables' => function($q) use ($branch) {
            $q->where('branch_id', $branch->id);
        }])->where('branch_id', $branch->id);

        if (!is_null($this->areaID)) {
            $query = $query->where('id', $this->areaID);
        }

        $areas = $query->get();

        return view('livewire.qr-code.qr-codes', [
            'tables' => $areas,
            'areas' => Area::where('branch_id', $branch->id)->get()
        ]);
    }
}
