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

$pageTitle = 'Our Projects';
$activePage = 'projects';
$msg = '';

if (isset($_GET['delete'])) {
    $pdo->prepare("DELETE FROM our_projects WHERE id=?")->execute([$_GET['delete']]);
    $msg = adminAlert('Project berhasil dihapus.');
}
if (isset($_GET['toggle'])) {
    $pdo->prepare("UPDATE our_projects SET is_active = 1 - is_active WHERE id=?")->execute([$_GET['toggle']]);
    header('Location: projects.php'); exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id']??null;
    $data = [
        trim($_POST['name']??''),
        trim($_POST['location']??''),
        trim($_POST['project_value']??''),
        trim($_POST['description']??''),
        $_POST['category']??'',
        (int)($_POST['year']??date('Y')),
        (int)($_POST['sort_order']??0),
        isset($_POST['is_active'])?1:0,
    ];
    $image = $_POST['existing_image']??'';
    if (!empty($_FILES['image']['name'])) {
        $up = uploadFile($_FILES['image'], 'assets/images/projects');
        if ($up) $image = $up;
    }
    if ($id) {
        $data[] = $id;
        $pdo->prepare("UPDATE our_projects SET name=?,location=?,project_value=?,description=?,image=?,category=?,year=?,sort_order=?,is_active=? WHERE id=?")
            ->execute(array_merge(array_slice($data,0,4), [$image], array_slice($data,4)));
        $msg = adminAlert('Project berhasil diperbarui.');
    } else {
        $pdo->prepare("INSERT INTO our_projects (name,location,project_value,description,image,category,year,sort_order,is_active) VALUES (?,?,?,?,?,?,?,?,?)")
            ->execute(array_merge(array_slice($data,0,4), [$image], array_slice($data,4)));
        $msg = adminAlert('Project berhasil ditambahkan.');
    }
}

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

$items = $pdo->query("SELECT * FROM our_projects ORDER BY sort_order ASC, id DESC")->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 Project' : 'Tambah Project' ?></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">Nama Project <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">Lokasi</label><input type="text" name="location" class="form-control" value="<?= htmlspecialchars($editItem['location']??'') ?>"></div>
                    <div class="mb-3"><label class="form-label fw-semibold">Nilai Project</label><input type="text" name="project_value" class="form-control" placeholder="e.g. Rp 1,5 Miliar" value="<?= htmlspecialchars($editItem['project_value']??'') ?>"></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="row g-2 mb-3">
                        <div class="col">
                            <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>
                            </select>
                        </div>
                        <div class="col"><label class="form-label fw-semibold">Tahun</label><input type="number" name="year" class="form-control" value="<?= $editItem['year']??date('Y') ?>" min="2000" max="2099"></div>
                    </div>
                    <div class="mb-3"><label class="form-label fw-semibold">Foto Project</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="projects.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 Projects (<?= count($items) ?>)</div>
            <div class="table-responsive">
                <table class="table mb-0 align-middle">
                    <thead class="table-light"><tr><th>Foto</th><th>Nama Project</th><th>Lokasi</th><th>Nilai</th><th>Status</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><span class="badge bg-secondary small"><?= $item['category'] ?> <?= $item['year'] ?></span></td>
                            <td class="text-muted small"><?= htmlspecialchars($item['location']??'-') ?></td>
                            <td class="text-muted small"><?= htmlspecialchars($item['project_value']??'-') ?></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'; ?>
