<?php
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/helpers.php';

check_auth();

$lang = $_SESSION['lang'] ?? 'en';
$date = $_GET['date'] ?? date('Y-m-d');
$doctor_id = $_GET['doctor_id'] ?? '';

$db = db();

// Fetch Doctor Name if filtered
$doctor_name = '';
if ($doctor_id) {
    // doctor_id is now employee_id
    $stmt = $db->prepare("SELECT name_$lang FROM employees WHERE id = ?");
    $stmt->execute([$doctor_id]);
    $doctor_name = $stmt->fetchColumn();
}

// Fetch Holidays for the date
$holidays_on_date = [];
if ($doctor_id) {
    // Specific doctor holiday check (using leave_requests)
    $stmt = $db->prepare("SELECT reason FROM leave_requests WHERE employee_id = ? AND status = 'Approved' AND ? BETWEEN start_date AND end_date");
    $stmt->execute([$doctor_id, $date]);
    $holiday_note = $stmt->fetchColumn();
    if ($holiday_note !== false) {
        $holidays_on_date[] = [
            'doctor_name' => $doctor_name,
            'note' => $holiday_note
        ];
    }
} else {
    // All doctors holiday check (using leave_requests and filtering by position Doctor)
    $stmt = $db->prepare("
        SELECT e.name_$lang as doctor_name, lr.reason as note 
        FROM leave_requests lr 
        JOIN employees e ON lr.employee_id = e.id 
        JOIN positions p ON e.position_id = p.id
        WHERE lr.status = 'Approved' 
          AND UPPER(p.name_en) = 'DOCTOR'
          AND ? BETWEEN lr.start_date AND lr.end_date
    ");
    $stmt->execute([$date]);
    $holidays_on_date = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Fetch Appointments
$query = "
    SELECT 
        a.start_time, a.end_time, a.status, a.reason,
        p.name as patient_name, p.phone as patient_tel,
        d.name_$lang as doctor_name
    FROM appointments a
    JOIN patients p ON a.patient_id = p.id
    LEFT JOIN employees d ON a.doctor_id = d.id
    WHERE DATE(a.start_time) = ?
";
$params = [$date];

if ($doctor_id) {
    $query .= " AND a.doctor_id = ?";
    $params[] = $doctor_id;
}

$query .= " ORDER BY a.start_time ASC";

$stmt = $db->prepare($query);
$stmt->execute($params);
$appointments = $stmt->fetchAll();

?>
<!DOCTYPE html>
<html lang="<?php echo $lang; ?>" dir="<?php echo $lang == 'ar' ? 'rtl' : 'ltr'; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo __('appointments'); ?> - <?php echo $date; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #fff; color: #000; }
        @media print {
            .no-print { display: none !important; }
            body { padding: 0; margin: 0; }
            .container { max-width: 100% !important; }
            a[href]:after { content: none !important; }
        }
        .header-box { border-bottom: 2px solid #000; padding-bottom: 15px; margin-bottom: 20px; }
        .table thead th { background-color: #f0f0f0 !important; border-bottom: 2px solid #000; }
        .table td, .table th { border: 1px solid #ddd; padding: 8px 12px; vertical-align: middle; }
        .holiday-banner { background-color: #fff3cd; border: 1px solid #ffeeba; color: #856404; padding: 10px; margin-bottom: 15px; border-radius: 4px; }
        @media print {
            .holiday-banner { border: 1px solid #000; background-color: #eee; color: #000; }
        }
    </style>
</head>
<body class="p-4">

<div class="container">
    <div class="d-flex justify-content-between align-items-center mb-4 no-print">
        <a href="javascript:window.close()" class="btn btn-outline-secondary">&larr; <?php echo __('back'); ?></a>
        <button onclick="window.print()" class="btn btn-primary"><?php echo __('print'); ?></button>
    </div>

    <div class="header-box text-center">
        <h3><?php echo __('appointments_list'); ?></h3>
        <p class="mb-1"><strong><?php echo __('date'); ?>:</strong> <?php echo date('l, d F Y', strtotime($date)); ?></p>
        <?php if ($doctor_name): ?>
            <p class="mb-0"><strong><?php echo __('doctor'); ?>:</strong> <?php echo htmlspecialchars($doctor_name); ?></p>
        <?php endif; ?>
    </div>

    <?php if (!empty($holidays_on_date)): ?>
        <div class="holiday-banner">
            <h5 class="mb-2 fw-bold">⚠️ <?php echo __('doctor_holidays'); ?></h5>
            <ul class="mb-0 ps-3">
                <?php foreach ($holidays_on_date as $h): ?>
                    <li>
                        <strong><?php echo htmlspecialchars($h['doctor_name']); ?>:</strong> 
                        <?php echo htmlspecialchars($h['note'] ?: 'On Holiday'); ?>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if (empty($appointments)): ?>
        <div class="alert alert-light text-center border p-5">
            <h4><?php echo __('no_appointments'); ?></h4>
        </div>
    <?php else: ?>
        <table class="table table-striped w-100">
            <thead>
                <tr>
                    <th width="15%"><?php echo __('time'); ?></th>
                    <th width="25%"><?php echo __('patient'); ?></th>
                    <th width="15%"><?php echo __('phone'); ?></th>
                    <?php if (!$doctor_id): ?>
                    <th width="20%"><?php echo __('doctor'); ?></th>
                    <?php endif; ?>
                    <th width="25%"><?php echo __('reason'); ?> / <?php echo __('notes'); ?></th>
                    <th width="10%"><?php echo __('status'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($appointments as $app): ?>
                <tr>
                    <td class="fw-bold"><?php echo date('h:i A', strtotime($app['start_time'])); ?></td>
                    <td><?php echo htmlspecialchars($app['patient_name']); ?></td>
                    <td><?php echo htmlspecialchars($app['patient_tel']); ?></td>
                    <?php if (!$doctor_id): ?>
                    <td><?php echo htmlspecialchars($app['doctor_name']); ?></td>
                    <?php endif; ?>
                    <td><?php echo htmlspecialchars($app['reason'] ?: '-'); ?></td>
                    <td>
                        <?php 
                        $statusClass = match($app['status']) {
                            'Completed' => 'success',
                            'Cancelled' => 'danger',
                            default => 'primary'
                        };
                        ?>
                        <span class="badge bg-<?php echo $statusClass; ?> text-dark bg-opacity-10 border border-<?php echo $statusClass; ?>">
                            <?php echo $app['status']; ?>
                        </span>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>

    <div class="mt-5 pt-3 border-top text-center text-muted small">
        <p><?php echo __('printed_on'); ?> <?php echo date('d/m/Y H:i'); ?></p>
    </div>
</div>

</body>
</html>