<?php
session_start();
include "config.php";

/* ======================
   PROTECT PAGE
======================*/
if(!isset($_SESSION['patient_mobile'])){
    header("Location: patient_login.php");
    exit;
}

$mobile = $_SESSION['patient_mobile'];
$message = "";


/* ======================
   FETCH / CREATE PATIENT
======================*/
$pq = mysqli_query($conn,"SELECT * FROM patients WHERE mobile='$mobile'");

if(mysqli_num_rows($pq)==0){
    // Auto-create patient if not exists
    mysqli_query($conn,"
    INSERT INTO patients (name,mobile,age,gender)
    VALUES ('','{$mobile}',0,'')
    ");
    $pq = mysqli_query($conn,"SELECT * FROM patients WHERE mobile='$mobile'");
}

$patient = mysqli_fetch_assoc($pq);

$name = $patient['name'] ?? '';
$age = $patient['age'] ?? '';

/* ======================
   DOCTOR TIMING CONFIG
======================*/
$doctor_start_time = "10:00"; // Clinic opens
$doctor_end_time = "21:00"; // Clinic closes
$slot_minutes = 10;

/* ======================
   SELECTED DATE
======================*/
$date = $_POST['date'] ?? date("Y-m-d");

/* ======================
   SAVE APPOINTMENT
======================*/
if(isset($_POST['save'])){

    $name = $_POST['name'];
    $age = $_POST['age'];
    $time = $_POST['time'];
    $reason = $_POST['reason'];

    // Prevent past time booking for today
    if($date == date("Y-m-d") && $time <= date("H:i")){
        $message = "Please select a future time slot";
    }else{

        mysqli_query($conn,"
        INSERT INTO appointments
        (patient_name,mobile,age,visit_date,visit_time,reason,status)
        VALUES
        ('$name','$mobile','$age','$date','$time','$reason','Pending')
        ");

        $message = "Appointment Booked Successfully";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Book Appointment</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="assets/style.css">
</head>

<body>

<div class="container">

<h2>Book Appointment</h2>

<?php if($message!=""){ ?>
<p class="msg"><?php echo $message; ?></p>
<?php } ?>

<form method="post">

<!-- Patient Name -->
<input type="text" name="name" placeholder="Patient Name" required>

<!-- Mobile -->
<input type="text" value="<?php echo $mobile; ?>" readonly>

<!-- Age -->
<input type="number" name="age" placeholder="Age" required>

<!-- Date -->
<input type="date" name="date"
value="<?php echo $date; ?>"
onchange="this.form.submit()" required>

<!-- Time Slots -->
<select name="time" required>
<option value="">Select Time Slot</option>

<?php
$start = strtotime($doctor_start_time);
$end = strtotime($doctor_end_time);

while($start < $end){

    $slot = date("H:i", $start);

    // Skip past slots for today
    if($date == date("Y-m-d") && $slot <= date("H:i")){
        $start = strtotime("+$slot_minutes minutes", $start);
        continue;
    }

    // Check if slot already booked
    $check = mysqli_query($conn,"
    SELECT id FROM appointments
    WHERE visit_date='$date'
    AND visit_time='$slot'
    ");

    if(mysqli_num_rows($check)==0){
        echo "<option value='$slot'>$slot</option>";
    }

    $start = strtotime("+$slot_minutes minutes", $start);
}
?>

</select>

<!-- Reason -->
<textarea name="reason" placeholder="Problem" required></textarea>

<button class="btn btn-success" name="save">Book Appointment</button>

</form>

<br>

<a href="patient_dashboard.php" class="btn btn-primary">
Back To Dashboard
</a>

</div>

</body>
</html>