<?php
session_start();
include '../layouts/dbconn.php';

header('Content-Type: application/json');

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

// Check role permissions
$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ENT_DOCTOR', 'ENT_CONSULTANT'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

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

$procedure_id = isset($input['procedure_id']) ? (int)$input['procedure_id'] : 0;
$new_status = isset($input['status']) ? $input['status'] : '';
$notes = isset($input['notes']) ? $input['notes'] : '';

if (!$procedure_id || !$new_status) {
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit();
}

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

// Get current procedure details
$procedure_sql = "SELECT status FROM patient_procedures WHERE procedure_id = ?";
$stmt = $conn->prepare($procedure_sql);
$stmt->bind_param('i', $procedure_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Procedure not found']);
    exit();
}

$procedure = $result->fetch_assoc();
$old_status = $procedure['status'];

// Begin transaction
$conn->begin_transaction();

try {
    // Update procedure status
    $update_sql = "UPDATE patient_procedures SET status = ?, updated_at = NOW() WHERE procedure_id = ?";
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param('si', $new_status, $procedure_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to update procedure status');
    }
    
    // If marking as completed, update completion date
    if ($new_status === 'COMPLETED') {
        $complete_sql = "UPDATE patient_procedures SET completed_at = NOW() WHERE procedure_id = ?";
        $stmt = $conn->prepare($complete_sql);
        $stmt->bind_param('i', $procedure_id);
        $stmt->execute();
    }
    
    // Update outcome if provided and status is COMPLETED
    if ($new_status === 'COMPLETED' && $notes) {
        $outcome_sql = "UPDATE patient_procedures SET outcome = ? WHERE procedure_id = ?";
        $stmt = $conn->prepare($outcome_sql);
        $stmt->bind_param('si', $notes, $procedure_id);
        $stmt->execute();
    }
    
    // Log status change in history (if table exists)
    $history_sql = "INSERT INTO procedure_status_history 
                    (procedure_id, old_status, new_status, changed_by, notes, changed_at) 
                    VALUES (?, ?, ?, ?, ?, NOW())";
    $stmt = $conn->prepare($history_sql);
    $stmt->bind_param('issis', $procedure_id, $old_status, $new_status, $_SESSION['user_id'], $notes);
    $stmt->execute();
    
    // Commit transaction
    $conn->commit();
    
    echo json_encode(['success' => true, 'message' => 'Procedure status updated successfully']);
    
} catch (Exception $e) {
    // Rollback on error
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

$conn->close();
?>