<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\DB;
use App\Core\Request;
use App\Core\Response;
use App\Services\PrintSettingsService;
use App\Shared\Support\BarcodeSupport;
use PDO;

final class InventoryBarcodePrintController
{
    private PDO $pdo;

    public function __construct()
    {
        $this->pdo = DB::pdo();
    }

    public function index(): void
    {
        Auth::requireLogin();
        require_permission('inventory.barcode.print');

        Response::view('pages/inventory/barcode_print', [
            'page_title' => 'طباعة باركود',
            'breadcrumbs' => [
                ['label' => 'لوحة التحكم', 'url' => '/admin/dashboard'],
                ['label' => 'المخزن'],
                ['label' => 'طباعة باركود'],
            ],
            'settings' => (new PrintSettingsService($this->pdo))->settings(),
        ]);
    }

    public function print(): void
    {
        Auth::requireLogin();
        require_permission('inventory.barcode.print');

        $itemId = (int) Request::get('item_id', 0);
        $qty = max(1, min(500, (int) Request::get('qty', 1)));
        if ($itemId <= 0) {
            http_response_code(422);
            echo 'يرجى اختيار الصنف أولًا.';
            return;
        }

        $st = $this->pdo->prepare('SELECT id, name, barcode, price FROM items WHERE id = ? LIMIT 1');
        $st->execute([$itemId]);
        $item = $st->fetch(PDO::FETCH_ASSOC) ?: null;
        if (!$item) {
            http_response_code(404);
            echo 'الصنف غير موجود.';
            return;
        }

        $barcodeValue = trim((string) ($item['barcode'] ?? ''));
        if ($barcodeValue === '') {
            http_response_code(422);
            echo 'هذا الصنف لا يحتوي على باركود ليتم طباعته.';
            return;
        }

        $settingsService = new PrintSettingsService($this->pdo);
        $company = company_profile($this->pdo);
        $widthMm = $settingsService->barcodeLabelWidthMm();
        $heightMm = $settingsService->barcodeLabelHeightMm();
        $svg = BarcodeSupport::svgCode39($barcodeValue);
        $showPrice = $settingsService->barcodeShowPrice();
        $showItemName = $settingsService->barcodeShowItemName();
        $autoPrint = (string) Request::get('autoprint', '1') === '1';
        $closeAfterPrint = (string) Request::get('close_after_print', '0') === '1';

        extract([
            'title' => 'طباعة باركود - ' . (string) ($item['name'] ?? ''),
            'company' => $company,
            'item' => $item,
            'qty' => $qty,
            'barcodeSvg' => $svg,
            'widthMm' => $widthMm,
            'heightMm' => $heightMm,
            'autoPrint' => $autoPrint,
            'closeAfterPrint' => $closeAfterPrint,
            'showPrice' => $showPrice,
            'showItemName' => $showItemName,
        ], EXTR_SKIP);

        require APP_PATH . '/views/print/barcode_labels.php';
    }
}
