<?php
// إيقاف أي مخرجات أو تحذيرات قد تظهر وتخرب الـ JSON
ob_start();

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");

include_once 'db_connect.php'; 

$data = json_decode(file_get_contents("php://input"), true);

if (isset($data['doctor_id']) && isset($data['patient_id'])) {
    
    $doctor_id = $data['doctor_id'];
    $patient_id = $data['patient_id'];
    $date = $data['appointment_date'];
    $time = $data['appointment_time'];

    try {
        $conn->exec("set names utf8mb4");

        // 1. حساب تسلسل المريض
        $sql_count = "SELECT COUNT(*) as total FROM bookings WHERE doctor_id = :doctor_id AND appointment_date = :app_date";
        $stmt_count = $conn->prepare($sql_count);
        $stmt_count->execute([':doctor_id' => $doctor_id, ':app_date' => $date]);
        $row_count = $stmt_count->fetch(PDO::FETCH_ASSOC);
        $next_day_id = (int)$row_count['total'] + 1;

        // 2. التحقق من التكرار
        $sql_check = "SELECT id FROM bookings WHERE doctor_id = :doctor_id AND patient_id = :patient_id AND appointment_date = :app_date";
        $stmt_check = $conn->prepare($sql_check);
        $stmt_check->execute([':doctor_id' => $doctor_id, ':patient_id' => $patient_id, ':app_date' => $date]);

        if ($stmt_check->rowCount() > 0) {
            ob_clean(); // مسح أي مخرجات زائدة
            echo json_encode(["status" => "error", "message" => "لديك حجز مسبق في هذا اليوم"]);
        } else {
            // 3. الحفظ
            $sql_insert = "INSERT INTO bookings (doctor_id, patient_id, appointment_date, appointment_time, day_id) 
                           VALUES (:doctor_id, :patient_id, :app_date, :app_time, :day_id)";
            
            $stmt_insert = $conn->prepare($sql_insert);
            $success = $stmt_insert->execute([
                ':doctor_id' => $doctor_id,
                ':patient_id' => $patient_id,
                ':app_date' => $date,
                ':app_time' => $time,
                ':day_id' => $next_day_id
            ]);

            ob_clean(); // مسح أي مخرجات زائدة قبل إرسال الرد النهائي
            if ($success) {
                echo json_encode(["status" => "success", "day_id" => $next_day_id]);
            } else {
                echo json_encode(["status" => "error", "message" => "فشل تنفيذ الحجز"]);
            }
        }

    } catch (PDOException $e) {
        ob_clean();
        echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    }

} else {
    ob_clean();
    echo json_encode(["status" => "error", "message" => "Incomplete data"]);
}
?>