<?php
session_start();
require_once 'config.php';
require_once 'sms.php'; // We'll create this next

if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    header("Location: book.php");
    exit();
}

// --- Validation & Sanitization ---
$patient_id = $_SESSION['patient_id'] ?? 0;
$chamber_id = intval($_POST['chamber_id']);
$date = $_POST['appointment_date'];
$time_slot_start = $_POST['time_slot'];
$category = $_POST['patient_category'];
$fee = floatval($_POST['fee']);

if (!$patient_id || !$chamber_id || !$date || !$time_slot_start) {
    $_SESSION['error'] = "All fields are required.";
    header("Location: book.php");
    exit();
}

// --- Check if slot is still available (prevent double booking) ---
$slot_check = $conn->query("SELECT id, end_time FROM time_slots 
                            WHERE chamber_id = $chamber_id AND slot_date = '$date' AND start_time = '$time_slot_start'");
if ($slot_check->num_rows == 0) {
    // Slot not pre-generated? Generate it now (simple fallback)
    $schedule = $conn->query("SELECT slot_duration FROM chamber_schedules 
                              JOIN chambers ON chamber_schedules.chamber_id = chambers.id
                              WHERE chamber_schedules.chamber_id = $chamber_id 
                              AND day_of_week = " . date('w', strtotime($date)));
    $dur = $schedule->fetch_assoc()['slot_duration'] ?? 30;
    $end_time = date('H:i:s', strtotime($time_slot_start) + $dur * 60);
    $conn->query("INSERT INTO time_slots (chamber_id, slot_date, start_time, end_time) 
                  VALUES ($chamber_id, '$date', '$time_slot_start', '$end_time')");
    $slot_id = $conn->insert_id;
} else {
    $slot = $slot_check->fetch_assoc();
    $slot_id = $slot['id'];
    // Check if already booked
    $check_appointment = $conn->query("SELECT id FROM appointments WHERE time_slot_id = $slot_id");
    if ($check_appointment->num_rows > 0) {
        $_SESSION['error'] = "This time slot was just taken. Please choose another.";
        header("Location: book.php");
        exit();
    }
}

// --- Insert Appointment ---
$stmt = $conn->prepare("INSERT INTO appointments (patient_id, chamber_id, time_slot_id, appointment_date, patient_category, fee, status, booking_time) 
                        VALUES (?, ?, ?, ?, ?, ?, 'confirmed', NOW())");
$stmt->bind_param("iiissd", $patient_id, $chamber_id, $slot_id, $date, $category, $fee);
if (!$stmt->execute()) {
    $_SESSION['error'] = "Database error: " . $stmt->error;
    header("Location: book.php");
    exit();
}

// Mark slot as booked
$conn->query("UPDATE time_slots SET is_booked = 1 WHERE id = $slot_id");

// --- Get details for SMS ---
$chamber = $conn->query("SELECT name, address, phone FROM chambers WHERE id = $chamber_id")->fetch_assoc();
$patient = $conn->query("SELECT name, phone FROM patients WHERE id = $patient_id")->fetch_assoc();

// --- Send SMS to Patient ---
$patient_msg = "Dear {$patient['name']}, your appointment is confirmed on $date at $time_slot_start at {$chamber['name']}, {$chamber['address']}. Fee: $fee Tk. Thank you.";
sendSMS($patient['phone'], $patient_msg);

// --- Send SMS to Admin ---
$admin_phone = "017XXXXXXXX"; // Replace with your admin number
$admin_msg = "New booking: {$patient['name']} on $date at $time_slot_start at {$chamber['name']}. Category: $category, Fee: $fee Tk.";
sendSMS($admin_phone, $admin_msg);

$_SESSION['success'] = "Appointment booked successfully! A confirmation SMS has been sent.";
header("Location: confirmation.php"); // Redirect to a thank you/confirmation page
?>