<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Core\Auth;
use App\Core\Database;
use PDO;

class CatalogController extends Controller
{
    public function index(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        Auth::requireRole(['admin']);
        $pdo = Database::pdo();
        // Tolérer l'absence de tables de catalogue
        try { $categories = $pdo->query('SELECT * FROM cost_categories ORDER BY name')->fetchAll(); } catch (\Throwable $e) { $categories = []; }
        try { $items = $pdo->query('SELECT i.*, c.name as category_name FROM cost_items i JOIN cost_categories c ON c.id=i.category_id ORDER BY c.name, i.designation')->fetchAll(); } catch (\Throwable $e) { $items = []; }
        $this->view('catalog/index', compact('categories','items'));
    }

    public function storeCategory(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        Auth::requireRole(['admin']);
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { $this->redirect('/catalog'); }
        $name = trim($_POST['name'] ?? '');
        if ($name) {
            $pdo = Database::pdo();
            try {
                $stmt = $pdo->prepare('INSERT INTO cost_categories(name) VALUES(?)');
                $stmt->execute([$name]);
            } catch (\Throwable $e) { /* ignorer si table manquante */ }
        }
        $this->redirect('/catalog');
    }

    public function storeItem(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        Auth::requireRole(['admin']);
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { $this->redirect('/catalog'); }
        $category_id = (int)($_POST['category_id'] ?? 0);
        $designation = trim($_POST['designation'] ?? '');
        $unit = trim($_POST['unit'] ?? 'u');
        $unit_price = (float)($_POST['unit_price'] ?? 0);
        $currency = trim($_POST['currency'] ?? 'XOF');
        if ($category_id && $designation && $unit_price >= 0) {
            $pdo = Database::pdo();
            try {
                $stmt = $pdo->prepare('INSERT INTO cost_items(category_id,designation,unit,unit_price,currency) VALUES(?,?,?,?,?)');
                $stmt->execute([$category_id,$designation,$unit,$unit_price,$currency]);
            } catch (\Throwable $e) { /* ignorer si table manquante */ }
        }
        $this->redirect('/catalog');
    }
}
