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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

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

// Get filter parameters
$department_id = $_GET['department'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$status = $_GET['status'] ?? '';
$antibiotic = $_GET['antibiotic'] ?? '';
$pharmacist = $_GET['pharmacist'] ?? '';

// Build WHERE clause
$where_conditions = [];
$params = [];

if (!empty($department_id)) {
    $where_conditions[] = "ar.unit_id = ?";
    $params[] = $department_id;
}

if (!empty($date_from)) {
    $where_conditions[] = "ar.report_date >= ?";
    $params[] = $date_from;
}

if (!empty($date_to)) {
    $where_conditions[] = "ar.report_date <= ?";
    $params[] = $date_to;
}

if (!empty($status)) {
    $where_conditions[] = "ar.status = ?";
    $params[] = $status;
}

if (!empty($antibiotic)) {
    $where_conditions[] = "ar.antibiotic_id = ?";
    $params[] = $antibiotic;
}

if (!empty($pharmacist)) {
    $where_conditions[] = "ar.reporting_pharmacist_id = ?";
    $params[] = $pharmacist;
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get department name
$department_name = 'جميع الأقسام';
if (!empty($department_id)) {
    try {
        $stmt = $conn->prepare("SELECT unit_name FROM units WHERE id = ?");
        $stmt->execute([$department_id]);
        $dept = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($dept) {
            $department_name = $dept['unit_name'];
        }
    } catch (Exception $e) {
        // Handle error
    }
}

// Set headers for Excel download
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="department_report_' . date('Y-m-d_H-i-s') . '.xls"');
header('Pragma: no-cache');
header('Expires: 0');

// Output UTF-8 BOM for proper Arabic display
echo "\xEF\xBB\xBF";

try {
    // Get detailed reports data
    $sql = "
        SELECT 
            ar.id,
            ar.report_date,
            p.patient_name,
            p.mrn,
            u.unit_name,
            COALESCE(a.antibiotic_name, ar.other_medication_name, 'غير محدد') as antibiotic_name,
            ar.problem_authority,
            ar.problem_authority_name,
            ar.intervention_choice,
            ar.degree_of_damage,
            ar.result_of_intervention,
            ar.corrective_action,
            ar.result_of_corrective_action,
            ar.recommendations,
            ar.status,
            ph.full_name as pharmacist_name,
            ar.created_at
        FROM antibiotic_reports ar
        LEFT JOIN patients p ON ar.patient_id = p.id
        LEFT JOIN units u ON ar.unit_id = u.id
        LEFT JOIN antibiotics a ON ar.antibiotic_id = a.id
        LEFT JOIN users ph ON ar.reporting_pharmacist_id = ph.id
        $where_clause
        ORDER BY ar.report_date DESC, ar.created_at DESC
    ";
    
    $stmt = $conn->prepare($sql);
    $stmt->execute($params);
    $reports = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die("خطأ في قاعدة البيانات: " . $e->getMessage());
}

?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <title>تقرير تفصيلي للقسم - <?php echo htmlspecialchars($department_name); ?></title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            direction: rtl; 
            font-size: 12px;
        }
        table { 
            border-collapse: collapse; 
            width: 100%; 
            margin-bottom: 20px; 
        }
        th, td { 
            border: 1px solid #000; 
            padding: 4px; 
            text-align: center; 
            vertical-align: middle;
            font-size: 10px;
        }
        th { 
            background-color: #4472C4; 
            color: #ffffff; 
            font-weight: bold; 
            font-size: 9px;
        }
        tr:nth-child(odd) td { background-color: #ffffff; }
        tr:nth-child(even) td { background-color: #f2f7ff; }
        .header { 
            text-align: center; 
            margin-bottom: 20px; 
            background-color: #4472C4;
            color: white;
            padding: 10px;
            font-weight: bold;
        }
        .sub-header {
            background-color: #D9E2F3;
            font-weight: bold;
            text-align: center;
        }
        .patient-info {
            background-color: #F2F2F2;
        }
        .status-pending { background-color: #FFF2CC; }
        .status-completed { background-color: #D5E8D4; }
        .status-cancelled { background-color: #F8CECC; }
        .intervention-1 { background-color: #E1D5E7; }
        .intervention-0 { background-color: #FFFFFF; }
    </style>
</head>
<body>
    <!-- Header Table -->
    <table>
        <tr><td colspan="10" style="background-color:#1a3a5c; color:#ffffff; font-size:14pt; font-weight:bold; text-align:center; padding:10px;">تقرير تفصيلي لإدارة المضادات الحيوية - <?php echo htmlspecialchars($department_name); ?></td></tr>
        <tr><td colspan="10" style="background-color:#2e5c8a; color:#ffffff; font-size:9pt; text-align:center; padding:5px;"><?php if (!empty($date_from) || !empty($date_to)): ?>الفترة: <?php echo $date_from ? date('d/m/Y', strtotime($date_from)) : 'غير محدد'; ?> - <?php echo $date_to ? date('d/m/Y', strtotime($date_to)) : 'غير محدد'; ?> | <?php endif; ?>تاريخ التقرير: <?php echo date('d/m/Y H:i:s'); ?> | تم إنشاؤه بواسطة: <?php echo htmlspecialchars($_SESSION['full_name']); ?></td></tr>
        <tr><td colspan="10" style="height:6px; border:none;"></td></tr>
    </table>

    <table>
        <thead>
            <tr>
                <th rowspan="2">تاريخ محضر<br>ملف المريض</th>
                <th rowspan="2">اسم المريض</th>
                <th rowspan="2">الرقم الطبي</th>
                <th colspan="7">إجراءات التدخل وإدارة الأخطاء المهنية فيما يتعلق بالأدوية غير مكتمل أو الوقت الخطأ فيما يتعلق بالأدوية لا يطبق</th>
            </tr>
            <tr>
                <th>توافق<br>بين الأدوية</th>
                <th>برنامج ترشيد استهلاك<br>المضادات الحيوية</th>
                <th>الأدوية<br>عالية الخطورة</th>
                <th>الأدوية المتشابهة<br>في الشكل والنطق</th>
                <th>تسجيل وتوثيق<br>الأخطاء الطبية</th>
                <th>تعريف الأدوية</th>
                <th>وصف وكمية الدواء</th>
            </tr>
        </thead>
        <tbody>
            <?php if (!empty($reports)): ?>
                <?php foreach ($reports as $report): ?>
                    <tr>
                        <!-- Report Date -->
                        <td class="patient-info"><?php echo date('d/m/Y', strtotime($report['report_date'])); ?></td>
                        
                        <!-- Patient Name -->
                        <td class="patient-info"><?php echo htmlspecialchars($report['patient_name'] ?? 'غير محدد'); ?></td>
                        
                        <!-- Medical Record Number -->
                        <td class="patient-info"><?php echo htmlspecialchars($report['mrn'] ?? 'غير محدد'); ?></td>
                        
                        <!-- Drug Compatibility -->
                        <td class="<?php echo strpos($report['intervention_choice'], 'monitoring') !== false ? 'intervention-1' : 'intervention-0'; ?>">
                            <?php echo strpos($report['intervention_choice'], 'monitoring') !== false ? '1' : '0'; ?>
                        </td>
                        
                        <!-- Antibiotic Stewardship Program -->
                        <td class="<?php echo strpos($report['intervention_choice'], 'addition_new_drug') !== false ? 'intervention-1' : 'intervention-0'; ?>">
                            <?php echo strpos($report['intervention_choice'], 'addition_new_drug') !== false ? '1' : '0'; ?>
                        </td>
                        
                        <!-- High-Alert Medications -->
                        <td class="<?php echo strpos($report['intervention_choice'], 'change_medication') !== false ? 'intervention-1' : 'intervention-0'; ?>">
                            <?php echo strpos($report['intervention_choice'], 'change_medication') !== false ? '1' : '0'; ?>
                        </td>
                        
                        <!-- Similar Drugs (Look-alike/Sound-alike) -->
                        <td class="<?php echo strpos($report['intervention_choice'], 'dose_adjustment') !== false ? 'intervention-1' : 'intervention-0'; ?>">
                            <?php echo strpos($report['intervention_choice'], 'dose_adjustment') !== false ? '1' : '0'; ?>
                        </td>
                        
                        <!-- Medical Error Documentation -->
                        <td class="<?php echo strpos($report['intervention_choice'], 'drug_discontinuation') !== false ? 'intervention-1' : 'intervention-0'; ?>">
                            <?php echo strpos($report['intervention_choice'], 'drug_discontinuation') !== false ? '1' : '0'; ?>
                        </td>
                        
                        <!-- Drug Definition -->
                        <td class="<?php echo !empty($report['corrective_action']) ? 'intervention-1' : 'intervention-0'; ?>">
                            <?php echo !empty($report['corrective_action']) ? '1' : '0'; ?>
                        </td>
                        
                        <!-- Drug Description and Quantity -->
                        <td><?php echo htmlspecialchars($report['antibiotic_name'] ?? 'غير محدد'); ?></td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="10" style="text-align: center; padding: 20px; color: #666;">
                        لا توجد بيانات متاحة للفترة المحددة
                    </td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>

    <!-- Summary Section -->
    <table style="margin-top: 20px;">
        <tr class="sub-header">
            <td colspan="6">ملخص الإحصائيات</td>
        </tr>
        <tr>
            <th>إجمالي التقارير</th>
            <th>التقارير المعلقة</th>
            <th>التقارير المكتملة</th>
            <th>التقارير الملغية</th>
            <th>إجمالي المرضى</th>
            <th>إجمالي التدخلات</th>
        </tr>
        <tr>
            <td><?php echo count($reports); ?></td>
            <td><?php echo count(array_filter($reports, function($r) { return $r['status'] == 'pending'; })); ?></td>
            <td><?php echo count(array_filter($reports, function($r) { return $r['status'] == 'completed'; })); ?></td>
            <td><?php echo count(array_filter($reports, function($r) { return $r['status'] == 'cancelled'; })); ?></td>
            <td><?php echo count(array_unique(array_column($reports, 'patient_name'))); ?></td>
            <td><?php echo count(array_filter($reports, function($r) { return !empty($r['intervention_choice']); })); ?></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'); ?></td></tr>
    </table>
</body>
</html>
