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

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['data' => []]);
    exit();
}

$doctor_id = $_SESSION['user_id'];

$query = "SELECT 
    p.patient_id,
    p.patient_number,
    u.full_name as patient_name,
    u.phone_primary,
    u.email,
    p.date_of_birth,
    p.gender,
    p.blood_group,
    MIN(c.consultation_date) as first_visit,
    MAX(c.consultation_date) as last_visit,
    COUNT(c.consultation_id) as total_visits,
    (SELECT c2.follow_up_date 
     FROM consultations c2 
     WHERE c2.patient_id = p.patient_id 
     AND c2.doctor_id = ? 
     AND c2.follow_up_required = 1 
     AND c2.follow_up_date >= CURDATE() 
     ORDER BY c2.follow_up_date ASC 
     LIMIT 1) as next_follow_up
FROM patients p
INNER JOIN users u ON p.user_id = u.user_id
INNER JOIN consultations c ON p.patient_id = c.patient_id
WHERE c.doctor_id = ?
GROUP BY p.patient_id, p.patient_number, u.full_name, u.phone_primary, u.email, p.date_of_birth, p.gender, p.blood_group
ORDER BY MAX(c.consultation_date) DESC";

$stmt = $conn->prepare($query);
$stmt->bind_param("ii", $doctor_id, $doctor_id);
$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 = $dob->diff($now)->y;
    
    // Age and Gender
    $gender_icon = $row['gender'] == 'MALE' ? '♂' : ($row['gender'] == 'FEMALE' ? '♀' : '⚲');
    $age_gender = $age . ' years ' . $gender_icon;
    
    // Format dates
    $first_visit = date('d M Y', strtotime($row['first_visit']));
    $last_visit = date('d M Y', strtotime($row['last_visit']));
    
    // Follow-up status
    $follow_up = 'N/A';
    if ($row['next_follow_up']) {
        $follow_up_date = date('d M Y', strtotime($row['next_follow_up']));
        $days_until = (new DateTime($row['next_follow_up']))->diff(new DateTime())->days;
        $follow_up = '<span class="badge badge-soft-warning">' . $follow_up_date . ' (' . $days_until . ' days)</span>';
    }
    
    // Actions
    $actions = '
        <a href="patient_medical_history.php?patient_id=' . $row['patient_id'] . '" 
           class="btn btn-sm btn-info me-1" title="View History">
            <i class="ri-history-line"></i>
        </a>
        <a href="new_consultation.php?patient_id=' . $row['patient_id'] . '" 
           class="btn btn-sm btn-success me-1" title="New Consultation">
            <i class="ri-stethoscope-line"></i>
        </a>
        <a href="patient_documents.php?patient_id=' . $row['patient_id'] . '" 
           class="btn btn-sm btn-primary" title="Documents">
            <i class="ri-file-text-line"></i>
        </a>';
    
    $data[] = [
        'patient_id' => htmlspecialchars($row['patient_number']),
        'patient_name' => htmlspecialchars($row['patient_name']),
        'age_gender' => $age_gender,
        'contact' => htmlspecialchars($row['phone_primary']),
        'first_visit' => $first_visit,
        'last_visit' => $last_visit,
        'total_visits' => '<span class="badge badge-soft-primary">' . $row['total_visits'] . '</span>',
        'follow_up' => $follow_up,
        'actions' => $actions
    ];
}

echo json_encode(['data' => $data]);
$conn->close();
?>