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

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

$doctor_id = $_SESSION['user_id'];

// Build query based on filters
$where = "WHERE a.doctor_id = ?";
$params = [$doctor_id];
$types = "i";

// Date range filter
if (!empty($_POST['date_range'])) {
    $dates = explode(' to ', $_POST['date_range']);
    if (count($dates) == 2) {
        $where .= " AND a.appointment_date BETWEEN ? AND ?";
        $params[] = $dates[0];
        $params[] = $dates[1];
        $types .= "ss";
    } elseif (count($dates) == 1) {
        $where .= " AND a.appointment_date >= ?";
        $params[] = $dates[0];
        $types .= "s";
    }
}

// Status filter
if (!empty($_POST['status'])) {
    $where .= " AND a.status = ?";
    $params[] = $_POST['status'];
    $types .= "s";
}

// Patient search
if (!empty($_POST['patient'])) {
    $where .= " AND (p.first_name LIKE ? OR p.last_name LIKE ? OR p.patient_number LIKE ?)";
    $search = '%' . $_POST['patient'] . '%';
    $params[] = $search;
    $params[] = $search;
    $params[] = $search;
    $types .= "sss";
}

$query = "SELECT 
    a.appointment_id,
    a.appointment_number,
    a.appointment_date,
    a.appointment_time,
    a.appointment_type,
    a.status,
    a.chief_complaint,
    p.patient_id,
    p.patient_number,
    p.first_name,
    p.last_name,
    p.phone_number,
    p.email
FROM appointments a
INNER JOIN patients p ON a.patient_id = p.patient_id
$where
ORDER BY a.appointment_date ASC, a.appointment_time ASC";

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

$data = [];
while ($row = $result->fetch_assoc()) {
    // Format date and time
    $datetime = date('d M Y', strtotime($row['appointment_date'])) . ' ' . 
                date('h:i A', strtotime($row['appointment_time']));
    
    // Format patient name
    $patient_name = $row['first_name'] . ' ' . $row['last_name'] . 
                   '<br><small class="text-muted">' . $row['patient_number'] . '</small>';
    
    // Format contact
    $contact = $row['phone_number'];
    if ($row['email']) {
        $contact .= '<br><small>' . $row['email'] . '</small>';
    }
    
    // Format type
    $type_badge = [
        'CONSULTATION' => 'info',
        'FOLLOW_UP' => 'primary',
        'PROCEDURE' => 'warning',
        'EMERGENCY' => 'danger',
        'TELEMEDICINE' => 'success'
    ];
    $type = '<span class="badge bg-' . ($type_badge[$row['appointment_type']] ?? 'secondary') . '">' . 
            str_replace('_', ' ', $row['appointment_type']) . '</span>';
    
    // Format status
    $status_badge = [
        'SCHEDULED' => 'info',
        'CONFIRMED' => 'primary',
        'CHECKED_IN' => 'warning',
        'IN_PROGRESS' => 'primary',
        'COMPLETED' => 'success',
        'CANCELLED' => 'danger',
        'NO_SHOW' => 'dark'
    ];
    $status = '<span class="badge bg-' . ($status_badge[$row['status']] ?? 'secondary') . '">' . 
              str_replace('_', ' ', $row['status']) . '</span>';
    
    // Format reason
    $reason = $row['chief_complaint'] ? substr($row['chief_complaint'], 0, 50) . 
              (strlen($row['chief_complaint']) > 50 ? '...' : '') : '-';
    
    // Actions
    $actions = '<div class="btn-group" role="group">';
    
    if (in_array($row['status'], ['SCHEDULED', 'CONFIRMED'])) {
        $actions .= '<button class="btn btn-sm btn-soft-primary btn-reschedule" data-id="' . 
                   $row['appointment_id'] . '" title="Reschedule">
                   <i class="ri-calendar-line"></i></button>';
        
        $actions .= '<button class="btn btn-sm btn-soft-danger btn-cancel" data-id="' . 
                   $row['appointment_id'] . '" title="Cancel">
                   <i class="ri-close-line"></i></button>';
    }
    
    $actions .= '<a href="appointment_details.php?id=' . $row['appointment_id'] . 
               '" class="btn btn-sm btn-soft-info" title="View Details">
               <i class="ri-eye-line"></i></a>';
    
    $actions .= '</div>';
    
    $data[] = [
        'appointment_id' => $row['appointment_number'],
        'datetime' => $datetime,
        'patient_name' => $patient_name,
        'contact' => $contact,
        'type' => $type,
        'reason' => $reason,
        'status' => $status,
        'actions' => $actions
    ];
}

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