<?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'];

// Get filters
$date_range = isset($_POST['date_range']) ? $_POST['date_range'] : '';
$patient_filter = isset($_POST['patient']) ? intval($_POST['patient']) : 0;
$type_filter = isset($_POST['type']) ? $_POST['type'] : '';

// Build query
$where = ["c.doctor_id = ?"];
$params = [$doctor_id];
$types = "i";

// Date range filter
if (!empty($date_range)) {
    $dates = explode(' to ', $date_range);
    if (count($dates) == 2) {
        $where[] = "DATE(c.consultation_date) BETWEEN ? AND ?";
        $params[] = $dates[0];
        $params[] = $dates[1];
        $types .= "ss";
    }
}

// Patient filter
if ($patient_filter > 0) {
    $where[] = "c.patient_id = ?";
    $params[] = $patient_filter;
    $types .= "i";
}

// Type filter
if (!empty($type_filter)) {
    $where[] = "c.consultation_type = ?";
    $params[] = $type_filter;
    $types .= "s";
}

$where_clause = implode(' AND ', $where);

$query = "SELECT 
    c.*,
    u.full_name as patient_name,
    p.phone_number,
    p.date_of_birth,
    p.gender,
    (SELECT COUNT(*) FROM prescriptions WHERE consultation_id = c.consultation_id) as prescription_count,
    (SELECT COUNT(*) FROM lab_orders WHERE consultation_id = c.consultation_id) as lab_order_count,
    (SELECT COUNT(*) FROM medical_procedures WHERE consultation_id = c.consultation_id) as procedure_count
FROM consultations c
INNER JOIN patients p ON c.patient_id = p.patient_id
INNER JOIN users u ON p.user_id = u.user_id
WHERE $where_clause
ORDER BY c.consultation_date DESC";

$stmt = $conn->prepare($query);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();

$data = [];
while ($row = $result->fetch_assoc()) {
    // Calculate age
    $dob = new DateTime($row['date_of_birth']);
    $now = new DateTime();
    $age = $now->diff($dob)->y;
    
    // Format consultation type badge
    $type_badge = ($row['consultation_type'] == 'NEW') ? 
        '<span class="badge bg-primary">NEW</span>' : 
        '<span class="badge bg-info">FOLLOW-UP</span>';
    
    // Format status badge
    $status_badges = [
        'SCHEDULED' => 'secondary',
        'IN_PROGRESS' => 'warning',
        'COMPLETED' => 'success',
        'CANCELLED' => 'danger'
    ];
    $status_class = $status_badges[$row['status']] ?? 'secondary';
    $status_badge = '<span class="badge bg-' . $status_class . '">' . $row['status'] . '</span>';
    
    // Follow-up info
    $follow_up = $row['follow_up_date'] ? 
        date('M d, Y', strtotime($row['follow_up_date'])) : 
        '<span class="text-muted">None</span>';
    
    // Actions
    $actions = '<div class="btn-group btn-group-sm">
        <button class="btn btn-outline-primary view-consultation" data-id="' . $row['consultation_id'] . '" title="View Details">
            <i class="ri-eye-line"></i>
        </button>
        <a href="view_consultation.php?id=' . $row['consultation_id'] . '" class="btn btn-outline-info" title="Full View">
            <i class="ri-file-text-line"></i>
        </a>
    </div>';
    
    $data[] = [
        'consultation_date' => date('M d, Y h:i A', strtotime($row['consultation_date'])),
        'patient_name' => htmlspecialchars($row['patient_name']) . '<br><small class="text-muted">' . $age . 'Y, ' . $row['gender'] . '</small>',
        'type' => $type_badge,
        'chief_complaint' => htmlspecialchars(substr($row['chief_complaint'], 0, 50)) . '...',
        'diagnosis' => htmlspecialchars(substr($row['diagnosis'] ?: 'N/A', 0, 50)),
        'follow_up' => $follow_up,
        'actions' => $actions
    ];
}

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

$conn->close();
?>