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

$pageTitle = 'Katalog';
$activePage = 'catalogs';
$msg = '';

if (isset($_GET['delete'])) {
    $stmt = $pdo->prepare("SELECT pdf_file FROM catalogs WHERE id=?");
    $stmt->execute([$_GET['delete']]);
    $row = $stmt->fetch();
    if ($row && $row['pdf_file'] && file_exists(dirname(__DIR__).'/'.$row['pdf_file'])) @unlink(dirname(__DIR__).'/'.$row['pdf_file']);
    $pdo->prepare("DELETE FROM catalogs WHERE id=?")->execute([$_GET['delete']]);
    $msg = adminAlert('Katalog berhasil dihapus.');
}
if (isset($_GET['toggle'])) {
    $pdo->prepare("UPDATE catalogs SET is_active = 1 - is_active WHERE id=?")->execute([$_GET['toggle']]);
    header('Location: catalogs.php'); exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id']??null;
    $title = trim($_POST['title']??'');
    $desc = trim($_POST['description']??'');
    $cat = $_POST['category']??'';
    $sort = (int)($_POST['sort_order']??0);
    $active = isset($_POST['is_active']) ? 1 : 0;
    
    $pdf = $_POST['existing_pdf']??'';
    if (!empty($_FILES['pdf_file']['name'])) {
        $up = uploadPDF($_FILES['pdf_file'], 'assets/files');
        if ($up) $pdf = $up;
    }
    $cover = $_POST['existing_cover']??'';
    if (!empty($_FILES['cover_image']['name'])) {
        $up = uploadFile($_FILES['cover_image'], 'assets/images/catalog');
        if ($up) $cover = $up;
    }
    
    if ($id) {
        $pdo->prepare("UPDATE catalogs SET title=?,description=?,pdf_file=?,cover_image=?,category=?,sort_order=?,is_active=? WHERE id=?")
            ->execute([$title,$desc,$pdf,$cover,$cat,$sort,$active,$id]);
        $msg = adminAlert('Katalog berhasil diperbarui.');
    } else {
        $pdo->prepare("INSERT INTO catalogs (title,description,pdf_file,cover_image,category,sort_order,is_active) VALUES (?,?,?,?,?,?,?)")
            ->execute([$title,$desc,$pdf,$cover,$cat,$sort,$active]);
        $msg = adminAlert('Katalog berhasil ditambahkan.');
    }
}

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

$items = $pdo->query("SELECT * FROM catalogs 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 Katalog' : 'Tambah Katalog' ?></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_pdf" value="<?= $editItem['pdf_file'] ?>">
                        <input type="hidden" name="existing_cover" value="<?= $editItem['cover_image'] ?>">
                    <?php endif; ?>
                    <div class="mb-3"><label class="form-label fw-semibold">Judul <span class="text-danger">*</span></label><input type="text" name="title" class="form-control" required value="<?= htmlspecialchars($editItem['title']??'') ?>"></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="mb-3">
                        <label class="form-label fw-semibold">Kategori</label>
                        <select name="category" class="form-select">
                            <option value="Automotive" <?= ($editItem['category']??'')=='Automotive'?'selected':'' ?>>Automotive</option>
                            <option value="Interior" <?= ($editItem['category']??'')=='Interior'?'selected':'' ?>>Interior</option>
                            <option value="Marine" <?= ($editItem['category']??'')=='Marine'?'selected':'' ?>>Marine</option>
                            <option value="Brand" <?= ($editItem['category']??'')=='Brand'?'selected':'' ?>>Brand</option>
                            <option value="Price" <?= ($editItem['category']??'')=='Price'?'selected':'' ?>>Price List</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">File PDF <?= $editItem ? '(kosong = tidak ganti)' : '' ?></label>
                        <input type="file" name="pdf_file" class="form-control" accept="application/pdf">
                        <?php if ($editItem && $editItem['pdf_file']): ?><div class="mt-1"><i class="bi bi-file-pdf text-danger me-1"></i><small><?= basename($editItem['pdf_file']) ?></small></div><?php endif; ?>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Gambar Cover</label>
                        <input type="file" name="cover_image" class="form-control" accept="image/*">
                        <?php if ($editItem && $editItem['cover_image']): ?><img src="../<?= $editItem['cover_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="catalogs.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 Katalog (<?= count($items) ?>)</div>
            <div class="table-responsive">
                <table class="table mb-0 align-middle">
                    <thead class="table-light"><tr><th>Cover</th><th>Judul</th><th>Kat.</th><th>PDF</th><th>Status</th><th>Aksi</th></tr></thead>
                    <tbody>
                    <?php foreach ($items as $item): ?>
                        <tr>
                            <td><img src="../<?= $item['cover_image'] ?>" style="width:55px;height:70px;object-fit:cover;border-radius:4px;" onerror="this.src='https://via.placeholder.com/55x70?text=PDF'"></td>
                            <td><div class="fw-semibold"><?= htmlspecialchars($item['title']) ?></div><small class="text-muted"><?= htmlspecialchars(substr($item['description']??'',0,50)) ?></small></td>
                            <td><span class="badge bg-secondary"><?= $item['category'] ?></span></td>
                            <td><?php if ($item['pdf_file']): ?><a href="../<?= $item['pdf_file'] ?>" target="_blank" class="btn btn-sm btn-outline-danger"><i class="bi bi-file-pdf"></i></a><?php else: ?><span class="text-muted small">-</span><?php endif; ?></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'; ?>
