<?php
class CategoryController extends Controller
{
    public function index(): void
    {
        Auth::requirePermission('products.view');
        $categories = Database::fetchAll('SELECT c.*,(SELECT COUNT(*) FROM products WHERE category_id=c.id) AS product_count FROM categories c ORDER BY c.category_name');
        $pageTitle='Categories';
        ob_start(); require APP_PATH.'/views/categories/index.php'; $content=ob_get_clean();
        require APP_PATH.'/views/layouts/main.php';
    }
    public function store(): void
    {
        Auth::requirePermission('products.create'); Auth::requireCsrf();
        $name = trim($this->post('category_name',''));
        if (!$name) { $this->flash('error','Name required.'); $this->back(); return; }
        Database::insert('INSERT INTO categories (category_name,description,status) VALUES (?,?,?)',[$name,trim($this->post('description','')), 'active']);
        redirectWith(APP_URL.'/categories','success','Category added.');
    }
    public function update(string $id): void
    {
        Auth::requirePermission('products.edit'); Auth::requireCsrf();
        Database::execute('UPDATE categories SET category_name=?,description=?,status=? WHERE id=?',
            [trim($this->post('category_name','')),trim($this->post('description','')),$this->post('status','active'),(int)$id]);
        redirectWith(APP_URL.'/categories','success','Category updated.');
    }
    public function delete(string $id): void
    {
        Auth::requirePermission('products.delete');
        Auth::requireCsrf();

        $catId = (int) $id;
        $cat = Database::fetchOne('SELECT * FROM categories WHERE id = ?', [$catId]);
        if (!$cat) {
            redirectWith(APP_URL.'/categories', 'error', 'Category not found.');
            return;
        }

        $productCount = (int) Database::fetchColumn(
            'SELECT COUNT(*) FROM products WHERE category_id = ?', [$catId]
        );

        if ($productCount > 0) {
            // Has products — cannot hard delete safely. Deactivate instead.
            Database::execute("UPDATE categories SET status='inactive' WHERE id=?", [$catId]);
            Auth::logAudit(Auth::id(), 'category_deactivate', 'categories',
                "Category \"{$cat['category_name']}\" deactivated ({$productCount} products attached).");
            redirectWith(APP_URL.'/categories', 'success',
                "\"{$cat['category_name']}\" has {$productCount} product(s) assigned, so it was ".
                'deactivated instead of deleted.');
            return;
        }

        // No products — safe to permanently delete
        try {
            Database::execute('DELETE FROM categories WHERE id = ?', [$catId]);
            Auth::logAudit(Auth::id(), 'category_delete', 'categories',
                "Category \"{$cat['category_name']}\" permanently deleted.");
            redirectWith(APP_URL.'/categories', 'success',
                "\"{$cat['category_name']}\" deleted permanently.");
        } catch (\Exception $e) {
            redirectWith(APP_URL.'/categories', 'error', 'Delete failed: ' . $e->getMessage());
        }
    }
}