<?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\WarehouseRepository;
use App\Services\WarehouseService;
use Throwable;
use App\Modules\Inventory\Application\Services\InventoryRouteContext;

final class WarehouseController
{
    private \PDO $pdo;
    private WarehouseRepository $warehouses;
    private WarehouseService $service;

    public function __construct()
    {
        $this->pdo = DB::pdo();
        $this->warehouses = new WarehouseRepository($this->pdo);
        $this->service = new WarehouseService($this->pdo, $this->warehouses);
    }

    public function handle(): void
    {
        Auth::requireLogin();
        $routeContext = new InventoryRouteContext();
        $routeContext = new InventoryRouteContext();

        try {
            if (Request::isPost()) {
                $this->handlePost();
                return;
            }

            $action = (string) Request::get('action', '');
            $id = (int) Request::get('id', 0);
            $edit = ($action === 'edit' && $id > 0) ? ($this->warehouses->findById($id) ?: null) : null;

            Response::view('pages/warehouse/index', [
                'rows' => $this->warehouses->all(),
                'edit_wh' => $edit,
                'has_allow_negative' => $this->warehouses->hasAllowNegativeColumn(),
                'page_title' => 'المخازن',
                'breadcrumbs' => [$routeContext->dashboardCrumb(), ['label'=>'المخازن']],
            ]);
        } catch (Throwable $e) {
            Response::flash('danger', 'خطأ: ' . $e->getMessage());
            Response::redirect($routeContext->warehousesPath());
        }
    }

    private function handlePost(): void
    {
        $routeContext = new InventoryRouteContext();
        Csrf::verify();
        $action = (string) Request::post('action', '');
        if ($action === 'save') {
            $this->service->save(Request::all());
            Response::flash('success', 'تم الحفظ');
            Response::redirect($routeContext->warehousesPath());
        }
    }
}
