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

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

// Check authentication
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

// Check if user is ENT doctor
if ($_SESSION['role_code'] !== 'ENT_DOCTOR') {
    echo json_encode(['error' => 'Insufficient permissions']);
    exit();
}

$doctor_id = $_SESSION['user_id'];
$today = date('Y-m-d');

$query = "SELECT 
    mp.*,
    ept.procedure_name,
    ept.category,
    ept.estimated_duration,
    u.full_name as patient_name,
    p.phone_number,
    p.gender,
    perf_user.full_name as performed_by_name
FROM medical_procedures mp
INNER JOIN ent_procedure_types ept ON mp.procedure_type_id = ept.procedure_type_id
INNER JOIN patients pat ON mp.patient_id = pat.patient_id
INNER JOIN users u ON pat.user_id = u.user_id
INNER JOIN patients p ON mp.patient_id = p.patient_id
LEFT JOIN users perf_user ON mp.performed_by = perf_user.user_id
WHERE mp.scheduled_by = ? 
AND DATE(mp.scheduled_date) = ?
ORDER BY mp.scheduled_date ASC";

$stmt = $conn->prepare($query);
$stmt->bind_param("is", $doctor_id, $today);
$stmt->execute();
$result = $stmt->get_result();

$data = [];
while ($row = $result->fetch_assoc()) {
    // Format status badge
    $status_badges = [
        'SCHEDULED' => 'secondary',
        'IN_PROGRESS' => 'warning',
        'COMPLETED' => 'success',
        'CANCELLED' => 'danger',
        'ON_HOLD' => 'info'
    ];
    $status_class = $status_badges[$row['status']] ?? 'secondary';
    $status_badge = '<span class="badge bg-' . $status_class . '">' . $row['status'] . '</span>';
    
    // Actions
    $actions = '<div class="btn-group btn-group-sm">';
    if ($row['status'] == 'SCHEDULED') {
        $actions .= '<button class="btn btn-outline-success start-procedure" data-id="' . $row['procedure_id'] . '" title="Start Procedure">
            <i class="ri-play-line"></i>
        </button>';
    }
    if ($row['status'] == 'IN_PROGRESS') {
        $actions .= '<button class="btn btn-outline-primary complete-procedure" data-id="' . $row['procedure_id'] . '" title="Complete">
            <i class="ri-check-line"></i>
        </button>';
    }
    $actions .= '<a href="view_procedure.php?id=' . $row['procedure_id'] . '" class="btn btn-outline-info" title="View Details">
        <i class="ri-eye-line"></i>
    </a>
    </div>';
    
    $data[] = [
        'time' => date('h:i A', strtotime($row['scheduled_date'])),
        'procedure_name' => htmlspecialchars($row['procedure_name']) . '<br><small class="text-muted">' . $row['category'] . '</small>',
        'patient_name' => htmlspecialchars($row['patient_name']) . '<br><small class="text-muted">' . $row['phone_number'] . '</small>',
        'duration' => $row['estimated_duration'] . ' mins',
        'status' => $status_badge,
        'actions' => $actions
    ];
}

echo json_encode(['data' => $data]);

$conn->close();
?>