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

$pageTitle = 'Produk';
$activePage = 'products';
$msg = '';

if (isset($_GET['delete'])) {
    $pdo->prepare("DELETE FROM products WHERE id=?")->execute([$_GET['delete']]);
    $msg = adminAlert('Produk berhasil dihapus.');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id']??null;
    $cat_id = (int)($_POST['category_id']??1);
    $name = trim($_POST['name']??'');
    $desc = trim($_POST['description']??'');
    $spec = trim($_POST['specifications']??'');
    $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/products');
        if ($up) $image = $up;
    }
    if ($id) {
        $pdo->prepare("UPDATE products SET category_id=?,name=?,description=?,specifications=?,image=?,sort_order=?,is_active=? WHERE id=?")
            ->execute([$cat_id,$name,$desc,$spec,$image,$sort,$active,$id]);
        $msg = adminAlert('Produk berhasil diperbarui.');
    } else {
        $pdo->prepare("INSERT INTO products (category_id,name,description,specifications,image,sort_order,is_active) VALUES (?,?,?,?,?,?,?)")
            ->execute([$cat_id,$name,$desc,$spec,$image,$sort,$active]);
        $msg = adminAlert('Produk berhasil ditambahkan.');
    }
}

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

$categories = $pdo->query("SELECT * FROM product_categories ORDER BY sort_order")->fetchAll();
$items = $pdo->query("SELECT p.*, pc.name as cat_name FROM products p JOIN product_categories pc ON p.category_id=pc.id ORDER BY p.category_id, p.sort_order")->fetchAll();
include 'partials/header.php';
?>
<?= $msg ?>
<div class="row g-4">
    <div class="col-lg-4">
        <div class="card">
            <div class="card-header"><?= $editItem ? 'Edit Produk' : 'Tambah Produk' ?></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'] ?>"><?php endif; ?>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Kategori</label>
                        <select name="category_id" class="form-select">
                            <?php foreach ($categories as $c): ?>
                                <option value="<?= $c['id'] ?>" <?= ($editItem['category_id']??'') == $c['id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['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($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">Spesifikasi</label><textarea name="specifications" class="form-control" rows="2"><?= htmlspecialchars($editItem['specifications']??'') ?></textarea></div>
                    <div class="mb-3"><label class="form-label fw-semibold">Foto</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;object-fit:cover;" 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="products.php" class="btn btn-outline-secondary">Batal</a><?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header">Daftar Produk (<?= count($items) ?>)</div>
            <div class="table-responsive">
                <table class="table mb-0 align-middle">
                    <thead class="table-light"><tr><th>Foto</th><th>Nama Produk</th><th>Kategori</th><th>Aksi</th></tr></thead>
                    <tbody>
                    <?php foreach ($items as $item): ?>
                        <tr>
                            <td><img src="../<?= $item['image'] ?>" style="width:70px;height:45px;object-fit:cover;border-radius:4px;" onerror="this.src='https://via.placeholder.com/70x45'"></td>
                            <td><div class="fw-semibold"><?= htmlspecialchars($item['name']) ?></div><small class="text-muted"><?= htmlspecialchars(substr($item['description']??'',0,50)) ?></small></td>
                            <td><span class="badge bg-dark"><?= htmlspecialchars($item['cat_name']) ?></span></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'; ?>
