<?php
session_start();
require_once '../config/db.php';
require_once 'auth.php';

$pageTitle = 'Brand';
$activePage = 'brands';
$msg = '';

if (isset($_GET['delete'])) {
    $pdo->prepare("DELETE FROM brands WHERE id=?")->execute([$_GET['delete']]);
    $msg = adminAlert('Brand berhasil dihapus.');
}
if (isset($_GET['toggle'])) {
    $pdo->prepare("UPDATE brands SET is_active = 1 - is_active WHERE id=?")->execute([$_GET['toggle']]);
    header('Location: brands.php'); exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id']??null;
    $name = trim($_POST['name']??'');
    $desc = trim($_POST['description']??'');
    $colors = trim($_POST['color_variants']??'');
    $cat = trim($_POST['category']??'');
    $sort = (int)($_POST['sort_order']??0);
    $active = isset($_POST['is_active']) ? 1 : 0;
    
    $image = $_POST['existing_image']??'';
    if (!empty($_FILES['image']['name'])) {
        $up = uploadFile($_FILES['image'], 'assets/images/brands');
        if ($up) $image = $up;
    }
    $sample = $_POST['existing_sample']??'';
    if (!empty($_FILES['sample_image']['name'])) {
        $up = uploadFile($_FILES['sample_image'], 'assets/images/brands');
        if ($up) $sample = $up;
    }
    
    if ($id) {
        $pdo->prepare("UPDATE brands SET name=?,description=?,image=?,sample_image=?,color_variants=?,category=?,sort_order=?,is_active=? WHERE id=?")
            ->execute([$name,$desc,$image,$sample,$colors,$cat,$sort,$active,$id]);
        $msg = adminAlert('Brand berhasil diperbarui.');
    } else {
        $pdo->prepare("INSERT INTO brands (name,description,image,sample_image,color_variants,category,sort_order,is_active) VALUES (?,?,?,?,?,?,?,?)")
            ->execute([$name,$desc,$image,$sample,$colors,$cat,$sort,$active]);
        $msg = adminAlert('Brand berhasil ditambahkan.');
    }
}

$editItem = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM brands WHERE id=?");
    $stmt->execute([$_GET['edit']]);
    $editItem = $stmt->fetch();
}

$items = $pdo->query("SELECT * FROM brands ORDER BY sort_order ASC")->fetchAll();
include 'partials/header.php';
?>
<?= $msg ?>
<div class="row g-4">
    <div class="col-lg-5">
        <div class="card">
            <div class="card-header"><?= $editItem ? 'Edit Brand' : 'Tambah Brand' ?></div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <?php if ($editItem): ?>
                        <input type="hidden" name="id" value="<?= $editItem['id'] ?>">
                        <input type="hidden" name="existing_image" value="<?= $editItem['image'] ?>">
                        <input type="hidden" name="existing_sample" value="<?= $editItem['sample_image'] ?>">
                    <?php endif; ?>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Nama Brand <span class="text-danger">*</span></label>
                        <input type="text" name="name" class="form-control" required value="<?= htmlspecialchars($editItem['name']??'') ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Deskripsi</label>
                        <textarea name="description" class="form-control" rows="3"><?= htmlspecialchars($editItem['description']??'') ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Kategori</label>
                        <input type="text" name="category" class="form-control" placeholder="e.g. Automotive, Interior, Marine" value="<?= htmlspecialchars($editItem['category']??'') ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Varian Warna</label>
                        <input type="text" name="color_variants" class="form-control" placeholder="e.g. Hitam, Coklat, Cream" value="<?= htmlspecialchars($editItem['color_variants']??'') ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Logo/Foto Brand</label>
                        <input type="file" name="image" class="form-control" accept="image/*">
                        <?php if ($editItem && $editItem['image']): ?><img src="../<?= $editItem['image'] ?>" class="mt-1 rounded" style="height:60px;" onerror="this.style.display='none'"><?php endif; ?>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Foto Sampel/Tekstur</label>
                        <input type="file" name="sample_image" class="form-control" accept="image/*">
                        <?php if ($editItem && $editItem['sample_image']): ?><img src="../<?= $editItem['sample_image'] ?>" class="mt-1 rounded" style="height:60px;" onerror="this.style.display='none'"><?php endif; ?>
                    </div>
                    <div class="row g-2 mb-3">
                        <div class="col"><label class="form-label fw-semibold">Urutan</label><input type="number" name="sort_order" class="form-control" value="<?= $editItem['sort_order']??0 ?>"></div>
                        <div class="col d-flex align-items-end pb-1"><div class="form-check"><input class="form-check-input" type="checkbox" name="is_active" id="ia" <?= ($editItem['is_active']??1)?'checked':'' ?>><label class="form-check-label fw-semibold" for="ia">Aktif</label></div></div>
                    </div>
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-dark"><?= $editItem ? 'Update' : 'Tambah' ?></button>
                        <?php if ($editItem): ?><a href="brands.php" class="btn btn-outline-secondary">Batal</a><?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div class="col-lg-7">
        <div class="card">
            <div class="card-header">Daftar Brand (<?= count($items) ?>)</div>
            <div class="table-responsive">
                <table class="table mb-0 align-middle">
                    <thead class="table-light"><tr><th>Logo</th><th>Nama</th><th>Kategori</th><th>Status</th><th>Aksi</th></tr></thead>
                    <tbody>
                    <?php foreach ($items as $item): ?>
                        <tr>
                            <td><img src="../<?= $item['image'] ?>" style="width:60px;height:40px;object-fit:contain;border-radius:4px;border:1px solid #eee;" onerror="this.src='https://via.placeholder.com/60x40?text=Brand'"></td>
                            <td><div class="fw-semibold"><?= htmlspecialchars($item['name']) ?></div><small class="text-muted"><?= htmlspecialchars($item['color_variants']??'') ?></small></td>
                            <td><span class="badge bg-secondary"><?= htmlspecialchars($item['category']??'-') ?></span></td>
                            <td><a href="?toggle=<?= $item['id'] ?>" class="badge <?= $item['is_active'] ? 'badge-active' : 'badge-inactive' ?> text-decoration-none"><?= $item['is_active'] ? 'Aktif' : 'Off' ?></a></td>
                            <td>
                                <a href="?edit=<?= $item['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-pencil"></i></a>
                                <a href="?delete=<?= $item['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Hapus?')"><i class="bi bi-trash"></i></a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php include 'partials/footer.php'; ?>
