<?php
session_start();
header('Content-Type: application/json');

include 'layouts/dbconn.php';

// Authentication check
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$response = ['success' => false, 'message' => ''];

try {
    // Get parameters
    $appointment_id = isset($_POST['appointment_id']) ? (int)$_POST['appointment_id'] : 0;
    $notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';
    
    // Validate
    if (!$appointment_id) {
        throw new Exception('Appointment ID is required');
    }
    
    // Check permissions
    $allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ENT_DOCTOR', 'ENT_CONSULTANT', 'NURSE'];
    if (!in_array($_SESSION['role_code'], $allowed_roles)) {
        throw new Exception('You do not have permission to update notes');
    }
    
    // Check if appointment exists
    $check_sql = "SELECT appointment_id FROM appointments WHERE appointment_id = ?";
    $stmt = $conn->prepare($check_sql);
    $stmt->bind_param("i", $appointment_id);
    $stmt->execute();
    $exists = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if (!$exists) {
        throw new Exception('Appointment not found');
    }
    
    // Update notes
    $update_sql = "UPDATE appointments 
                   SET notes = ?,
                       updated_at = NOW()
                   WHERE appointment_id = ?";
    
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param("si", $notes, $appointment_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to update notes');
    }
    $stmt->close();
    
    $response = [
        'success' => true,
        'message' => 'Notes updated successfully'
    ];
    
} catch (Exception $e) {
    error_log("Update appointment notes error: " . $e->getMessage());
    $response = [
        'success' => false,
        'message' => $e->getMessage()
    ];
}

if (isset($conn)) {
    $conn->close();
}

echo json_encode($response);
exit();
?>