<?php
class BrandController extends Controller
{
    public function index(): void
    {
        Auth::requirePermission('products.view');
        $brands = Database::fetchAll('SELECT b.*,(SELECT COUNT(*) FROM products WHERE brand_id=b.id) AS product_count FROM brands b ORDER BY b.brand_name');
        $pageTitle='Brands';
        ob_start(); require APP_PATH.'/views/brands/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('brand_name',''));
        if (!$name) { $this->flash('error','Name required.'); $this->back(); return; }
        Database::insert('INSERT INTO brands (brand_name,description,status) VALUES (?,?,?)',[$name,trim($this->post('description','')),'active']);
        redirectWith(APP_URL.'/brands','success','Brand added.');
    }
    public function update(string $id): void
    {
        Auth::requirePermission('products.edit'); Auth::requireCsrf();
        Database::execute('UPDATE brands SET brand_name=?,description=?,status=? WHERE id=?',
            [trim($this->post('brand_name','')),trim($this->post('description','')),$this->post('status','active'),(int)$id]);
        redirectWith(APP_URL.'/brands','success','Brand updated.');
    }
    public function delete(string $id): void
    {
        Auth::requirePermission('products.delete');
        Auth::requireCsrf();

        $brandId = (int) $id;
        $brand = Database::fetchOne('SELECT * FROM brands WHERE id = ?', [$brandId]);
        if (!$brand) {
            redirectWith(APP_URL.'/brands', 'error', 'Brand not found.');
            return;
        }

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

        if ($productCount > 0) {
            // Has products — cannot hard delete safely. Deactivate instead.
            Database::execute("UPDATE brands SET status='inactive' WHERE id=?", [$brandId]);
            Auth::logAudit(Auth::id(), 'brand_deactivate', 'brands',
                "Brand \"{$brand['brand_name']}\" deactivated ({$productCount} products attached).");
            redirectWith(APP_URL.'/brands', 'success',
                "\"{$brand['brand_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 brands WHERE id = ?', [$brandId]);
            Auth::logAudit(Auth::id(), 'brand_delete', 'brands',
                "Brand \"{$brand['brand_name']}\" permanently deleted.");
            redirectWith(APP_URL.'/brands', 'success',
                "\"{$brand['brand_name']}\" deleted permanently.");
        } catch (\Exception $e) {
            redirectWith(APP_URL.'/brands', 'error', 'Delete failed: ' . $e->getMessage());
        }
    }
}