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

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

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

$user_id = $_SESSION['user_id'];

// Get doctor_id from doctors table
$doctor_query = "SELECT doctor_id FROM doctors WHERE user_id = ?";
$doctor_stmt = $conn->prepare($doctor_query);
if (!$doctor_stmt) {
    echo json_encode(['error' => 'Database error: ' . $conn->error, 'data' => []]);
    exit();
}
$doctor_stmt->bind_param("i", $user_id);
if (!$doctor_stmt->execute()) {
    echo json_encode(['error' => 'Query error: ' . $doctor_stmt->error, 'data' => []]);
    exit();
}
$doctor_result = $doctor_stmt->get_result();
$doctor_data = $doctor_result->fetch_assoc();
$doctor_id = $doctor_data ? $doctor_data['doctor_id'] : 0;

if ($doctor_id == 0) {
    echo json_encode(['error' => 'Doctor not found', 'data' => []]);
    exit();
}

$query = "SELECT 
    p.patient_id,
    p.patient_number,
    u.full_name as patient_name,
    u.phone_primary,
    u.email,
    u.date_of_birth,
    u.gender,
    p.blood_group,
    MIN(c.started_at) as first_visit,
    MAX(c.started_at) as last_visit,
    COUNT(c.consultation_id) as total_visits,
    (SELECT c2.next_appointment 
     FROM consultations c2 
     WHERE c2.patient_id = p.patient_id 
     AND c2.doctor_id = ? 
     AND c2.next_appointment IS NOT NULL 
     AND c2.next_appointment >= CURDATE() 
     ORDER BY c2.next_appointment 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, u.date_of_birth, u.gender, p.blood_group
ORDER BY MAX(c.started_at) DESC";

$stmt = $conn->prepare($query);
if (!$stmt) {
    echo json_encode(['error' => 'Database error: ' . $conn->error, 'data' => []]);
    exit();
}

$stmt->bind_param("ii", $doctor_id, $doctor_id);
if (!$stmt->execute()) {
    echo json_encode(['error' => 'Query error: ' . $stmt->error, 'data' => []]);
    exit();
}

$result = $stmt->get_result();

$data = [];

while ($row = $result->fetch_assoc()) {
    // Calculate age
    $age = 'N/A';
    if (!empty($row['date_of_birth'])) {
        $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 . ($age !== 'N/A' ? ' years ' : ' ') . $gender_icon;
    
    // Format dates
    $first_visit = !empty($row['first_visit']) ? date('d M Y', strtotime($row['first_visit'])) : 'N/A';
    $last_visit = !empty($row['last_visit']) ? date('d M Y', strtotime($row['last_visit'])) : 'N/A';
    
    // 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();
?>