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

$pageTitle = 'Price List';
$activePage = 'price';
$msg = '';

// ── DELETE price item ──────────────────────────────────────────────────────
if (isset($_GET['delete'])) {
    $pdo->prepare("DELETE FROM price_list WHERE id=?")->execute([$_GET['delete']]);
    header('Location: price.php'); exit;
}

// ── TOGGLE aktif price item ────────────────────────────────────────────────
if (isset($_GET['toggle'])) {
    $pdo->prepare("UPDATE price_list SET is_active = 1 - is_active WHERE id=?")->execute([$_GET['toggle']]);
    header('Location: price.php'); exit;
}

// ── DELETE kategori ────────────────────────────────────────────────────────
if (isset($_GET['del_cat'])) {
    $catId = (int)$_GET['del_cat'];
    // cegah hapus kalau masih ada item
    $cntStmt = $pdo->prepare("SELECT COUNT(*) FROM price_list pl JOIN price_categories pc ON pl.category=pc.name WHERE pc.id=?");
    $cntStmt->execute([$catId]);
    if ($cntStmt->fetchColumn() > 0) {
        $msg = adminAlert('Kategori tidak bisa dihapus karena masih memiliki item harga.', 'danger');
    } else {
        $pdo->prepare("DELETE FROM price_categories WHERE id=?")->execute([$catId]);
        $msg = adminAlert('Kategori berhasil dihapus.', 'success');
    }
}

// ── SAVE kategori (add / edit) ─────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_category'])) {
    $catId   = $_POST['cat_id'] ?? null;
    $catName = trim($_POST['cat_name'] ?? '');
    $catSort = (int)($_POST['cat_sort'] ?? 0);
    if ($catName !== '') {
        if ($catId) {
            $oldName = $pdo->query("SELECT name FROM price_categories WHERE id=$catId")->fetchColumn();
            $pdo->prepare("UPDATE price_categories SET name=?, sort_order=? WHERE id=?")
                ->execute([$catName, $catSort, $catId]);
            // update semua item yang pakai nama lama
            if ($oldName && $oldName !== $catName) {
                $pdo->prepare("UPDATE price_list SET category=? WHERE category=?")->execute([$catName, $oldName]);
            }
            $msg = adminAlert('Kategori berhasil diperbarui.');
        } else {
            try {
                $pdo->prepare("INSERT INTO price_categories (name, sort_order) VALUES (?,?)")->execute([$catName, $catSort]);
                $msg = adminAlert('Kategori baru berhasil ditambahkan.', 'success');
            } catch (\PDOException $e) {
                $msg = adminAlert('Nama kategori sudah ada.', 'danger');
            }
        }
    }
}

// ── SAVE price item (add / edit) ──────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_item'])) {
    $id         = $_POST['id'] ?? null;
    $cat        = $_POST['category'] ?? '';
    $name       = trim($_POST['product_name'] ?? '');
    $desc       = trim($_POST['description'] ?? '');
    $unit       = trim($_POST['unit'] ?? 'meter');
    $price_disp = trim($_POST['price_display'] ?? '');
    $sort       = (int)($_POST['sort_order'] ?? 0);
    $active     = isset($_POST['is_active']) ? 1 : 0;
    if ($id) {
        $pdo->prepare("UPDATE price_list SET category=?,product_name=?,description=?,unit=?,price_display=?,sort_order=?,is_active=? WHERE id=?")
            ->execute([$cat, $name, $desc, $unit, $price_disp, $sort, $active, $id]);
        $msg = adminAlert('Harga berhasil diperbarui.');
    } else {
        $pdo->prepare("INSERT INTO price_list (category,product_name,description,unit,price_display,sort_order,is_active) VALUES (?,?,?,?,?,?,?)")
            ->execute([$cat, $name, $desc, $unit, $price_disp, $sort, $active]);
        $msg = adminAlert('Harga berhasil ditambahkan.', 'success');
    }
}

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

$categories = $pdo->query("SELECT * FROM price_categories ORDER BY sort_order ASC, name ASC")->fetchAll();
$items      = $pdo->query("SELECT * FROM price_list ORDER BY category ASC, sort_order ASC")->fetchAll();

// hitung jumlah item per kategori
$catCounts = [];
foreach ($items as $i) {
    $catCounts[$i['category']] = ($catCounts[$i['category']] ?? 0) + 1;
}

include 'partials/header.php';
?>

<?= $msg ?>

<div class="row g-4">
    <!-- ══ KOLOM KIRI ════════════════════════════════════════════════════ -->
    <div class="col-lg-4 d-flex flex-column gap-4">

        <!-- Form Tambah / Edit Item -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span><?= $editItem ? 'Edit Harga' : 'Tambah Item Harga' ?></span>
                <?php if (!$editItem): ?>
                    <button class="btn btn-sm btn-outline-dark" data-bs-toggle="modal" data-bs-target="#catModal" onclick="resetCatForm()">
                        <i class="bi bi-tag me-1"></i> Kelola Kategori
                    </button>
                <?php endif; ?>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="save_item" value="1">
                    <?php if ($editItem): ?><input type="hidden" name="id" value="<?= $editItem['id'] ?>"><?php endif; ?>

                    <div class="mb-3">
                        <label class="form-label fw-semibold">Kategori</label>
                        <select name="category" class="form-select">
                            <?php foreach ($categories as $c): ?>
                                <option value="<?= htmlspecialchars($c['name']) ?>"
                                    <?= ($editItem['category'] ?? '') === $c['name'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($c['name']) ?>
                                </option>
                            <?php endforeach; ?>
                            <?php if (empty($categories)): ?>
                                <option value="">— Belum ada kategori —</option>
                            <?php endif; ?>
                        </select>
                        <div class="mt-1">
                            <a href="#" class="small text-muted" data-bs-toggle="modal" data-bs-target="#catModal" onclick="resetCatForm()">
                                <i class="bi bi-plus-circle me-1"></i>Tambah kategori baru
                            </a>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-semibold">Nama Produk <span class="text-danger">*</span></label>
                        <input type="text" name="product_name" class="form-control" required value="<?= htmlspecialchars($editItem['product_name'] ?? '') ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Deskripsi</label>
                        <textarea name="description" class="form-control" rows="2"><?= htmlspecialchars($editItem['description'] ?? '') ?></textarea>
                    </div>
                    <div class="row g-2 mb-3">
                        <div class="col">
                            <label class="form-label fw-semibold">Satuan</label>
                            <input type="text" name="unit" class="form-control" value="<?= htmlspecialchars($editItem['unit'] ?? 'meter') ?>">
                        </div>
                        <div class="col">
                            <label class="form-label fw-semibold">Harga (tampil)</label>
                            <input type="text" name="price_display" class="form-control" placeholder="Rp 75.000/m" value="<?= htmlspecialchars($editItem['price_display'] ?? '') ?>">
                        </div>
                    </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="price.php" class="btn btn-outline-secondary">Batal</a><?php endif; ?>
                    </div>
                </form>
            </div>
        </div>

        <!-- Daftar Kategori (ringkasan) -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span>Kategori (<?= count($categories) ?>)</span>
                <button class="btn btn-sm btn-dark" data-bs-toggle="modal" data-bs-target="#catModal" onclick="resetCatForm()">
                    <i class="bi bi-plus-lg me-1"></i> Tambah Kategori
                </button>
            </div>
            <div class="card-body p-0">
                <?php if (empty($categories)): ?>
                    <p class="text-muted text-center py-3 mb-0 small">Belum ada kategori.</p>
                <?php else: ?>
                    <ul class="list-group list-group-flush">
                        <?php foreach ($categories as $c): ?>
                        <li class="list-group-item d-flex justify-content-between align-items-center py-2 px-3">
                            <div>
                                <span class="fw-semibold"><?= htmlspecialchars($c['name']) ?></span>
                                <small class="text-muted ms-2"><?= $catCounts[$c['name']] ?? 0 ?> item</small>
                            </div>
                            <div class="d-flex gap-1">
                                <button class="btn btn-xs btn-outline-secondary"
                                        onclick='editCat(<?= htmlspecialchars(json_encode($c)) ?>)'
                                        data-bs-toggle="modal" data-bs-target="#catModal"
                                        title="Edit">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <?php if (($catCounts[$c['name']] ?? 0) === 0): ?>
                                    <a href="?del_cat=<?= $c['id'] ?>" class="btn btn-xs btn-outline-danger"
                                       onclick="return confirm('Hapus kategori <?= htmlspecialchars(addslashes($c['name'])) ?>?')"
                                       title="Hapus">
                                        <i class="bi bi-trash"></i>
                                    </a>
                                <?php else: ?>
                                    <button class="btn btn-xs btn-outline-danger" disabled title="Masih ada <?= $catCounts[$c['name']] ?> item">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                <?php endif; ?>
                            </div>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>

    </div>

    <!-- ══ KOLOM KANAN ══════════════════════════════════════════════════ -->
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header">Daftar Harga (<?= count($items) ?>)</div>
            <div class="table-responsive">
                <table class="table mb-0 align-middle">
                    <thead class="table-light">
                        <tr><th>Kategori</th><th>Nama Produk</th><th>Satuan</th><th>Harga</th><th>Status</th><th>Aksi</th></tr>
                    </thead>
                    <tbody>
                    <?php foreach ($items as $item): ?>
                        <tr>
                            <td><span class="badge bg-dark"><?= htmlspecialchars($item['category']) ?></span></td>
                            <td>
                                <div class="fw-semibold"><?= htmlspecialchars($item['product_name']) ?></div>
                                <small class="text-muted"><?= htmlspecialchars(substr($item['description'] ?? '', 0, 50)) ?></small>
                            </td>
                            <td class="text-muted"><?= htmlspecialchars($item['unit']) ?></td>
                            <td class="fw-semibold text-success"><?= htmlspecialchars($item['price_display'] ?? '-') ?></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 item ini?')"><i class="bi bi-trash"></i></a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    <?php if (empty($items)): ?>
                        <tr><td colspan="6" class="text-center text-muted py-4">Belum ada data harga.</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- ══ MODAL: Tambah / Edit Kategori ══════════════════════════════════════ -->
<div class="modal fade" id="catModal" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold" id="catModalTitle">Tambah Kategori</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="save_category" value="1">
                <input type="hidden" name="cat_id" id="catId">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Nama Kategori <span class="text-danger">*</span></label>
                        <input type="text" name="cat_name" id="catName" class="form-control" required
                               placeholder="cth: Furniture, Outdoor, dll">
                    </div>
                    <div class="mb-1">
                        <label class="form-label fw-semibold">Urutan Tampil</label>
                        <input type="number" name="cat_sort" id="catSort" class="form-control" value="0">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-dark" id="catSubmitBtn">Simpan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php
$extraJs = <<<JS
<script>
function resetCatForm() {
    document.getElementById('catModalTitle').textContent = 'Tambah Kategori';
    document.getElementById('catId').value = '';
    document.getElementById('catName').value = '';
    document.getElementById('catSort').value = '0';
    document.getElementById('catSubmitBtn').textContent = 'Simpan';
}
function editCat(data) {
    document.getElementById('catModalTitle').textContent = 'Edit Kategori';
    document.getElementById('catId').value = data.id;
    document.getElementById('catName').value = data.name;
    document.getElementById('catSort').value = data.sort_order;
    document.getElementById('catSubmitBtn').textContent = 'Update';
}
</script>
JS;
include 'partials/footer.php';
?>
