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

$pageTitle = 'Produk Brand';
$activePage = 'brand_products';
$msg = '';

// Get brand filter
$brandFilter = $_GET['brand'] ?? '';

// Delete product
if (isset($_GET['delete_product'])) {
    $pdo->prepare("DELETE FROM brand_products WHERE id=?")->execute([$_GET['delete_product']]);
    $msg = adminAlert('Produk brand berhasil dihapus.');
}

// Delete color
if (isset($_GET['delete_color'])) {
    $pdo->prepare("DELETE FROM brand_product_colors WHERE id=?")->execute([$_GET['delete_color']]);
    $msg = adminAlert('Warna berhasil dihapus.');
    $redir = $_GET['back'] ?? 'brand-products.php';
    header("Location: $redir"); exit;
}

// Handle POST - add/edit product
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'save_product') {
        $id = $_POST['id'] ?? null;
        $brand_id = (int)($_POST['brand_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $slug = trim($_POST['slug'] ?? '');
        if (!$slug) $slug = strtolower(preg_replace('/[^a-z0-9]+/', '-', strtolower($name)));
        $desc = trim($_POST['description'] ?? '');
        $sort = (int)($_POST['sort_order'] ?? 0);
        $active = isset($_POST['is_active']) ? 1 : 0;

        $logo = $_POST['existing_logo'] ?? '';
        if (!empty($_FILES['logo_image']['name'])) {
            $up = uploadFile($_FILES['logo_image'], 'assets/images/brand-products');
            if ($up) $logo = $up;
        }

        if ($id) {
            $pdo->prepare("UPDATE brand_products SET brand_id=?,name=?,slug=?,description=?,logo_image=?,sort_order=?,is_active=? WHERE id=?")
                ->execute([$brand_id,$name,$slug,$desc,$logo,$sort,$active,$id]);
            $msg = adminAlert('Produk brand berhasil diperbarui.');
        } else {
            $pdo->prepare("INSERT INTO brand_products (brand_id,name,slug,description,logo_image,sort_order,is_active) VALUES (?,?,?,?,?,?,?)")
                ->execute([$brand_id,$name,$slug,$desc,$logo,$sort,$active]);
            $msg = adminAlert('Produk brand berhasil ditambahkan.');
        }
    }

    if ($_POST['action'] === 'save_color') {
        $id = $_POST['color_id'] ?? null;
        $bp_id = (int)($_POST['brand_product_id'] ?? 0);
        $cname = trim($_POST['color_name'] ?? '');
        $ccode = trim($_POST['color_code'] ?? '');
        $csort = (int)($_POST['color_sort'] ?? 0);

        $cimg = $_POST['existing_color_image'] ?? '';
        if (!empty($_FILES['color_image']['name'])) {
            $up = uploadFile($_FILES['color_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([$bp_id,$cname,$ccode,$cimg,$csort]);
            $msg = adminAlert('Warna berhasil ditambahkan.');
        }
    }
}

// Edit mode
$editProduct = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM brand_products WHERE id=?");
    $stmt->execute([$_GET['edit']]);
    $editProduct = $stmt->fetch();
    if ($editProduct) $brandFilter = $editProduct['brand_id'];
}

// Fetch data
$brands = $pdo->query("SELECT * FROM brands WHERE is_active=1 ORDER BY sort_order")->fetchAll();

if ($brandFilter) {
    $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.brand_id=? ORDER BY bp.sort_order");
    $stmt->execute([$brandFilter]);
    $items = $stmt->fetchAll();
} else {
    $items = $pdo->query("SELECT bp.*, b.name as brand_name FROM brand_products bp JOIN brands b ON bp.brand_id=b.id ORDER BY b.sort_order, bp.sort_order")->fetchAll();
}

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

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <select class="form-select form-select-sm d-inline-block" style="width:auto;" onchange="location='brand-products.php?brand='+this.value">
            <option value="">-- Semua Brand --</option>
            <?php foreach ($brands as $b): ?>
                <option value="<?= $b['id'] ?>" <?= $brandFilter==$b['id']?'selected':'' ?>><?= htmlspecialchars($b['name']) ?></option>
            <?php endforeach; ?>
        </select>
    </div>
</div>

<div class="row g-4">
    <!-- Form -->
    <div class="col-lg-4">
        <div class="card">
            <div class="card-header"><?= $editProduct ? 'Edit Produk Brand' : 'Tambah Produk Brand' ?></div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="save_product">
                    <?php if ($editProduct): ?>
                        <input type="hidden" name="id" value="<?= $editProduct['id'] ?>">
                        <input type="hidden" name="existing_logo" value="<?= $editProduct['logo_image'] ?>">
                    <?php endif; ?>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Brand <span class="text-danger">*</span></label>
                        <select name="brand_id" class="form-select" required>
                            <option value="">-- Pilih Brand --</option>
                            <?php foreach ($brands as $b): ?>
                                <option value="<?= $b['id'] ?>" <?= ($editProduct['brand_id']??$brandFilter)==$b['id']?'selected':'' ?>><?= htmlspecialchars($b['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Nama Produk <span class="text-danger">*</span></label>
                        <input type="text" name="name" class="form-control" required value="<?= htmlspecialchars($editProduct['name']??'') ?>" placeholder="cth: Giorgio, Carrera">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Slug</label>
                        <input type="text" name="slug" class="form-control" value="<?= htmlspecialchars($editProduct['slug']??'') ?>" placeholder="auto-generate jika kosong">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Deskripsi</label>
                        <textarea name="description" class="form-control" rows="3"><?= htmlspecialchars($editProduct['description']??'') ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Logo/Gambar Produk</label>
                        <input type="file" name="logo_image" class="form-control" accept="image/*">
                        <small class="text-muted">Gambar logo produk (akan ditampilkan di grid)</small>
                        <?php if ($editProduct && $editProduct['logo_image']): ?>
                            <div class="mt-2"><img src="../<?= $editProduct['logo_image'] ?>" class="rounded" style="height:60px;background:#000;padding:8px;" onerror="this.style.display='none'"></div>
                        <?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="<?= $editProduct['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" <?= ($editProduct['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"><?= $editProduct ? 'Update' : 'Tambah' ?></button>
                        <?php if ($editProduct): ?><a href="brand-products.php<?= $brandFilter?"?brand=$brandFilter":'' ?>" class="btn btn-outline-secondary">Batal</a><?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- List -->
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header">Daftar Produk 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>Brand</th><th>Warna</th><th>Aksi</th></tr>
                    </thead>
                    <tbody>
                    <?php foreach ($items as $item):
                        $colorCount = $pdo->prepare("SELECT COUNT(*) FROM brand_product_colors WHERE brand_product_id=?");
                        $colorCount->execute([$item['id']]);
                        $cCount = $colorCount->fetchColumn();
                    ?>
                        <tr>
                            <td>
                                <?php if ($item['logo_image']): ?>
                                    <img src="../<?= $item['logo_image'] ?>" style="width:70px;height:45px;object-fit:contain;background:#000;border-radius:4px;padding:4px;" onerror="this.src='https://placehold.co/70x45/000/c9a84c?text=<?= urlencode($item['name']) ?>'">
                                <?php else: ?>
                                    <div style="width:70px;height:45px;background:#000;border-radius:4px;display:flex;align-items:center;justify-content:center;color:#c9a84c;font-size:.7rem;font-weight:700;"><?= htmlspecialchars($item['name']) ?></div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="fw-semibold"><?= htmlspecialchars($item['name']) ?></div>
                                <small class="text-muted"><?= $item['is_active'] ? '<span class="text-success">Aktif</span>' : '<span class="text-danger">Nonaktif</span>' ?></small>
                            </td>
                            <td><span class="badge bg-dark"><?= htmlspecialchars($item['brand_name']) ?></span></td>
                            <td>
                                <a href="brand-product-colors.php?product=<?= $item['id'] ?>" class="btn btn-sm btn-outline-secondary">
                                    <i class="bi bi-palette"></i> <?= $cCount ?> warna
                                </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_product=<?= $item['id'] ?><?= $brandFilter?"&brand=$brandFilter":'' ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Hapus produk ini beserta semua warnanya?')"><i class="bi bi-trash"></i></a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    <?php if (empty($items)): ?>
                        <tr><td colspan="5" class="text-center text-muted py-4">Belum ada produk brand.</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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