<?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 
    c.consultation_id,
    c.consultation_date as last_visit,
    c.follow_up_date,
    c.follow_up_reason,
    c.diagnosis,
    c.follow_up_completed,
    p.patient_id,
    p.patient_number,
    u.full_name as patient_name,
    u.phone_primary,
    p.date_of_birth
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 c.doctor_id = ? 
AND c.follow_up_required = 1
AND c.follow_up_date IS NOT NULL
AND c.follow_up_completed = 0
ORDER BY c.follow_up_date ASC";

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

$data = [];

while ($row = $result->fetch_assoc()) {
    $follow_up_date = date('d M Y', strtotime($row['follow_up_date']));
    $last_visit = date('d M Y', strtotime($row['last_visit']));
    
    // Status
    $today = date('Y-m-d');
    if ($row['follow_up_date'] < $today) {
        $status = '<span class="badge badge-soft-danger">Overdue</span>';
        $card_class = 'overdue';
    } elseif ($row['follow_up_date'] == $today) {
        $status = '<span class="badge badge-soft-warning">Today</span>';
        $card_class = 'today';
    } else {
        $days_until = (new DateTime($row['follow_up_date']))->diff(new DateTime())->days;
        $status = '<span class="badge badge-soft-info">' . $days_until . ' days</span>';
        $card_class = '';
    }
    
    // Actions
    $actions = '
        <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_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>
        <button class="btn btn-sm btn-primary btn-schedule me-1" 
                data-patient-id="' . $row['patient_id'] . '" title="Schedule Appointment">
            <i class="ri-calendar-line"></i>
        </button>
        <button class="btn btn-sm btn-secondary btn-mark-completed" 
                data-id="' . $row['consultation_id'] . '" title="Mark Complete">
            <i class="ri-check-line"></i>
        </button>';
    
    $data[] = [
        'follow_up_date' => $follow_up_date,
        'patient_name' => htmlspecialchars($row['patient_name']),
        'contact' => htmlspecialchars($row['phone_primary']),
        'last_visit' => $last_visit,
        'diagnosis' => htmlspecialchars(substr($row['diagnosis'], 0, 50)) . (strlen($row['diagnosis']) > 50 ? '...' : ''),
        'reason' => htmlspecialchars($row['follow_up_reason'] ?? 'Routine follow-up'),
        'status' => $status,
        'actions' => $actions
    ];
}

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