<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/booking.php';

/* ================= GUEST MANAGEMENT ================= */
if(isset($_POST['add_guest'])){
    $name  = $_POST['name'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $idno  = $_POST['id_number'];

    $stmt = $conn->prepare("INSERT INTO guests (name, phone, email, id_number) VALUES (?,?,?,?)");
    $stmt->bind_param("ssss",$name,$phone,$email,$idno);
    $stmt->execute();

    // Redirect to same page to auto-populate guest dropdown
    header("Location: booking.php?new_guest_id=".$stmt->insert_id);
    exit;
}

/* ================= CREATE RESERVATION ================= */
if(isset($_POST['reserve'])){
    $guest_id = intval($_POST['guest_id']);
    $room_id  = intval($_POST['room_id']);
    $date_in  = $_POST['date_in'];
    $date_out = $_POST['date_out'];
    $payment_amount = floatval($_POST['payment_amount']);
    $payment_type   = $_POST['payment_type'] ?? 'Airtel Money';

    if(strtotime($date_out) <= strtotime($date_in)){
        echo "<div class='alert alert-danger'>Check-out must be after check-in!</div>";
    } else {
        $check = $conn->query("
            SELECT id FROM reservations 
            WHERE room_id=$room_id 
            AND status='Reserved'
            AND NOT (date_out <= '$date_in' OR date_in >= '$date_out')
        ");
        if($check && $check->num_rows > 0){
            echo "<div class='alert alert-danger'>Room is already reserved for the selected dates!</div>";
        } else {
            $stmt = $conn->prepare("
                INSERT INTO reservations (guest_id, room_id, date_in, date_out, status) 
                VALUES (?, ?, ?, ?, 'Reserved')
            ");
            $stmt->bind_param("iiss",$guest_id,$room_id,$date_in,$date_out);
            $stmt->execute();
            $reservation_id = $stmt->insert_id;

            $conn->query("UPDATE rooms SET status='Reserved' WHERE id=$room_id");

            if($payment_amount > 0){
                $stmt_pay = $conn->prepare("
                    INSERT INTO payments 
                    (reservation_id, guest_id, amount, type, payment_date, status) 
                    VALUES (?, ?, ?, ?, NOW(), 'Paid')
                ");
                $stmt_pay->bind_param("iids", $reservation_id, $guest_id, $payment_amount, $payment_type);
                $stmt_pay->execute();
            }

            echo "<script>alert('Reservation created successfully!');window.location='booking.php';</script>";
            exit;
        }
    }
}

/* ================= FETCH DATA ================= */
$guests = $conn->query("SELECT * FROM guests ORDER BY name");
$rooms  = $conn->query("SELECT * FROM rooms ORDER BY room_number");

// Get the ID of newly added guest for auto-select
$new_guest_id = intval($_GET['new_guest_id'] ?? 0);

?>

<div class="container mt-4">
<h4> Booking Form</h4>
<hr>

<!-- ======= ADD GUEST FORM ======= -->
<div class="card mb-4">
  <div class="card-header bg-primary text-white">Add Guest</div>
  <div class="card-body">
    <form method="POST" class="row g-3">
        <div class="col-md-3">
            <input type="text" name="name" class="form-control" placeholder="Guest Name" required>
        </div>
        <div class="col-md-2">
            <input type="text" name="phone" class="form-control" placeholder="Phone">
        </div>
        <div class="col-md-3">
            <input type="email" name="email" class="form-control" placeholder="Email">
        </div>
        <div class="col-md-2">
            <input type="text" name="id_number" class="form-control" placeholder="ID/Passport">
        </div>
        <div class="col-md-2">
            <button name="add_guest" class="btn btn-success w-100">Register as Guest</button>
        </div>
    </form>
  </div>
</div>

<!-- ======= CREATE RESERVATION FORM ======= -->
<div class="card mb-4">
  <div class="card-header bg-warning text-dark">Create Reservation</div>
  <div class="card-body">
    <form method="POST" class="row g-3">
        <!-- Guest -->
        <div class="col-md-3">
            
               <input type="text" name="name" class="form-control" placeholder="Guest Name" required>
              
        </div>

        <!-- Room -->
        <div class="col-md-3">
            <select name="room_id" class="form-control" required>
                <option value="">Select Room</option>
                <?php while($r=$rooms->fetch_assoc()): ?>
                    <option value="<?= $r['id'] ?>">
                        Room <?= $r['room_number'] ?> (<?= $r['room_type'] ?>) - MK <?= number_format($r['price'],2) ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </div>

        <!-- Check-in / Check-out -->
        <div class="col-md-2">
            <input type="date" name="date_in" class="form-control" min="<?= date('Y-m-d') ?>" required>
        </div>
        <div class="col-md-2">
            <input type="date" name="date_out" class="form-control" min="<?= date('Y-m-d') ?>" required>
        </div>

        <!-- Payment -->
        <div class="col-md-2">
            <input type="number" name="payment_amount" class="form-control" placeholder="Payment MK" step="0.01" min="0" value="0">
            <small class="text-muted">Optional</small>
        </div>

        <!-- Payment Method -->
        <div class="col-md-2">
            <select name="payment_type" class="form-control" required>
                <option value="Airtel Money">Airtel Money</option>
                <option value="TNM Mpamba">TNM Mpamba</option>
                <option value="Cash">Cash</option>
                <option value="Bank Transfer">Bank Transfer</option>
            </select>
        </div>

        <div class="col-md-2">
            <button name="reserve" class="btn btn-warning w-100"><i class="fa fa-bed"></i>Make Reservation</button>
        </div>
    </form>
  </div>
</div>


