<?php
$pageTitle = 'Tambah Paket';
$activeMenu = 'packages';
require_once __DIR__ . '/../../includes/header.php';

$db = get_db_connection();
$errors = [];
$formData = [
    'package_name' => '',
    'price' => '',
    'description' => '',
    'status' => 'active',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    if (!validate_csrf_token($token)) {
        $errors[] = 'Token tidak sah. Silakan coba lagi.';
    }

    $formData['package_name'] = sanitize_input($_POST['package_name'] ?? '');
    $formData['price'] = sanitize_input($_POST['price'] ?? '0');
    $formData['description'] = sanitize_input($_POST['description'] ?? '');
    $formData['status'] = sanitize_input($_POST['status'] ?? 'active');

    if ($formData['package_name'] === '') {
        $errors[] = 'Nama paket wajib diisi.';
    }

    if (!is_numeric($formData['price']) || (float) $formData['price'] <= 0) {
        $errors[] = 'Harga paket harus lebih dari 0.';
    }

    if (!in_array($formData['status'], ['active', 'inactive'], true)) {
        $errors[] = 'Status tidak valid.';
    }

    if (empty($errors)) {
        $sql = 'INSERT INTO packages (package_name, price, description, status, created_at) VALUES (?, ?, ?, ?, NOW())';
        $stmt = $db->prepare($sql);
        if ($stmt) {
            $price = (float) $formData['price'];
            $stmt->bind_param('sdss', $formData['package_name'], $price, $formData['description'], $formData['status']);
            if ($stmt->execute()) {
                redirect_with_message('index.php', 'Paket berhasil ditambahkan.');
            } else {
                $errors[] = 'Gagal menyimpan data paket.';
            }
        } else {
            $errors[] = 'Terjadi kesalahan pada database.';
        }
    }
}

$token = csrf_token();
?>
<div class="card card-metric p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <small class="text-muted">Isi detail paket dengan informasi valid.</small>
        </div>
        <a href="index.php" class="btn btn-outline-secondary"><i class="fa-solid fa-arrow-left me-2"></i>Kembali</a>
    </div>
    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <ul class="mb-0">
                <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>
    <form method="POST" class="row gy-3 needs-validation" novalidate>
        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($token); ?>">
        <div class="col-md-8">
            <label class="form-label">Nama Paket</label>
            <input type="text" name="package_name" class="form-control" value="<?php echo htmlspecialchars($formData['package_name']); ?>" required>
            <div class="invalid-feedback">Nama paket wajib diisi.</div>
        </div>
        <div class="col-md-4">
            <label class="form-label">Harga</label>
            <input type="number" step="0.01" min="0" name="price" class="form-control" value="<?php echo htmlspecialchars($formData['price']); ?>" required>
            <div class="invalid-feedback">Masukkan harga paket.</div>
        </div>
        <div class="col-12">
            <label class="form-label">Deskripsi</label>
            <textarea name="description" rows="4" class="form-control" required><?php echo htmlspecialchars($formData['description']); ?></textarea>
            <div class="invalid-feedback">Deskripsi paket wajib diisi.</div>
        </div>
        <div class="col-md-4">
            <label class="form-label">Status</label>
            <select name="status" class="form-select" required>
                <option value="active" <?php echo $formData['status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                <option value="inactive" <?php echo $formData['status'] === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
            </select>
            <div class="invalid-feedback">Pilih status paket.</div>
        </div>
        <div class="col-12">
            <button type="submit" class="btn btn-primary">Simpan</button>
        </div>
    </form>
</div>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>