<?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();

// Get parameters
$unit_id = $_GET['unit_id'] ?? null;
$from_date = $_GET['from_date'] ?? date('Y-m-d', strtotime('-7 days'));
$to_date = $_GET['to_date'] ?? date('Y-m-d');
$include_reports = isset($_GET['include_reports']) && $_GET['include_reports'] == '1';
$include_medication_tracking = isset($_GET['include_medication_tracking']) && $_GET['include_medication_tracking'] == '1';

// Get unit information
$unit_name = 'جميع الأقسام';
if ($unit_id) {
    $unit_stmt = $conn->prepare("SELECT unit_name FROM units WHERE id = ?");
    $unit_stmt->execute([$unit_id]);
    $unit_result = $unit_stmt->fetch(PDO::FETCH_ASSOC);
    if ($unit_result) {
        $unit_name = $unit_result['unit_name'];
    }
}

// Build WHERE clause for reports
$where_conditions = ["ar.report_date BETWEEN ? AND ?"];
$params = [$from_date, $to_date];

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

$where_clause = implode(' AND ', $where_conditions);

// Get antibiotic reports data
$reports_data = [];
if ($include_reports) {
    $reports_query = "
        SELECT 
            ar.report_date,
            p.patient_name,
            p.mrn as medical_number,
            COALESCE(a.antibiotic_name, ar.other_medication_name, 'غير محدد') as antibiotic_name,
            ar.problem_authority,
            ar.intervention_choice,
            ar.status,
            u.full_name as pharmacist_name,
            ar.recommendations as notes
        FROM antibiotic_reports ar
        LEFT JOIN patients p ON ar.patient_id = p.id
        LEFT JOIN antibiotics a ON ar.antibiotic_id = a.id
        LEFT JOIN users u ON ar.reporting_pharmacist_id = u.id
        LEFT JOIN units un ON ar.unit_id = un.id
        WHERE $where_clause
        ORDER BY ar.report_date DESC, p.patient_name
    ";
    
    $reports_stmt = $conn->prepare($reports_query);
    $reports_stmt->execute($params);
    $reports_data = $reports_stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Get medication tracking data
$medication_data = [];
if ($include_medication_tracking) {
    $med_where_conditions = ["p.tracking_date BETWEEN ? AND ?"];
    $med_params = [$from_date, $to_date];
    
    if ($unit_id) {
        $med_where_conditions[] = "p.unit_id = ?";
        $med_params[] = $unit_id;
    }
    
    $med_where_clause = implode(' AND ', $med_where_conditions);
    
    $medication_query = "
        SELECT 
            p.tracking_date,
            p.patient_file,
            p.patient_name,
            p.medical_number,
            p.drug_compatibility,
            p.antibiotic_program,
            p.high_risk_drugs,
            p.strict_priority,
            p.error_documentation,
            p.documentation_quality,
            p.medication_description,
            p.pharmacist_name,
            u.unit_name
        FROM patient_medication_tracking p
        LEFT JOIN units u ON p.unit_id = u.id
        WHERE $med_where_clause
        ORDER BY p.tracking_date DESC, p.patient_name
    ";
    
    $med_stmt = $conn->prepare($medication_query);
    $med_stmt->execute($med_params);
    $medication_data = $med_stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Log export activity
logActivity($conn, $_SESSION['user_id'], 'تصدير تقرير موحد للقسم Excel', 'unified_department_export');

// Create Excel file with HTML table
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="unified_department_report_' . $unit_name . '_' . $from_date . '_to_' . $to_date . '.xls"');
header('Cache-Control: max-age=0');
header('Pragma: public');
echo "\xEF\xBB\xBF";
?>
<!DOCTYPE html>
<html dir="rtl">
<head>
    <meta charset="utf-8">
    <title>تقرير موحد للقسم - <?php echo $unit_name; ?></title>
    <style>
        body {
            font-family: Arial, sans-serif;
            direction: rtl;
            font-size: 8pt;
            margin: 0;
            padding: 0;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
            font-size: 7pt;
        }
        
        th, td {
            border: 1px solid #000;
            padding: 3px;
            text-align: center;
            vertical-align: middle;
        }
        
        th {
            background-color: #4472C4;
            color: #ffffff;
            font-weight: bold;
            font-size: 7pt;
        }
        
        tr:nth-child(odd) td { background-color: #ffffff; }
        tr:nth-child(even) td { background-color: #f2f7ff; }
        
        .compact-cell {
            max-width: 60px;
            word-wrap: break-word;
            font-size: 6pt;
        }
        
        .intervention-cell {
            font-weight: bold;
            color: #007bff;
            font-size: 7pt;
        }
        
        .status-pending td { background-color: #fff3cd !important; }
        .status-completed td { background-color: #d4edda !important; }
        .status-cancelled td { background-color: #f8d7da !important; }
    </style>
</head>
<body>
    <!-- Header Table -->
    <table>
        <tr><td colspan="12" style="background-color:#1a3a5c; color:#ffffff; font-size:14pt; font-weight:bold; text-align:center; padding:10px;">تقرير موحد للقسم - <?php echo $unit_name; ?></td></tr>
        <tr><td colspan="12" style="background-color:#2e5c8a; color:#ffffff; font-size:9pt; text-align:center; padding:5px;">الفترة: <?php echo date('d/m/Y', strtotime($from_date)); ?> إلى <?php echo date('d/m/Y', strtotime($to_date)); ?> | تاريخ التصدير: <?php echo date('d/m/Y H:i'); ?> | المستخدم: <?php echo $_SESSION['full_name'] ?? 'غير محدد'; ?></td></tr>
        <tr><td colspan="12" style="height:6px; border:none;"></td></tr>
    </table>

    <?php if ($include_medication_tracking && !empty($medication_data)): ?>
    <table>
        <tr><td colspan="12" style="background-color:#D9E1F2; color:#1F3864; font-weight:bold; font-size:11pt; text-align:right; padding:8px 12px; border:2px solid #4472C4;">جدول متابعة المرضى والأدوية</td></tr>
        <thead>
            <tr>
                <th>التاريخ</th>
                <th>ملف المريض</th>
                <th>اسم المريض</th>
                <th>الرقم الطبي</th>
                <th>توافق الأدوية</th>
                <th>برنامج المضادات</th>
                <th>أدوية عالية الخطورة</th>
                <th>أولوية صارمة</th>
                <th>توثيق الأخطاء</th>
                <th>جودة التوثيق</th>
                <th>وصف الدواء</th>
                <th>الصيدلي</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($medication_data as $row): ?>
            <tr>
                <td class="compact-cell"><?php echo date('d/m/Y', strtotime($row['tracking_date'])); ?></td>
                <td class="compact-cell"><?php echo $row['patient_file'] ?? ''; ?></td>
                <td class="compact-cell"><?php echo $row['patient_name'] ?? ''; ?></td>
                <td class="compact-cell"><?php echo $row['medical_number'] ?? ''; ?></td>
                <td class="intervention-cell"><?php echo $row['drug_compatibility'] ?? 0; ?></td>
                <td class="intervention-cell"><?php echo $row['antibiotic_program'] ?? 0; ?></td>
                <td class="intervention-cell"><?php echo $row['high_risk_drugs'] ?? 0; ?></td>
                <td class="intervention-cell"><?php echo $row['strict_priority'] ?? 0; ?></td>
                <td class="intervention-cell"><?php echo $row['error_documentation'] ?? 0; ?></td>
                <td class="intervention-cell"><?php echo $row['documentation_quality'] ?? 0; ?></td>
                <td class="compact-cell"><?php echo substr($row['medication_description'] ?? '', 0, 30); ?></td>
                <td class="compact-cell"><?php echo $row['pharmacist_name'] ?? ''; ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>

    <?php if ($include_reports && !empty($reports_data)): ?>
    <table>
        <tr><td colspan="9" style="background-color:#D9E1F2; color:#1F3864; font-weight:bold; font-size:11pt; text-align:right; padding:8px 12px; border:2px solid #4472C4;">تقارير المضادات الحيوية</td></tr>
        <thead>
            <tr>
                <th>تاريخ التقرير</th>
                <th>اسم المريض</th>
                <th>الرقم الطبي</th>
                <th>المضاد الحيوي</th>
                <th>سلطة المشكلة</th>
                <th>التدخل</th>
                <th>الحالة</th>
                <th>الصيدلي</th>
                <th>الملاحظات</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($reports_data as $row): ?>
            <tr class="status-<?php echo $row['status']; ?>">
                <td class="compact-cell"><?php echo date('d/m/Y', strtotime($row['report_date'])); ?></td>
                <td class="compact-cell"><?php echo $row['patient_name'] ?? ''; ?></td>
                <td class="compact-cell"><?php echo $row['medical_number'] ?? ''; ?></td>
                <td class="compact-cell"><?php echo $row['antibiotic_name'] ?? ''; ?></td>
                <td class="compact-cell"><?php echo $row['problem_authority'] ?? ''; ?></td>
                <td class="compact-cell"><?php 
                    $interventions = json_decode($row['intervention_choice'] ?? '', true);
                    if (is_array($interventions)) {
                        echo htmlspecialchars(implode(', ', $interventions));
                    } else {
                        echo htmlspecialchars($row['intervention_choice'] ?? '');
                    }
                ?></td>
                <td class="compact-cell">
                    <?php 
                    $status_text = [
                        'pending' => 'معلق',
                        'completed' => 'مكتمل',
                        'cancelled' => 'ملغي'
                    ];
                    echo $status_text[$row['status']] ?? $row['status'];
                    ?>
                </td>
                <td class="compact-cell"><?php echo $row['pharmacist_name'] ?? ''; ?></td>
                <td class="compact-cell"><?php echo substr($row['notes'] ?? '', 0, 50); ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>

    <!-- Summary Statistics -->
    <table style="width:50%; margin:0 auto;">
        <tr><td colspan="2" style="background-color:#D9E1F2; color:#1F3864; font-weight:bold; font-size:11pt; text-align:right; padding:8px 12px; border:2px solid #4472C4;">ملخص إحصائي</td></tr>
        <tr>
            <th>البيان</th>
            <th>العدد</th>
        </tr>
        <?php if ($include_medication_tracking): ?>
        <tr>
            <td>إجمالي سجلات متابعة الأدوية</td>
            <td><?php echo count($medication_data); ?></td>
        </tr>
        <?php endif; ?>
        <?php if ($include_reports): ?>
        <tr>
            <td>إجمالي تقارير المضادات الحيوية</td>
            <td><?php echo count($reports_data); ?></td>
        </tr>
        <?php endif; ?>
        <tr>
            <td>فترة التقرير</td>
            <td><?php echo date('d/m/Y', strtotime($from_date)) . ' - ' . date('d/m/Y', strtotime($to_date)); ?></td>
        </tr>
    </table>

    <!-- Footer Table -->
    <table>
        <tr><td colspan="3" style="background-color:#f2f2f2; text-align:center; padding:8px; font-size:6pt; color:#555; border:1px solid #ccc;">نظام الصيدلة الإكلينيكية المتكامل (ICS) | تم الإنشاء: <?php echo date('d/m/Y H:i'); ?> | القسم: <?php echo $unit_name; ?></td></tr>
    </table>
</body>
</html>

<?php
// Log export in export_logs table
try {
    $export_params = [
        'unit_id' => $unit_id,
        'from_date' => $from_date,
        'to_date' => $to_date,
        'include_reports' => $include_reports,
        'include_medication_tracking' => $include_medication_tracking
    ];
    
    $filename = "unified_department_report_" . $unit_name . "_" . $from_date . "_to_" . $to_date . ".xls";
    
    $log_stmt = $conn->prepare("
        INSERT INTO export_logs (export_type, exported_by, parameters, record_count, file_name) 
        VALUES (?, ?, ?, ?, ?)
    ");
    $log_stmt->execute([
        'unified_department_report',
        $_SESSION['user_id'],
        json_encode($export_params),
        count($medication_data) + count($reports_data),
        $filename
    ]);
} catch (Exception $e) {
    error_log("Export logging error: " . $e->getMessage());
}
?>
