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

// Get search parameters from GET or POST
$search_type = $_REQUEST['search_type'] ?? '';
$search_query = $_REQUEST['search_query'] ?? '';
$date_from = $_REQUEST['date_from'] ?? '';
$date_to = $_REQUEST['date_to'] ?? '';
$unit_id = $_REQUEST['unit_id'] ?? '';
$status = $_REQUEST['status'] ?? '';

// Build query based on search parameters
$where_conditions = [];
$params = [];

if (!empty($search_query)) {
    if ($search_type == 'patient_name') {
        $where_conditions[] = "p.patient_name LIKE ?";
        $params[] = "%$search_query%";
    } elseif ($search_type == 'mrn') {
        $where_conditions[] = "p.mrn LIKE ?";
        $params[] = "%$search_query%";
    } elseif ($search_type == 'antibiotic') {
        $where_conditions[] = "a.antibiotic_name LIKE ?";
        $params[] = "%$search_query%";
    }
}

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($unit_id)) {
    $where_conditions[] = "ar.unit_id = ?";
    $params[] = $unit_id;
}

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

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

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

// Create Excel file with HTML table
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="search_results_' . 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;
        }
        .status-completed {
            background-color: #d1e7dd;
            color: #0f5132;
            font-weight: bold;
            padding: 4px 8px;
        }
        .status-pending {
            background-color: #fff3cd;
            color: #664d03;
            font-weight: bold;
            padding: 4px 8px;
        }
    </style>
</head>
<body>
    <!-- Header Table -->
    <table>
        <tr><td colspan="11" style="background-color:#1a3a5c; color:#ffffff; font-size:16pt; font-weight:bold; text-align:center; padding:12px;">نتائج البحث - تقارير المضادات الحيوية</td></tr>
        <tr><td colspan="11" 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'); ?><?php if (!empty($search_query)): ?> | البحث عن: <?php echo htmlspecialchars($search_query); ?><?php endif; ?></td></tr>
        <tr><td colspan="11" 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:80px;">رقم التقرير</th>
                <th style="background-color:#4472C4; color:#ffffff; font-weight:bold; padding:10px; border:1px solid #2e5c8a; width:120px;">التاريخ</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;">رقم الملف</th>
                <th style="background-color:#4472C4; color:#ffffff; font-weight:bold; padding:10px; border:1px solid #2e5c8a; width:150px;">القسم</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:140px;">سلطة المشكلة</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:110px;">الحالة</th>
                <th style="background-color:#4472C4; color:#ffffff; font-weight:bold; padding:10px; border:1px solid #2e5c8a; width:150px;">الصيدلي</th>
                <th style="background-color:#4472C4; color:#ffffff; font-weight:bold; padding:10px; border:1px solid #2e5c8a; width:160px;">تاريخ الإنشاء</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($data)): ?>
                <tr>
                    <td colspan="11" style="text-align:center; padding:30px;">لا توجد نتائج</td>
                </tr>
            <?php else: ?>
                <?php foreach ($data as $row): ?>
                <tr>
                    <td><?php echo htmlspecialchars($row['id']); ?></td>
                    <td><?php echo htmlspecialchars($row['report_date']); ?></td>
                    <td style="text-align:right;"><?php echo htmlspecialchars($row['patient_name']); ?></td>
                    <td><?php echo htmlspecialchars($row['mrn']); ?></td>
                    <td><?php echo htmlspecialchars($row['unit_name']); ?></td>
                    <td style="text-align:right;"><?php echo htmlspecialchars($row['antibiotic_name']); ?></td>
                    <td><?php echo htmlspecialchars(translateProblemAuthority($row['problem_authority'])); ?></td>
                    <td style="text-align:right;"><?php 
                        $interventions = json_decode($row['intervention_choice'], true);
                        if (is_array($interventions)) {
                            $translations = [
                                'drug_discontinuation' => 'إيقاف الدواء',
                                'monitoring' => 'المراقبة',
                                'changing_another_agent' => 'تغيير إلى دواء آخر',
                                'changing_administration_route' => 'تغيير طريقة الإعطاء',
                                'addition_new_drug' => 'إضافة دواء جديد'
                            ];
                            $translated = array_map(function($item) use ($translations) {
                                return $translations[$item] ?? $item;
                            }, $interventions);
                            echo htmlspecialchars(implode(', ', $translated));
                        } else {
                            echo htmlspecialchars($row['intervention_choice'] ?? '-');
                        }
                    ?></td>
                    <td><?php echo $row['status'] == 'completed' ? 'مكتمل' : 'معلق'; ?></td>
                    <td style="text-align:right;"><?php echo htmlspecialchars($row['pharmacist_name']); ?></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;">إجمالي النتائج: <?php echo count($data); ?> | نظام الصيدلة الإكلينيكية المتكامل (ICS) - مستشفى مدينة نصر التخصصي | تم التصدير بواسطة: <?php echo htmlspecialchars($_SESSION['full_name']); ?> | التاريخ: <?php echo date('Y-m-d h:i A'); ?></td></tr>
    </table>
</body>
</html>
