<?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'];
$today = date('Y-m-d');

$query = "SELECT 
    a.appointment_id,
    a.appointment_date,
    a.appointment_time,
    a.appointment_type,
    a.reason_for_visit,
    a.appointment_status,
    a.is_follow_up,
    p.patient_id,
    u.full_name as patient_name,
    u.phone_primary,
    p.date_of_birth,
    p.blood_group,
    p.allergies,
    (SELECT COUNT(*) FROM consultations WHERE patient_id = p.patient_id) as visit_count,
    (SELECT MAX(consultation_date) FROM consultations WHERE patient_id = p.patient_id AND doctor_id = a.doctor_id) as last_visit
FROM appointments a
INNER JOIN patients p ON a.patient_id = p.patient_id
INNER JOIN users u ON p.user_id = u.user_id
WHERE a.doctor_id = ? 
AND DATE(a.appointment_date) = ?
ORDER BY a.appointment_time ASC";

$stmt = $conn->prepare($query);
$stmt->bind_param("is", $doctor_id, $today);
$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;
    
    // Format appointment time
    $time = date('h:i A', strtotime($row['appointment_time']));
    
    // Patient info with avatar
    $initials = strtoupper(substr($row['patient_name'], 0, 1));
    $patient_info = '
        <div class="d-flex align-items-center">
            <div class="patient-avatar me-2">' . $initials . '</div>
            <div>
                <strong>' . htmlspecialchars($row['patient_name']) . '</strong><br>
                <small class="text-muted">' . $age . ' years • ' . ($row['blood_group'] ?? 'N/A') . '</small>
            </div>
        </div>';
    
    // Contact info
    $contact = htmlspecialchars($row['phone_primary']);
    
    // Appointment type
    $type_badge = $row['is_follow_up'] ? 
        '<span class="badge badge-soft-info">Follow-up</span>' : 
        '<span class="badge badge-soft-primary">New Visit</span>';
    
    // Reason for visit
    $reason = htmlspecialchars(substr($row['reason_for_visit'], 0, 50));
    if (strlen($row['reason_for_visit']) > 50) {
        $reason .= '...';
    }
    
    // Status badge
    $status_class = '';
    $status_text = '';
    switch ($row['appointment_status']) {
        case 'SCHEDULED':
            $status_class = 'status-scheduled';
            $status_text = 'Scheduled';
            break;
        case 'CHECKED_IN':
            $status_class = 'status-checked-in';
            $status_text = 'Checked In';
            break;
        case 'IN_CONSULTATION':
            $status_class = 'status-in-consultation';
            $status_text = 'In Consultation';
            break;
        case 'COMPLETED':
            $status_class = 'status-completed';
            $status_text = 'Completed';
            break;
        default:
            $status_class = 'badge-soft-secondary';
            $status_text = $row['appointment_status'];
    }
    $status = '<span class="status-badge ' . $status_class . '">' . $status_text . '</span>';
    
    // Actions based on status
    $actions = '';
    if ($row['appointment_status'] == 'CHECKED_IN') {
        $actions .= '<button class="btn btn-sm btn-success btn-start-consultation me-1" 
                            data-id="' . $row['appointment_id'] . '" 
                            data-patient="' . htmlspecialchars($row['patient_name']) . '">
                        <i class="ri-stethoscope-line"></i> Start
                    </button>';
    }
    
    if ($row['appointment_status'] == 'IN_CONSULTATION') {
        $actions .= '<a href="new_consultation.php?appointment_id=' . $row['appointment_id'] . '" 
                       class="btn btn-sm btn-primary me-1">
                        <i class="ri-edit-line"></i> Continue
                    </a>';
    }
    
    $actions .= '<button class="btn btn-sm btn-info btn-view-history me-1" 
                        data-patient-id="' . $row['patient_id'] . '">
                    <i class="ri-history-line"></i> History
                </button>';
    
    if ($row['appointment_status'] != 'COMPLETED' && $row['appointment_status'] != 'CANCELLED') {
        $actions .= '<button class="btn btn-sm btn-secondary btn-mark-completed" 
                            data-id="' . $row['appointment_id'] . '">
                        <i class="ri-check-line"></i> Complete
                    </button>';
    }
    
    $data[] = [
        'appointment_time' => $time,
        'patient_info' => $patient_info,
        'contact' => $contact,
        'appointment_type' => $type_badge,
        'reason' => $reason,
        'status' => $status,
        'actions' => $actions
    ];
}

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