<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\DB;
use App\Core\Request;
use App\Core\Response;
use App\Repositories\StockVoucherRepository;
use App\Services\StockVoucherService;
use Throwable;

final class StockVoucherController
{
    private StockVoucherRepository $repo;
    private StockVoucherService $service;

    public function __construct(private ?\PDO $pdo = null)
    {
        $this->pdo ??= DB::pdo();
        $this->repo = new StockVoucherRepository($this->pdo);
        $this->service = new StockVoucherService($this->pdo, $this->repo);
    }

    public function handle(): void
    {
        Auth::requireLogin();
        $this->service->initSessionState();
        $state = $this->service->getState(Request::all());

        try {
            if (Request::isPost()) {
                Csrf::verify();
                $this->handlePost((string) Request::post('action', ''), $state);
                return;
            }
            $this->render($state);
        } catch (Throwable $e) {
            Response::flash('danger', 'خطأ: ' . $e->getMessage());
            Response::redirect('/inventory/stock-voucher');
        }
    }

    private function handlePost(string $action, array $state): void
    {
        if ($action === 'noop') {
            Response::redirect('/inventory/stock-voucher');
            return;
        }
        if ($action === 'add_line') {
            $unitId = Request::int('unit_id');
            $this->service->addLine(Request::int('item_id'), (float) Request::post('qty', 0), $unitId > 0 ? $unitId : null);
            Response::redirect('/inventory/stock-voucher');
            return;
        }
        if ($action === 'remove_line') {
            $this->service->removeLine(Request::int('i'));
            Response::redirect('/inventory/stock-voucher');
            return;
        }
        if ($action === 'update_line') {
            $unitId = Request::int('unit_id');
            $this->service->updateLine($state['docType'], Request::int('i'), (float) Request::post('qty', 0), $unitId > 0 ? $unitId : null);
            Response::flash('success', 'تم حفظ السطر');
            Response::redirect('/inventory/stock-voucher');
            return;
        }
        if ($action === 'clear') {
            $this->service->clear();
            Response::redirect('/inventory/stock-voucher');
            return;
        }
        if ($action === 'post') {
            $docId = $this->service->post($state);
            Response::flash('success', 'تم ترحيل الإذن');
            Response::redirect('/inventory/warehouse-docs/view?id=' . $docId);
            return;
        }
    }

    private function render(array $state): void
    {
        $items = $this->repo->items();
        $itemsMap = [];
        foreach ($items as $it) $itemsMap[(int)$it['id']] = $it;
        Response::view('pages/stock/stock_voucher', [
            'warehouses' => $this->repo->warehouses(),
            'items' => $items,
            'units' => $this->repo->units(),
            'doc_type' => $state['docType'],
            'warehouse_id' => $state['warehouseId'],
            'to_warehouse_id' => $state['toWarehouseId'],
            'doc_date' => $state['docDate'],
            'notes' => $state['notes'],
            'lines' => $_SESSION['wh_doc_lines'] ?? [],
            'items_map' => $itemsMap,
            'page_title' => 'إذن مخزني',
            'breadcrumbs' => [['label'=>'لوحة التحكم','url'=>'/admin/dashboard'], ['label'=>'إذن مخزني']],
        ]);
    }
}
