<?php
session_start();
include '../db.php';

// Cek apakah user sudah login
if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'user') {
    header('Location: login.php');
    exit;
}

// Atur zona waktu ke Asia/Jakarta
date_default_timezone_set('Asia/Jakarta');

// Tangkap data dari URL jika ada
$selected_date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d'); // Default tanggal hari ini
$selected_place = isset($_GET['tempat']) ? $_GET['tempat'] : ''; // Default tempat kosong

// Jika form disubmit
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $kode_booking = uniqid('RES-');
    $user_id = $_SESSION['user_id'];
    $nama = $_POST['nama'];
    $no_telepon = $_POST['no_telepon'];
    $surat = $_POST['surat'];
    $tempat = $_POST['tempat'];
    $hari = $_POST['hari'];
    $jam_mulai = $_POST['jam_mulai'];
    $jam_selesai = $_POST['jam_selesai'];
    $keterangan = $_POST['keterangan'];
    $status = 'pending';

    // Proses unggah file
    $file_name = null;
    if (isset($_FILES['file_upload']) && $_FILES['file_upload']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = '../uploads/';
        $file_name = uniqid() . '_' . basename($_FILES['file_upload']['name']);
        $target_file = $upload_dir . $file_name;

        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }

        if (!move_uploaded_file($_FILES['file_upload']['tmp_name'], $target_file)) {
            echo "<script>
                    alert('Gagal mengunggah file.');
                  </script>";
            $file_name = null;
        }
    }

    // Simpan data ke database
    $query = "INSERT INTO reservations (kode_booking, user_id, nama, no_telepon, surat, tempat, hari, jam_mulai, jam_selesai, keterangan, file_upload, status) 
              VALUES ('$kode_booking', '$user_id', '$nama', '$no_telepon', '$surat', '$tempat', '$hari', '$jam_mulai', '$jam_selesai', '$keterangan', '$file_name', '$status')";

    if ($conn->query($query)) {
        echo "<script>
                window.onload = function() {
                    Swal.fire({
                        title: 'Berhasil!',
                        text: 'Reservasi berhasil diajukan!',
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then(function() {
                        window.location.href = 'dashboard.php';
                    });
                }
              </script>";
    } else {
        echo "<script>
                window.onload = function() {
                    Swal.fire({
                        title: 'Gagal!',
                        text: 'Terjadi kesalahan saat mengajukan reservasi. Silakan coba lagi.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                }
              </script>";
    }
}

// Mendapatkan daftar tempat untuk dropdown
$sqlPlaces = "SELECT id, name FROM places";
$resultPlaces = $conn->query($sqlPlaces);
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reservasi</title>
    <!-- Bootstrap & Font Awesome -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <!-- Flatpickr (Time‑Picker) -->
    <!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css"> -->
    <!-- Google Font -->
    <link rel="preconnect" href="https://fonts.gstatic.com" />
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet" />
    <!-- Favicon -->
    <link rel="icon" href="../assets/img/logotng.png" type="image/x-icon">

    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <style>
        :root {
            --primary: #4c7cf3;
        }

        body {
            background: linear-gradient(135deg, #e9efff 0%, #f7f9ff 100%);
            font-family: 'Poppins', sans-serif;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 2rem;
        }

        .card-reservasi {
            border: none;
            border-radius: 1rem;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.08);
        }

        .card-reservasi .card-header {
            background: none;
            border-bottom: none;
            padding-bottom: 0;
        }

        .card-reservasi .card-title {
            font-weight: 600;
        }

        .form-label {
            font-weight: 500;
        }

        .input-group-text {
            background: none;
            border: none;
        }

        .form-control:focus,
        .form-select:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 0.15rem rgba(76, 124, 243, .25);
        }

        .btn-primary {
            background: var(--primary);
            border: none;
        }

        .btn-primary:hover {
            background: #3b6bef;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="card card-reservasi">
            <div class="card-header text-center">
                <h1 class="card-title mb-0">Form Reservasi</h1>
                <p class="text-muted">Lengkapi data di bawah untuk mengajukan reservasi.</p>
                <a href="calendar_reserv.php?tempat=<?php echo urlencode($selected_place); ?>" class="btn btn-outline-dark btn-sm mt-2">
                    <i class="far fa-calendar-alt me-1"></i>Pilih Tanggal & Tempat
                </a>
            </div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data" class="row g-3">
                    <!-- Nama -->
                    <div class="col-md-6">
                        <label for="nama" class="form-label">Nama</label>
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-user"></i></span>
                            <input type="text" class="form-control" id="nama" name="nama" placeholder="Masukkan nama" required>
                        </div>
                    </div>
                    <!-- No Telepon -->
                    <div class="col-md-6">
                        <label for="no_telepon" class="form-label">No Telepon</label>
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-phone-alt"></i></span>
                            <input type="text" class="form-control" id="no_telepon" name="no_telepon" placeholder="08xxxx" required>
                        </div>
                    </div>
                    <!-- Email -->
                    <div class="col-12">
                        <label for="surat" class="form-label">Email</label>
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-envelope"></i></span>
                            <input type="email" class="form-control" id="surat" name="surat" placeholder="nama@email.com" required>
                        </div>
                    </div>
                    <!-- Tempat -->
                    <div class="col-12">
                        <label for="tempat" class="form-label">Tempat</label>
                        <select name="tempat" class="form-select" id="tempat" required>
                            <option value="">Pilih Tempat</option>
                            <?php while ($places = $resultPlaces->fetch_assoc()): ?>
                                <option value="<?php echo htmlspecialchars($places['name']); ?>" <?php echo ($places['name'] === $selected_place) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($places['name']); ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <!-- Tanggal Reservasi -->
                    <div class="col-md-6">
                        <label for="hari" class="form-label">Tanggal Reservasi</label>
                        <input type="date" class="form-control" id="hari" name="hari" value="<?php echo $selected_date; ?>" required>
                    </div>
                   <!-- Jam Mulai -->
                   <div class="col-md-3">
                        <label for="jam_mulai" class="form-label">Jam Mulai</label>
                        <select class="form-select" id="jam_mulai" name="jam_mulai" required>
                            <option value="">Pilih Jam</option>
                            <?php
                            for ($h = 6; $h <= 22; $h++) {
                                foreach (["00", "30"] as $m) {
                                    $time = sprintf("%02d:%s", $h, $m);
                                    echo "<option value=\"$time\">$time WIB</option>";
                                }
                            }
                            ?>
                        </select>
                    </div>
                    <!-- Jam Selesai -->
                    <div class="col-md-3">
                        <label for="jam_selesai" class="form-label">Jam Selesai</label>
                        <select class="form-select" id="jam_selesai" name="jam_selesai" required>
                            <option value="">Pilih Jam</option>
                            <?php
                            for ($h = 6; $h <= 22; $h++) {
                                foreach (["00", "30"] as $m) {
                                    $time = sprintf("%02d:%s", $h, $m);
                                    echo "<option value=\"$time\">$time WIB</option>";
                                }
                            }
                            ?>
                        </select>
                    </div>
                    <!-- Keterangan -->
                    <div class="col-12">
                        <label for="keterangan" class="form-label">Keterangan</label>
                        <textarea class="form-control" id="keterangan" name="keterangan" rows="3" placeholder="Deskripsikan keperluan reservasi..." required></textarea>
                    </div>
                    <!-- Upload File -->
                    <div class="col-12">
                        <label for="file_upload" class="form-label">Upload File</label>
                        <input type="file" class="form-control" id="file_upload" name="file_upload" required>
                    </div>
                    <!-- Buttons -->
                    <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-4">
                        <button type="submit" class="btn btn-primary me-md-2"><i class="fas fa-paper-plane me-1"></i>Ajukan</button>
                        <a href="dashboard.php" class="btn btn-outline-danger"><i class="fas fa-arrow-left me-1"></i>Back</a>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Bootstrap Bundle -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>