<?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('غير مصرح لك بالوصول');
}

$database = new Database();
$pdo = $database->getConnection();

// Get parameters (same as main page)
$filter_date = $_GET['filter_date'] ?? date('Y-m-d');
$filter_month = $_GET['filter_month'] ?? date('Y-m');
$filter_year = $_GET['filter_year'] ?? date('Y');
$filter_shift = $_GET['filter_shift'] ?? '';
$filter_user = $_GET['filter_user'] ?? '';
$view_type = $_GET['view_type'] ?? 'daily';

// Build date condition and parameters
$date_condition = "";
$params = [];

switch ($view_type) {
    case 'daily':
        $date_condition = "DATE(p.created_at) = ?";
        $params[] = $filter_date;
        $period_text = date('d/m/Y', strtotime($filter_date));
        break;
    case 'monthly':
        $date_condition = "DATE_FORMAT(p.created_at, '%Y-%m') = ?";
        $params[] = $filter_month;
        $period_text = date('m/Y', strtotime($filter_month . '-01'));
        break;
    case 'yearly':
        $date_condition = "YEAR(p.created_at) = ?";
        $params[] = $filter_year;
        $period_text = $filter_year;
        break;
}

// Add user filter
$user_condition = "";
if ($filter_user) {
    $user_condition = " AND p.created_by = ?";
    $params[] = $filter_user;
}

// Get user name for filtering
$user_name = 'جميع المستخدمين';
if ($filter_user) {
    $user_stmt = $pdo->prepare("SELECT full_name FROM users WHERE id = ?");
    $user_stmt->execute([$filter_user]);
    $user_result = $user_stmt->fetch(PDO::FETCH_ASSOC);
    if ($user_result) {
        $user_name = $user_result['full_name'];
    }
}

// Get all data using same queries as main page
// 1. Patients Data
$patients_query = "
    SELECT 
        p.id,
        p.patient_name,
        p.mrn,
        p.gender,
        p.created_at,
        u.full_name as created_by_name
    FROM patients p
    LEFT JOIN users u ON p.created_by = u.id
    WHERE $date_condition $user_condition
    ORDER BY p.created_at DESC
";
$patients_stmt = $pdo->prepare($patients_query);
$patients_stmt->execute($params);
$patients_data = $patients_stmt->fetchAll(PDO::FETCH_ASSOC);

// 2. Antibiotic Reports
$reports_date_condition = str_replace('p.created_at', 'ar.created_at', $date_condition);
$reports_user_condition = str_replace('p.created_by', 'ar.reporting_pharmacist_id', $user_condition);
$reports_query = "
    SELECT 
        ar.id,
        ar.report_date,
        p.patient_name,
        COALESCE(a.antibiotic_name, ar.other_medication_name, 'غير محدد') as antibiotic_name,
        ar.status,
        ar.created_at,
        u.full_name as created_by_name,
        un.unit_name
    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 $reports_date_condition $reports_user_condition
    ORDER BY ar.created_at DESC
";
$reports_stmt = $pdo->prepare($reports_query);
$reports_stmt->execute($params);
$reports_data = $reports_stmt->fetchAll(PDO::FETCH_ASSOC);

// 3. Medication Tracking
$medication_date_condition = str_replace('p.created_at', 'pmt.created_at', $date_condition);
$medication_user_condition = str_replace('p.created_by', 'pmt.created_by', $user_condition);
$medication_query = "
    SELECT 
        pmt.id,
        pmt.tracking_date,
        pmt.patient_name,
        pmt.medical_number,
        pmt.drug_compatibility,
        pmt.antibiotic_program,
        pmt.high_risk_drugs,
        pmt.created_at,
        u.full_name as created_by_name,
        un.unit_name
    FROM patient_medication_tracking pmt
    LEFT JOIN users u ON pmt.created_by = u.id
    LEFT JOIN units un ON pmt.unit_id = un.id
    WHERE $medication_date_condition $medication_user_condition
    ORDER BY pmt.created_at DESC
";
$medication_stmt = $pdo->prepare($medication_query);
$medication_stmt->execute($params);
$medication_data = $medication_stmt->fetchAll(PDO::FETCH_ASSOC);

// 4. Activity Log
$activity_date_condition = str_replace('p.created_at', 'a.created_at', $date_condition);
$activity_user_condition = str_replace('p.created_by', 'a.user_id', $user_condition);
$activity_query = "
    SELECT 
        a.id,
        a.action,
        a.table_name,
        a.created_at,
        u.full_name as user_name
    FROM activity_log a
    LEFT JOIN users u ON a.user_id = u.id
    WHERE $activity_date_condition $activity_user_condition
    ORDER BY a.created_at DESC
    LIMIT 200
";
$activity_stmt = $pdo->prepare($activity_query);
$activity_stmt->execute($params);
$activity_data = $activity_stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate statistics
$total_patients = count($patients_data);
$total_reports = count($reports_data);
$total_medication_records = count($medication_data);
$total_activities = count($activity_data);

// Log export activity
logActivity($pdo, $_SESSION['user_id'], 'تصدير تقرير فريق العمليات Excel', 'operations_team_report');

// Create Excel file
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="operations_team_report_' . $view_type . '_' . date('Y-m-d') . '.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>تقرير فريق العمليات</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            direction: rtl;
            font-size: 8pt;
            margin: 0;
            padding: 0;
        }
        
        .section-title {
            background-color: #4472C4;
            color: white;
            font-weight: bold;
            font-size: 12pt;
            padding: 10px;
            text-align: center;
            margin: 20px 0 0 0;
            page-break-before: always;
        }
        
        .stats-section {
            background-color: #f8f9fa;
            padding: 15px;
            margin: 15px 0;
            border: 2px solid #007bff;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
            font-size: 7pt;
        }
        
        th, td {
            border: 1px solid #000;
            padding: 4px;
            text-align: center;
            vertical-align: middle;
        }
        
        th {
            background-color: #4472C4;
            color: #ffffff;
            font-weight: bold;
            font-size: 8pt;
        }
        
        tr:nth-child(odd) td { background-color: #ffffff; }
        tr:nth-child(even) td { background-color: #f2f7ff; }
        
        .compact-cell {
            max-width: 80px;
            word-wrap: break-word;
            font-size: 7pt;
        }
        
        .status-completed td { background-color: #d4edda !important; }
        .status-pending td { background-color: #fff3cd !important; }
        .status-cancelled td { background-color: #f8d7da !important; }
        
        .page-break {
            page-break-before: always;
        }
    </style>
</head>
<body>
    <!-- Header Table -->
    <?php
    $view_types = [
        'daily' => 'يومي',
        'monthly' => 'شهري', 
        'yearly' => 'سنوي'
    ];
    ?>
    <table>
        <tr><td colspan="8" style="background-color:#1a3a5c; color:#ffffff; font-size:16pt; font-weight:bold; text-align:center; padding:12px;">تقرير فريق العمليات - نظام الصيدلة الإكلينيكية المتكامل (ICS)</td></tr>
        <tr><td colspan="8" style="background-color:#2e5c8a; color:#ffffff; font-size:10pt; text-align:center; padding:5px;">نوع التقرير: <?php echo $view_types[$view_type]; ?> | الفترة: <?php echo $period_text; ?> | المستخدم: <?php echo $user_name; ?> | تاريخ التصدير: <?php echo date('d/m/Y H:i'); ?> | صدر بواسطة: <?php echo $_SESSION['full_name'] ?? 'غير محدد'; ?></td></tr>
        <tr><td colspan="8" style="height:8px; border:none;"></td></tr>
    </table>

    <!-- Statistics Summary -->
    <table style="width:80%; margin:0 auto 20px auto;">
        <tr><td colspan="2" 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>
            </tr>
            <tr>
                <td>إجمالي المرضى المضافين</td>
                <td><?php echo $total_patients; ?></td>
            </tr>
            <tr>
                <td>تقارير المضادات الحيوية</td>
                <td><?php echo $total_reports; ?></td>
            </tr>
            <tr>
                <td>سجلات متابعة الأدوية</td>
                <td><?php echo $total_medication_records; ?></td>
            </tr>
            <tr>
                <td>إجمالي الأنشطة</td>
                <td><?php echo $total_activities; ?></td>
            </tr>
        </table>

    <!-- Patients Data -->
    <?php if (!empty($patients_data)): ?>
    <table>
        <tr><td colspan="7" style="background-color:#D9E1F2; color:#1F3864; font-weight:bold; font-size:12pt; text-align:right; padding:8px 12px; border:2px solid #4472C4;">1. المرضى المضافين (<?php echo count($patients_data); ?>)</td></tr>
        <thead>
            <tr>
                <th>م</th>
                <th>اسم المريض</th>
                <th>الرقم الطبي</th>
                <th>الجنس</th>
                <th>العمر</th>
                <th>تاريخ الإضافة</th>
                <th>أضيف بواسطة</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($patients_data as $index => $patient): ?>
            <tr>
                <td><?php echo $index + 1; ?></td>
                <td class="compact-cell"><?php echo htmlspecialchars($patient['patient_name']); ?></td>
                <td class="compact-cell"><?php echo htmlspecialchars($patient['mrn']); ?></td>
                <td><?php echo $patient['gender'] == 'male' ? 'ذكر' : 'أنثى'; ?></td>
                <td>-</td>
                <td><?php echo date('d/m/Y H:i', strtotime($patient['created_at'])); ?></td>
                <td class="compact-cell"><?php echo htmlspecialchars($patient['created_by_name']); ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>

    <!-- Antibiotic Reports -->
    <?php if (!empty($reports_data)): ?>
    <table>
        <tr><td colspan="8" style="background-color:#D9E1F2; color:#1F3864; font-weight:bold; font-size:12pt; text-align:right; padding:8px 12px; border:2px solid #4472C4;">2. تقارير المضادات الحيوية (<?php echo count($reports_data); ?>)</td></tr>
        <thead>
            <tr>
                <th>م</th>
                <th>تاريخ التقرير</th>
                <th>اسم المريض</th>
                <th>المضاد الحيوي</th>
                <th>الحالة</th>
                <th>القسم</th>
                <th>تاريخ الإنشاء</th>
                <th>أنشأ بواسطة</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($reports_data as $index => $report): ?>
            <tr class="status-<?php echo $report['status']; ?>">
                <td><?php echo $index + 1; ?></td>
                <td><?php echo date('d/m/Y', strtotime($report['report_date'])); ?></td>
                <td class="compact-cell"><?php echo htmlspecialchars($report['patient_name']); ?></td>
                <td class="compact-cell"><?php echo htmlspecialchars($report['antibiotic_name']); ?></td>
                <td>
                    <?php 
                    $status_text = [
                        'pending' => 'معلق',
                        'completed' => 'مكتمل',
                        'cancelled' => 'ملغي'
                    ];
                    echo $status_text[$report['status']] ?? $report['status'];
                    ?>
                </td>
                <td class="compact-cell"><?php echo htmlspecialchars($report['unit_name']); ?></td>
                <td><?php echo date('d/m/Y H:i', strtotime($report['created_at'])); ?></td>
                <td class="compact-cell"><?php echo htmlspecialchars($report['created_by_name']); ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>

    <!-- Medication Tracking -->
    <?php if (!empty($medication_data)): ?>
    <table>
        <tr><td colspan="9" style="background-color:#D9E1F2; color:#1F3864; font-weight:bold; font-size:12pt; text-align:right; padding:8px 12px; border:2px solid #4472C4;">3. متابعة المرضى والأدوية (<?php echo count($medication_data); ?>)</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 ($medication_data as $index => $med): ?>
            <tr>
                <td><?php echo $index + 1; ?></td>
                <td><?php echo date('d/m/Y', strtotime($med['tracking_date'])); ?></td>
                <td class="compact-cell"><?php echo htmlspecialchars($med['patient_name']); ?></td>
                <td class="compact-cell"><?php echo htmlspecialchars($med['medical_number']); ?></td>
                <td><?php echo $med['drug_compatibility']; ?></td>
                <td><?php echo $med['antibiotic_program']; ?></td>
                <td><?php echo $med['high_risk_drugs']; ?></td>
                <td class="compact-cell"><?php echo htmlspecialchars($med['unit_name']); ?></td>
                <td class="compact-cell"><?php echo htmlspecialchars($med['created_by_name']); ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>

    <!-- Activity Log -->
    <?php if (!empty($activity_data)): ?>
    <table>
        <tr><td colspan="5" style="background-color:#D9E1F2; color:#1F3864; font-weight:bold; font-size:12pt; text-align:right; padding:8px 12px; border:2px solid #4472C4;">4. سجل النشاط (آخر 200 عملية)</td></tr>
        <thead>
            <tr>
                <th>م</th>
                <th>العملية</th>
                <th>الجدول</th>
                <th>المستخدم</th>
                <th>التاريخ والوقت</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($activity_data as $index => $activity): ?>
            <tr>
                <td><?php echo $index + 1; ?></td>
                <td class="compact-cell"><?php echo htmlspecialchars($activity['action']); ?></td>
                <td class="compact-cell"><?php echo htmlspecialchars($activity['table_name']); ?></td>
                <td class="compact-cell"><?php echo htmlspecialchars($activity['user_name']); ?></td>
                <td><?php echo date('d/m/Y H:i:s', strtotime($activity['created_at'])); ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>

    <!-- 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('d/m/Y H:i'); ?> | صدر بواسطة: <?php echo $_SESSION['full_name'] ?? 'غير محدد'; ?> | الفترة: <?php echo $period_text; ?> | المستخدم: <?php echo $user_name; ?> | إجمالي السجلات: <?php echo $total_patients + $total_reports + $total_medication_records + $total_activities; ?></td></tr>
    </table>
</body>
</html>

<?php
// Log export in export_logs table
try {
    $export_params = [
        'view_type' => $view_type,
        'filter_date' => $filter_date,
        'filter_month' => $filter_month,
        'filter_year' => $filter_year,
        'filter_user' => $filter_user
    ];
    
    $total_records = $total_patients + $total_reports + $total_medication_records + $total_activities;
    $filename = "operations_team_report_" . $view_type . "_" . date('Y-m-d') . ".xls";
    
    $log_stmt = $pdo->prepare("
        INSERT INTO export_logs (export_type, exported_by, parameters, record_count, file_name) 
        VALUES (?, ?, ?, ?, ?)
    ");
    $log_stmt->execute([
        'operations_team_report',
        $_SESSION['user_id'],
        json_encode($export_params),
        $total_records,
        $filename
    ]);
} catch (Exception $e) {
    error_log("Export logging error: " . $e->getMessage());
}
?>
