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

$pageTitle = 'Our Customers';
$activePage = 'customers';
$msg = '';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id']??null;
    $name = trim($_POST['name']??'');
    $website = trim($_POST['website']??'#');
    $sort = (int)($_POST['sort_order']??0);
    $active = isset($_POST['is_active']) ? 1 : 0;
    $logo = $_POST['existing_logo']??'';
    if (!empty($_FILES['logo']['name'])) {
        $up = uploadFile($_FILES['logo'], 'assets/images/customers');
        if ($up) $logo = $up;
    }
    if ($id) {
        $pdo->prepare("UPDATE customers SET name=?,logo=?,website=?,sort_order=?,is_active=? WHERE id=?")
            ->execute([$name,$logo,$website,$sort,$active,$id]);
        $msg = adminAlert('Customer berhasil diperbarui.');
    } else {
        $pdo->prepare("INSERT INTO customers (name,logo,website,sort_order,is_active) VALUES (?,?,?,?,?)")
            ->execute([$name,$logo,$website,$sort,$active]);
        $msg = adminAlert('Customer berhasil ditambahkan.');
    }
}

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

$items = $pdo->query("SELECT * FROM customers ORDER BY sort_order ASC")->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 Customer' : 'Tambah Customer' ?></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_logo" value="<?= $editItem['logo'] ?>"><?php endif; ?>
                    <div class="mb-3"><label class="form-label fw-semibold">Nama <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">Website</label><input type="text" name="website" class="form-control" value="<?= htmlspecialchars($editItem['website']??'#') ?>"></div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Logo</label>
                        <input type="file" name="logo" class="form-control" accept="image/*">
                        <?php if ($editItem && $editItem['logo']): ?><img src="../<?= $editItem['logo'] ?>" class="mt-1 rounded" style="height:50px;object-fit:contain;" 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="customers.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 Customer (<?= count($items) ?>)</div>
            <div class="card-body">
                <div class="row g-3">
                    <?php foreach ($items as $item): ?>
                    <div class="col-6 col-md-4 col-lg-3">
                        <div class="card border text-center p-2">
                            <img src="../<?= $item['logo'] ?>" style="height:50px;object-fit:contain;margin:auto;" onerror="this.src='https://via.placeholder.com/80x50?text=Logo'">
                            <p class="mb-1 mt-2 small fw-semibold"><?= htmlspecialchars($item['name']) ?></p>
                            <div class="d-flex gap-1 justify-content-center">
                                <a href="?edit=<?= $item['id'] ?>" class="btn btn-sm btn-outline-primary px-2"><i class="bi bi-pencil"></i></a>
                                <a href="?delete=<?= $item['id'] ?>" class="btn btn-sm btn-outline-danger px-2" onclick="return confirm('Hapus?')"><i class="bi bi-trash"></i></a>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>
<?php include 'partials/footer.php'; ?>
