<?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', 'departments_summary');

// Define departments mapping
$departments = [
    'الدور الرابع' => ['4th floor', '4TH'],
    'الدور الخامس' => ['5th floor', '5TH'], 
    'الدور السادس' => ['6th Floor', '6TH'],
    'الحضانة' => ['NICU', 'NICU'],
    'رعاية اطفال' => ['NICU', 'NICU'], // Same as NICU for now
    'رعاية حرجة' => ['4th ICU', '4ICU'],
    'رعاية مركزة' => ['CICU', 'CICU'],
    'رعاية قلب' => ['CCU', 'CCU']
];

// Set headers for Excel download
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="departments_summary_' . date('Y-m-d_H-i-s') . '.xls"');
header('Cache-Control: max-age=0');
header('Pragma: public');

// Output UTF-8 BOM for proper Arabic display
echo "\xEF\xBB\xBF";
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <style>
        body {
            font-family: 'Arial', 'Tahoma', sans-serif;
            direction: rtl;
            margin: 0;
            padding: 20px;
            font-size: 11pt;
        }
        
        .summary-table {
            border-collapse: collapse;
            width: 100%;
            margin-bottom: 30px;
        }
        
        .summary-table th {
            background-color: #4472C4;
            color: #ffffff;
            font-weight: bold;
            padding: 12px 10px;
            text-align: center;
            border: 2px solid #2e5c8a;
            font-size: 11pt;
            white-space: nowrap;
        }
        
        .summary-table td {
            padding: 10px;
            text-align: center;
            border: 1px solid #bdc3c7;
            font-size: 10pt;
        }
        
        .summary-table tr:nth-child(odd) td {
            background-color: #ffffff;
        }
        
        .summary-table tr:nth-child(even) td {
            background-color: #f2f7ff;
        }
        
        .dept-name {
            text-align: right !important;
            font-weight: bold;
            background-color: #ecf0f1 !important;
            color: #2c3e50;
        }
        
        .total-row td {
            background-color: #fff3cd !important;
            font-weight: bold;
            border: 2px solid #ffc107;
            font-size: 11pt;
        }
        
        .completion-rate { font-weight: bold; }
        .rate-excellent { color: #28a745; }
        .rate-good { color: #17a2b8; }
        .rate-average { color: #ffc107; }
        .rate-poor { color: #dc3545; }
    </style>
</head>
<body>

<!-- Header Table -->
<table>
    <tr><td colspan="10" style="background-color:#1a3a5c; color:#ffffff; font-size:16pt; font-weight:bold; text-align:center; padding:12px;">ملخص الأقسام - تقرير سريع</td></tr>
    <tr><td colspan="10" style="background-color:#2e5c8a; color:#ffffff; font-size:10pt; text-align:center; padding:5px;">مستشفى مدينة نصر التخصصي - Nasr City Specialized Hospital | نظام الصيدلة الإكلينيكية المتكامل (ICS) | تاريخ التصدير: <?php echo date('Y-m-d H:i:s'); ?> | المستخدم: <?php echo htmlspecialchars($_SESSION['full_name']); ?></td></tr>
    <tr><td colspan="10" style="height:8px; border:none;"></td></tr>
</table>

<!-- Summary Table -->
<table class="summary-table">
    <thead>
        <tr>
            <th style="width: 200px;">اسم القسم</th>
            <th style="width: 80px;">كود القسم</th>
            <th style="width: 100px;">إجمالي التقارير</th>
            <th style="width: 100px;">التقارير المكتملة</th>
            <th style="width: 100px;">التقارير المعلقة</th>
            <th style="width: 100px;">عدد المرضى الفريد</th>
            <th style="width: 80px;">مرضى ذكور</th>
            <th style="width: 80px;">مرضى إناث</th>
            <th style="width: 100px;">معدل الإكمال %</th>
            <th style="width: 120px;">آخر تقرير</th>
        </tr>
    </thead>
    <tbody>
        <?php
        // Initialize totals
        $grand_total_reports = 0;
        $grand_total_completed = 0;
        $grand_total_pending = 0;
        $grand_total_patients = 0;
        $grand_total_male = 0;
        $grand_total_female = 0;
        $latest_report_date = '';
        
        // Loop through each department
        foreach ($departments as $dept_name => $dept_info):
            list($unit_name, $unit_code) = $dept_info;
            
            // Get department statistics
            $stmt = $conn->prepare("
                SELECT 
                    COUNT(ar.id) as total_reports,
                    SUM(CASE WHEN ar.status = 'completed' THEN 1 ELSE 0 END) as completed_reports,
                    SUM(CASE WHEN ar.status = 'pending' THEN 1 ELSE 0 END) as pending_reports,
                    COUNT(DISTINCT ar.patient_id) as unique_patients,
                    SUM(CASE WHEN p.gender = 'male' THEN 1 ELSE 0 END) as male_patients,
                    SUM(CASE WHEN p.gender = 'female' THEN 1 ELSE 0 END) as female_patients,
                    MAX(ar.report_date) as latest_report
                FROM antibiotic_reports ar
                JOIN patients p ON ar.patient_id = p.id
                JOIN units u ON ar.unit_id = u.id
                WHERE u.unit_name = ? OR u.unit_code = ?
            ");
            $stmt->execute([$unit_name, $unit_code]);
            $stats = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $total_reports = $stats['total_reports'] ?? 0;
            $completed_reports = $stats['completed_reports'] ?? 0;
            $pending_reports = $stats['pending_reports'] ?? 0;
            $unique_patients = $stats['unique_patients'] ?? 0;
            $male_patients = $stats['male_patients'] ?? 0;
            $female_patients = $stats['female_patients'] ?? 0;
            $latest_report = $stats['latest_report'] ?? '-';
            
            $completion_rate = $total_reports > 0 ? round(($completed_reports / $total_reports) * 100, 1) : 0;
            
            // Determine completion rate class
            $rate_class = 'rate-poor';
            if ($completion_rate >= 90) $rate_class = 'rate-excellent';
            elseif ($completion_rate >= 70) $rate_class = 'rate-good';
            elseif ($completion_rate >= 50) $rate_class = 'rate-average';
            
            // Add to grand totals
            $grand_total_reports += $total_reports;
            $grand_total_completed += $completed_reports;
            $grand_total_pending += $pending_reports;
            $grand_total_patients += $unique_patients;
            $grand_total_male += $male_patients;
            $grand_total_female += $female_patients;
            
            if ($latest_report > $latest_report_date) {
                $latest_report_date = $latest_report;
            }
        ?>
        <tr>
            <td class="dept-name"><?php echo $dept_name; ?></td>
            <td><?php echo $unit_code; ?></td>
            <td><?php echo $total_reports; ?></td>
            <td><?php echo $completed_reports; ?></td>
            <td><?php echo $pending_reports; ?></td>
            <td><?php echo $unique_patients; ?></td>
            <td><?php echo $male_patients; ?></td>
            <td><?php echo $female_patients; ?></td>
            <td class="completion-rate <?php echo $rate_class; ?>"><?php echo $completion_rate; ?>%</td>
            <td><?php echo $latest_report; ?></td>
        </tr>
        <?php endforeach; ?>
        
        <!-- Total Row -->
        <tr class="total-row">
            <td class="dept-name">الإجمالي العام</td>
            <td>-</td>
            <td><?php echo $grand_total_reports; ?></td>
            <td><?php echo $grand_total_completed; ?></td>
            <td><?php echo $grand_total_pending; ?></td>
            <td><?php echo $grand_total_patients; ?></td>
            <td><?php echo $grand_total_male; ?></td>
            <td><?php echo $grand_total_female; ?></td>
            <td class="completion-rate"><?php echo $grand_total_reports > 0 ? round(($grand_total_completed / $grand_total_reports) * 100, 1) : 0; ?>%</td>
            <td><?php echo $latest_report_date; ?></td>
        </tr>
    </tbody>
</table>

<!-- Charts Section -->
<table class="summary-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>
            <th>المؤشر</th>
            <th>القيمة</th>
            <th>التقييم</th>
            <th>ملاحظات</th>
        </tr>
        <tr>
            <td class="dept-name">معدل الإكمال العام</td>
            <td class="completion-rate <?php 
                $overall_rate = $grand_total_reports > 0 ? round(($grand_total_completed / $grand_total_reports) * 100, 1) : 0;
                if ($overall_rate >= 90) echo 'rate-excellent';
                elseif ($overall_rate >= 70) echo 'rate-good';
                elseif ($overall_rate >= 50) echo 'rate-average';
                else echo 'rate-poor';
            ?>"><?php echo $overall_rate; ?>%</td>
            <td><?php 
                if ($overall_rate >= 90) echo 'ممتاز';
                elseif ($overall_rate >= 70) echo 'جيد';
                elseif ($overall_rate >= 50) echo 'متوسط';
                else echo 'يحتاج تحسين';
            ?></td>
            <td>من إجمالي <?php echo $grand_total_reports; ?> تقرير</td>
        </tr>
        <tr>
            <td class="dept-name">نسبة الذكور إلى الإناث</td>
            <td><?php 
                $total_gender = $grand_total_male + $grand_total_female;
                if ($total_gender > 0) {
                    echo round(($grand_total_male / $total_gender) * 100, 1) . '% : ' . round(($grand_total_female / $total_gender) * 100, 1) . '%';
                } else {
                    echo 'لا توجد بيانات';
                }
            ?></td>
            <td>متوازن</td>
            <td><?php echo $grand_total_male; ?> ذكر، <?php echo $grand_total_female; ?> أنثى</td>
        </tr>
        <tr>
            <td class="dept-name">متوسط التقارير لكل قسم</td>
            <td><?php echo count($departments) > 0 ? round($grand_total_reports / count($departments), 1) : 0; ?></td>
            <td>-</td>
            <td>من <?php echo count($departments); ?> أقسام</td>
        </tr>
        <tr>
            <td class="dept-name">متوسط المرضى لكل قسم</td>
            <td><?php echo count($departments) > 0 ? round($grand_total_patients / count($departments), 1) : 0; ?></td>
            <td>-</td>
            <td>إجمالي <?php echo $grand_total_patients; ?> مريض فريد</td>
        </tr>
    </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 date('Y-m-d H:i:s'); ?> | بواسطة: <?php echo htmlspecialchars($_SESSION['full_name']); ?> | الأقسام المشمولة: الدور الرابع، الخامس، السادس، الحضانة، رعاية الأطفال، الرعاية الحرجة، الرعاية المركزة، رعاية القلب</td></tr>
</table>

</body>
</html>
