<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('HTTP/1.1 403 Forbidden');
    exit('غير مصرح لك بالوصول');
}

$db = new Database();
$conn = $db->getConnection();

// Log export activity
logActivity($conn, $_SESSION['user_id'], 'تصدير المرضى Excel', 'patients');

// Get patients data
$stmt = $conn->query("
    SELECT 
        p.id,
        p.patient_name,
        p.mrn,
        p.gender,
        p.units,
        p.reporting_pharmacist_id,
        p.created_at,
        COUNT(ar.id) as report_count,
        MAX(ar.created_at) as last_report_date
    FROM patients p
    LEFT JOIN antibiotic_reports ar ON p.id = ar.patient_id
    GROUP BY p.id
    ORDER BY p.created_at DESC
");
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate statistics
$total_patients = count($data);
$male_patients = count(array_filter($data, function($p) { return $p['gender'] == 'male'; }));
$female_patients = count(array_filter($data, function($p) { return $p['gender'] == 'female'; }));
$patients_with_reports = count(array_filter($data, function($p) { return $p['report_count'] > 0; }));

// Create Excel file with HTML table
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="patients_' . date('Y-m-d_H-i-s') . '.xls"');
header('Cache-Control: max-age=0');
header('Pragma: public');

echo "\xEF\xBB\xBF";
?>
<!DOCTYPE html>
<html dir="rtl">
<head>
    <meta charset="UTF-8">
    <style>
        body {
            font-family: 'Arial', 'Tahoma', sans-serif;
            direction: rtl;
            margin: 0;
            padding: 0;
        }
        table {
            border-collapse: collapse;
            width: 100%;
            direction: rtl;
            font-family: 'Arial', 'Tahoma', sans-serif;
        }
        .data-table td {
            padding: 8px 10px;
            text-align: center;
            border: 1px solid #adb5bd;
            font-size: 10pt;
            vertical-align: middle;
        }
        .data-table tr:nth-child(odd) td {
            background-color: #ffffff;
        }
        .data-table tr:nth-child(even) td {
            background-color: #f2f7ff;
        }
        .gender-male {
            background-color: #cfe2ff;
            color: #084298;
            font-weight: bold;
            padding: 4px 8px;
        }
        .gender-female {
            background-color: #f7d6e6;
            color: #ab296a;
            font-weight: bold;
            padding: 4px 8px;
        }
    </style>
</head>
<body>
    <!-- Header Table -->
    <table>
        <tr><td colspan="8" style="background-color:#1a3a5c; color:#ffffff; font-size:16pt; font-weight:bold; text-align:center; padding:12px;">قائمة المرضى الشاملة</td></tr>
        <tr><td colspan="8" style="background-color:#2e5c8a; color:#ffffff; font-size:10pt; text-align:center; padding:5px;">مستشفى مدينة نصر التخصصي - Nasr City Specialized Hospital | تاريخ التصدير: <?php echo date('Y-m-d h:i A'); ?></td></tr>
        <tr><td colspan="8" style="height:8px; border:none;"></td></tr>
    </table>

    <!-- Statistics Table -->
    <table>
        <tr><td colspan="4" style="background-color:#D9E1F2; color:#1F3864; font-weight:bold; font-size:12pt; text-align:right; padding:8px 12px; border:2px solid #4472C4;">الإحصائيات العامة</td></tr>
        <tr>
            <td style="background-color:#d1f2eb; font-weight:bold; padding:8px 12px; border:1px solid #dee2e6; color:#0f5132; width:25%;">إجمالي المرضى</td>
            <td style="background-color:#fff; text-align:center; font-weight:bold; color:#28a745; font-size:13pt; border:1px solid #dee2e6; width:25%;"><?php echo $total_patients; ?></td>
            <td style="background-color:#d1f2eb; font-weight:bold; padding:8px 12px; border:1px solid #dee2e6; color:#0f5132; width:25%;">مرضى ذكور</td>
            <td style="background-color:#fff; text-align:center; font-weight:bold; color:#28a745; font-size:13pt; border:1px solid #dee2e6; width:25%;"><?php echo $male_patients; ?></td>
        </tr>
        <tr>
            <td style="background-color:#d1f2eb; font-weight:bold; padding:8px 12px; border:1px solid #dee2e6; color:#0f5132;">مرضى إناث</td>
            <td style="background-color:#fff; text-align:center; font-weight:bold; color:#28a745; font-size:13pt; border:1px solid #dee2e6;"><?php echo $female_patients; ?></td>
            <td style="background-color:#d1f2eb; font-weight:bold; padding:8px 12px; border:1px solid #dee2e6; color:#0f5132;">مرضى لديهم تقارير</td>
            <td style="background-color:#fff; text-align:center; font-weight:bold; color:#28a745; font-size:13pt; border:1px solid #dee2e6;"><?php echo $patients_with_reports; ?></td>
        </tr>
        <tr><td colspan="4" style="height:8px; border:none;"></td></tr>
    </table>

    <!-- Data Table -->
    <table class="data-table">
        <thead>
            <tr>
                <th style="background-color:#4472C4; color:#ffffff; font-weight:bold; padding:10px; border:1px solid #2e5c8a; width:70px;">الرقم</th>
                <th style="background-color:#4472C4; color:#ffffff; font-weight:bold; padding:10px; border:1px solid #2e5c8a; width:180px;">اسم المريض</th>
                <th style="background-color:#4472C4; color:#ffffff; font-weight:bold; padding:10px; border:1px solid #2e5c8a; width:120px;">رقم الملف (MRN)</th>
                <th style="background-color:#4472C4; color:#ffffff; font-weight:bold; padding:10px; border:1px solid #2e5c8a; width:90px;">الجنس</th>
                <th style="background-color:#4472C4; color:#ffffff; font-weight:bold; padding:10px; border:1px solid #2e5c8a; width:220px;">الأقسام</th>
                <th style="background-color:#4472C4; color:#ffffff; font-weight:bold; padding:10px; border:1px solid #2e5c8a; width:100px;">عدد التقارير</th>
                <th style="background-color:#4472C4; color:#ffffff; font-weight:bold; padding:10px; border:1px solid #2e5c8a; width:130px;">آخر تقرير</th>
                <th style="background-color:#4472C4; color:#ffffff; font-weight:bold; padding:10px; border:1px solid #2e5c8a; width:140px;">تاريخ الإضافة</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($data)): ?>
                <tr>
                    <td colspan="8" style="text-align:center; padding:30px; color:#999;">لا توجد بيانات</td>
                </tr>
            <?php else: ?>
                <?php foreach ($data as $row): ?>
                <tr>
                    <td><?php echo htmlspecialchars($row['id']); ?></td>
                    <td style="text-align:right;"><?php echo htmlspecialchars($row['patient_name']); ?></td>
                    <td><?php echo htmlspecialchars($row['mrn']); ?></td>
                    <td class="<?php echo $row['gender'] == 'male' ? 'gender-male' : 'gender-female'; ?>">
                        <?php echo $row['gender'] == 'male' ? 'ذكر' : 'أنثى'; ?>
                    </td>
                    <td style="text-align:right;"><?php 
                        $units = json_decode($row['units'], true);
                        if (is_array($units)) {
                            echo htmlspecialchars(implode(', ', $units));
                        } else {
                            echo '-';
                        }
                    ?></td>
                    <td><?php echo htmlspecialchars($row['report_count']); ?></td>
                    <td><?php echo $row['last_report_date'] ? date('Y-m-d', strtotime($row['last_report_date'])) : '-'; ?></td>
                    <td><?php echo htmlspecialchars($row['created_at']); ?></td>
                </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>

    <!-- Footer Table -->
    <table>
        <tr><td colspan="3" style="background-color:#f2f2f2; text-align:center; padding:10px; font-size:9pt; color:#555; border:1px solid #ccc;">نظام الصيدلة الإكلينيكية المتكامل (ICS) - مستشفى مدينة نصر التخصصي | تم التصدير بواسطة: <?php echo htmlspecialchars($_SESSION['full_name']); ?> | التاريخ: <?php echo date('Y-m-d h:i A'); ?></td></tr>
    </table>
</body>
</html>
