<?php
declare(strict_types=1);
namespace App\Controllers;

use App\Core\Controller;
use App\Core\SessionAuth;
use App\Repositories\CategoryRepository;
use App\Repositories\CustomerRepository;
use App\Repositories\InvoiceRepository;
use App\Services\InvoiceService;

final class InvoiceController extends Controller {
    public function index(): void {
        app()->get(SessionAuth::class)->requireLogin();
        $categories = (new CategoryRepository())->active();
        $recentInvoices = (new InvoiceRepository())->recent();
        $this->view('invoices/index', compact('categories','recentInvoices'));
    }

    public function store(): void {
        app()->get(SessionAuth::class)->requireLogin();
        verify_csrf();
        try {
            $invoiceId = (new InvoiceService())->createFromRequest($_POST);
            flash('success', 'تم إنشاء الفاتورة بنجاح');
            redirect(base_url('?page=invoice_show&id=' . $invoiceId));
        } catch (\Throwable $e) {
            flash('error', $e->getMessage());
            redirect(base_url('?page=invoices'));
        }
    }

    public function show(): void {
        app()->get(SessionAuth::class)->requireLogin();
        $id = (int)($_GET['id'] ?? 0);
        $repo = new InvoiceRepository();
        $invoice = $repo->find($id);
        if (!$invoice) {
            http_response_code(404);
            $this->view('errors/404');
            return;
        }
        $lines = $repo->lines($id);
        $this->view('invoices/show', compact('invoice','lines'));
    }

    public function customerLookup(): void {
        app()->get(SessionAuth::class)->requireLogin();
        header('Content-Type: application/json; charset=utf-8');
        $value = trim((string)($_GET['q'] ?? ''));
        echo json_encode((new CustomerRepository())->findByIdentifier($value), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    }

    public function customerSearch(): void {
        app()->get(SessionAuth::class)->requireLogin();
        header('Content-Type: application/json; charset=utf-8');
        $q = trim((string)($_GET['q'] ?? ''));
        echo json_encode((new CustomerRepository())->search($q), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    }
}
