<?php
// api/doctor/appointments.php
require_once __DIR__ . '/../middleware.php';
require_once __DIR__ . '/../../layouts/dbconn.php';

// Ensure user is authorized
global $API_USER;
if (!isset($API_USER)) {
    jsonError('Unauthorized', 401);
}

// TODO: stricter role check?
// if ($API_USER['role_code'] !== 'ENT_DOCTOR' && ...) { ... }

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // List appointments for this doctor
    $doctor_user_id = $API_USER['sub'];

    // Check if we need to filter by date? Defaults to all future or specific logic
    // Using logic similar to manage_appointments.php but tailored for API

    $sql = "SELECT a.appointment_id, a.appointment_date, a.status, a.reason,
                   p.first_name, p.last_name, p.phone_number, p.patient_number
            FROM appointments a
            JOIN patients p ON a.patient_id = p.patient_id
            WHERE a.doctor_id = ? 
            ORDER BY a.appointment_date ASC";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $doctor_user_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $appointments = [];
    while ($row = $result->fetch_assoc()) {
        $appointments[] = $row;
    }

    jsonResponse($appointments);

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

    if (!isset($input['appointment_id']) || !isset($input['status'])) {
        jsonError('Missing parameters', 400);
    }

    $appt_id = $input['appointment_id'];
    $status = $input['status'];
    $doctor_user_id = $API_USER['sub'];

    // Verify ownership/permission
    $check = $conn->prepare("SELECT appointment_id FROM appointments WHERE appointment_id = ? AND doctor_id = ?");
    $check->bind_param("ii", $appt_id, $doctor_user_id);
    $check->execute();
    if ($check->get_result()->num_rows === 0) {
        jsonError('Appointment not found or access denied', 404);
    }

    $update = $conn->prepare("UPDATE appointments SET status = ? WHERE appointment_id = ?");
    $update->bind_param("si", $status, $appt_id);

    if ($update->execute()) {
        jsonResponse(['message' => 'Appointment updated successfully']);
    } else {
        jsonError('Update failed', 500);
    }

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