<?php
// api/patient/book.php
require_once __DIR__ . '/../middleware.php';
require_once __DIR__ . '/../../layouts/dbconn.php';

global $API_USER;
if (!isset($API_USER)) {
    jsonError('Unauthorized', 401);
}

// Get Patient ID
$user_id = $API_USER['sub'];
$stmt = $conn->prepare("SELECT patient_id FROM patients WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows === 0) {
    jsonError('Patient profile not found', 404);
}

$patient = $res->fetch_assoc();
$patient_id = $patient['patient_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    // Validate Input
    if (empty($input['doctor_id']) || empty($input['date']) || empty($input['time']) || empty($input['reason'])) {
        jsonError('Missing required fields: doctor_id, date, time, reason', 400);
    }

    $doctor_id = $input['doctor_id'];
    $date = $input['date'];
    $time = $input['time'];
    $reason = $input['reason']; // maps to chief_complaint
    $special_req = $input['special_requirements'] ?? '';
    $appt_type = 'CONSULTATION'; // Default

    // Check conflicts (Simplified version of book_appointment.php)
    $conflict = $conn->prepare("SELECT appointment_id FROM appointments 
                               WHERE doctor_id = ? AND appointment_date = ? AND appointment_time = ? 
                               AND status NOT IN ('CANCELLED', 'NO_SHOW')");
    $conflict->bind_param("iss", $doctor_id, $date, $time);
    $conflict->execute();
    if ($conflict->get_result()->num_rows > 0) {
        jsonError('Doctor is not available at this time', 409);
    }

    // Get duration
    $doc_q = $conn->prepare("SELECT appointment_duration FROM doctors WHERE doctor_id = ?");
    $doc_q->bind_param("i", $doctor_id);
    $doc_q->execute();
    $doc_res = $doc_q->get_result();
    $duration = 30;
    if ($doc_res->num_rows > 0) {
        $d = $doc_res->fetch_assoc();
        $duration = $d['appointment_duration'] ?? 30;
    }

    // Generate Appointment Number
    $appt_number = 'APT' . date('Ymd') . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);

    // Insert
    $sql = "INSERT INTO appointments (appointment_number, patient_id, doctor_id, 
            appointment_date, appointment_time, appointment_type, booking_source, 
            chief_complaint, special_requirements, estimated_duration, status, created_at) 
            VALUES (?, ?, ?, ?, ?, ?, 'MOBILE_APP', ?, ?, ?, 'SCHEDULED', NOW())";

    $insert = $conn->prepare($sql);
    $insert->bind_param(
        "siisssssi",
        $appt_number,
        $patient_id,
        $doctor_id,
        $date,
        $time,
        $appt_type,
        $reason,
        $special_req,
        $duration
    );

    if ($insert->execute()) {
        jsonResponse([
            'message' => 'Appointment booked successfully',
            'appointment_number' => $appt_number,
            'appointment_id' => $conn->insert_id
        ], 201);
    } else {
        jsonError('Booking failed: ' . $conn->error, 500);
    }

} else {
    jsonError('Method not allowed', 405);
}
?>