<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('category_management');

$pdo = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'add' || $action === 'edit') {
        $id = (int)($_POST['id'] ?? 0);
        $name = trim($_POST['name']);
        $description = trim($_POST['description']);
        $status = isset($_POST['status']) ? 1 : 0;
        if (empty($name)) { $_SESSION['error'] = 'Brand name is required.'; }
        else {
            try {
                if ($action === 'add') {
                    $stmt = $pdo->prepare("INSERT INTO brands (brand_name, description, status) VALUES (?,?,?)");
                    $stmt->execute([$name, $description, $status]);
                    $_SESSION['success'] = 'Brand added successfully.';
                } else {
                    $stmt = $pdo->prepare("UPDATE brands SET brand_name=?, description=?, status=? WHERE id=?");
                    $stmt->execute([$name, $description, $status, $id]);
                    $_SESSION['success'] = 'Brand updated successfully.';
                }
            } catch (PDOException $e) { $_SESSION['error'] = 'Error: ' . $e->getMessage(); }
        }
        header('Location: brands.php'); exit;
    }
    if ($action === 'delete') {
        $id = (int)$_POST['id'];
        $check = $pdo->prepare("SELECT COUNT(*) FROM products WHERE brand_id=?");
        $check->execute([$id]);
        if ($check->fetchColumn() > 0) {
            $_SESSION['error'] = 'Cannot delete: this brand is used by products.';
        } else {
            $stmt = $pdo->prepare("DELETE FROM brands WHERE id=?");
            $stmt->execute([$id]);
            $_SESSION['success'] = 'Brand deleted successfully.';
        }
        header('Location: brands.php'); exit;
    }
}

$brands = $pdo->query("SELECT b.*, (SELECT COUNT(*) FROM products WHERE brand_id=b.id) as product_count FROM brands b ORDER BY b.brand_name")->fetchAll();
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="page-title mb-0"><i class="fas fa-tag me-2"></i>Brands</h4>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#brandModal" onclick="resetBrandForm()"><i class="fas fa-plus me-1"></i>Add Brand</button>
        </div>
        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="brandsTable" class="table table-hover datatable">
                        <thead><tr><th>Name</th><th>Description</th><th>Products</th><th>Status</th><th>Actions</th></tr></thead>
                        <tbody>
                            <?php foreach ($brands as $b): ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($b['brand_name']) ?></strong></td>
                                <td><?= htmlspecialchars($b['description'] ?? '-') ?></td>
                                <td><span class="badge bg-secondary"><?= (int)$b['product_count'] ?></span></td>
                                <td><?= $b['status'] ? '<span class="badge badge-completed">Active</span>' : '<span class="badge badge-cancelled">Inactive</span>' ?></td>
                                <td>
                                    <button class="btn btn-sm btn-info" onclick="editBrand(<?= htmlspecialchars(json_encode($b)) ?>)"><i class="fas fa-edit"></i></button>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this brand?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $b['id'] ?>">
                                        <button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="brandModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" id="brandAction" value="add">
                <input type="hidden" name="id" id="brandId" value="0">
                <div class="modal-header"><h5 class="modal-title" id="brandModalTitle">Add Brand</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Brand Name *</label>
                        <input type="text" name="name" id="brandName" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea name="description" id="brandDesc" class="form-control" rows="2"></textarea>
                    </div>
                    <div class="form-check">
                        <input type="checkbox" name="status" id="brandStatus" class="form-check-input" checked>
                        <label class="form-check-label">Active</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function resetBrandForm() { $('#brandAction').val('add');$('#brandId').val(0);$('#brandModalTitle').text('Add Brand');$('#brandName').val('');$('#brandDesc').val('');$('#brandStatus').prop('checked',true); }
function editBrand(b) { $('#brandAction').val('edit');$('#brandId').val(b.id);$('#brandModalTitle').text('Edit Brand: '+b.brand_name);$('#brandName').val(b.brand_name);$('#brandDesc').val(b.description);$('#brandStatus').prop('checked',b.status==1);$('#brandModal').modal('show'); }
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
