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

$productId = (int)($_GET['product'] ?? 0);
if (!$productId) { header('Location: brand-products.php'); exit; }

$stmt = $pdo->prepare("SELECT bp.*, b.name as brand_name FROM brand_products bp JOIN brands b ON bp.brand_id=b.id WHERE bp.id=?");
$stmt->execute([$productId]);
$product = $stmt->fetch();
if (!$product) { header('Location: brand-products.php'); exit; }

$pageTitle = 'Warna - ' . $product['brand_name'] . ' ' . $product['name'];
$activePage = 'brand_products';
$msg = '';

// Delete
if (isset($_GET['delete'])) {
    $pdo->prepare("DELETE FROM brand_product_colors WHERE id=? AND brand_product_id=?")->execute([$_GET['delete'], $productId]);
    $msg = adminAlert('Warna berhasil dihapus.');
}

// Save
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? null;
    $cname = trim($_POST['color_name'] ?? '');
    $ccode = trim($_POST['color_code'] ?? '');
    $csort = (int)($_POST['sort_order'] ?? 0);

    $cimg = $_POST['existing_image'] ?? '';
    if (!empty($_FILES['image']['name'])) {
        $up = uploadFile($_FILES['image'], 'assets/images/brand-products/colors');
        if ($up) $cimg = $up;
    }

    if ($id) {
        $pdo->prepare("UPDATE brand_product_colors SET color_name=?,color_code=?,image=?,sort_order=? WHERE id=?")
            ->execute([$cname,$ccode,$cimg,$csort,$id]);
        $msg = adminAlert('Warna berhasil diperbarui.');
    } else {
        $pdo->prepare("INSERT INTO brand_product_colors (brand_product_id,color_name,color_code,image,sort_order) VALUES (?,?,?,?,?)")
            ->execute([$productId,$cname,$ccode,$cimg,$csort]);
        $msg = adminAlert('Warna berhasil ditambahkan.');
    }
}

// Edit mode
$editColor = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM brand_product_colors WHERE id=? AND brand_product_id=?");
    $stmt->execute([$_GET['edit'], $productId]);
    $editColor = $stmt->fetch();
}

$colors = $pdo->prepare("SELECT * FROM brand_product_colors WHERE brand_product_id=? ORDER BY sort_order");
$colors->execute([$productId]);
$colorList = $colors->fetchAll();

include 'partials/header.php';
?>
<?= $msg ?>

<div class="mb-3">
    <a href="brand-products.php?brand=<?= $product['brand_id'] ?>" class="btn btn-sm btn-outline-secondary"><i class="bi bi-arrow-left"></i> Kembali ke Produk Brand</a>
    <span class="ms-2 fw-semibold"><?= htmlspecialchars($product['brand_name']) ?> — <?= htmlspecialchars($product['name']) ?></span>
</div>

<div class="row g-4">
    <!-- Form -->
    <div class="col-lg-4">
        <div class="card">
            <div class="card-header"><?= $editColor ? 'Edit Warna' : 'Tambah Warna' ?></div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <?php if ($editColor): ?>
                        <input type="hidden" name="id" value="<?= $editColor['id'] ?>">
                        <input type="hidden" name="existing_image" value="<?= $editColor['image'] ?>">
                    <?php endif; ?>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Nama Warna <span class="text-danger">*</span></label>
                        <input type="text" name="color_name" class="form-control" required value="<?= htmlspecialchars($editColor['color_name']??'') ?>" placeholder="cth: BLACK, IVORY">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Kode Warna</label>
                        <input type="text" name="color_code" class="form-control" value="<?= htmlspecialchars($editColor['color_code']??'') ?>" placeholder="cth: MB 6001">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Foto Swatch</label>
                        <input type="file" name="image" class="form-control" accept="image/*">
                        <small class="text-muted">Foto tekstur/swatch warna</small>
                        <?php if ($editColor && $editColor['image']): ?>
                            <div class="mt-2"><img src="../<?= $editColor['image'] ?>" class="rounded" style="width:60px;height:60px;object-fit:cover;" onerror="this.style.display='none'"></div>
                        <?php endif; ?>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Urutan</label>
                        <input type="number" name="sort_order" class="form-control" value="<?= $editColor['sort_order']??0 ?>">
                    </div>
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-dark"><?= $editColor ? 'Update' : 'Tambah' ?></button>
                        <?php if ($editColor): ?><a href="brand-product-colors.php?product=<?= $productId ?>" class="btn btn-outline-secondary">Batal</a><?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Color Grid -->
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header">Varian Warna (<?= count($colorList) ?>)</div>
            <div class="card-body">
                <div class="row g-3">
                    <?php foreach ($colorList as $c): ?>
                    <div class="col-4 col-sm-3 col-md-2">
                        <div class="text-center">
                            <?php if ($c['image']): ?>
                                <img src="../<?= htmlspecialchars($c['image']) ?>" class="rounded mb-1" style="width:100%;aspect-ratio:1;object-fit:cover;border:1px solid #ddd;" onerror="this.src='https://placehold.co/100/ddd/666?text=<?= urlencode($c['color_name']) ?>'">
                            <?php else: ?>
                                <div class="rounded mb-1 bg-light d-flex align-items-center justify-content-center" style="width:100%;aspect-ratio:1;border:1px solid #ddd;font-size:.65rem;color:#888;"><?= htmlspecialchars($c['color_name']) ?></div>
                            <?php endif; ?>
                            <div class="fw-semibold" style="font-size:.7rem;"><?= htmlspecialchars($c['color_name']) ?></div>
                            <div class="text-muted" style="font-size:.6rem;"><?= htmlspecialchars($c['color_code']) ?></div>
                            <div class="mt-1">
                                <a href="?product=<?= $productId ?>&edit=<?= $c['id'] ?>" class="btn btn-xs btn-outline-primary" style="font-size:.6rem;padding:1px 6px;"><i class="bi bi-pencil"></i></a>
                                <a href="?product=<?= $productId ?>&delete=<?= $c['id'] ?>" class="btn btn-xs btn-outline-danger" style="font-size:.6rem;padding:1px 6px;" onclick="return confirm('Hapus warna ini?')"><i class="bi bi-trash"></i></a>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    <?php if (empty($colorList)): ?>
                        <div class="col-12 text-center text-muted py-4"><i class="bi bi-palette display-4 d-block mb-2"></i>Belum ada varian warna.</div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include 'partials/footer.php'; ?>
