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

include '../layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['appointment_id']) || !isset($input['status'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit();
}

$appointment_id = (int)$input['appointment_id'];
$status = $input['status'];
$user_id = $_SESSION['user_id'];

// Validate status
$valid_statuses = ['SCHEDULED', 'CONFIRMED', 'IN_PROGRESS', 'COMPLETED', 'CANCELLED', 'NO_SHOW'];
if (!in_array($status, $valid_statuses)) {
    echo json_encode(['success' => false, 'message' => 'Invalid status']);
    exit();
}

$conn->begin_transaction();

try {
    // Update appointment status
    $update_sql = "UPDATE appointments SET status = ?, updated_at = NOW() WHERE appointment_id = ?";
    $update_stmt = $conn->prepare($update_sql);
    $update_stmt->bind_param('si', $status, $appointment_id);
    $update_stmt->execute();
    
    if ($update_stmt->affected_rows === 0) {
        throw new Exception('Appointment not found or status unchanged');
    }
    
    // Log activity
    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, ip_address, logged_at)
               VALUES (?, 'UPDATE', 'TELEMEDICINE', ?, 'APPOINTMENT_STATUS', ?, NOW())";
    $log_stmt = $conn->prepare($log_sql);
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $log_stmt->bind_param('iis', $user_id, $appointment_id, $ip_address);
    $log_stmt->execute();
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Appointment status updated successfully',
        'appointment_id' => $appointment_id,
        'status' => $status
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        'success' => false,
        'message' => 'Failed to update appointment status: ' . $e->getMessage()
    ]);
}

$conn->close();
?>