<?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
$from_date = $_GET['from_date'] ?? date('Y-m-d', strtotime('-7 days'));
$to_date = $_GET['to_date'] ?? date('Y-m-d');
$unit_id = $_GET['unit_id'] ?? null;
$pharmacist = $_GET['pharmacist'] ?? null;
$include_statistics = isset($_GET['include_statistics']) && $_GET['include_statistics'] == '1';

// Build query
$where_conditions = ["p.tracking_date BETWEEN ? AND ?"];
$params = [$from_date, $to_date];

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

if ($pharmacist) {
    $where_conditions[] = "p.pharmacist_name LIKE ?";
    $params[] = "%$pharmacist%";
}

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

// Get data
$stmt = $conn->prepare("
    SELECT 
        p.*,
        u.unit_name,
        u.unit_code
    FROM patient_medication_tracking p
    LEFT JOIN units u ON p.unit_id = u.id
    WHERE $where_clause
    ORDER BY p.tracking_date DESC, u.unit_name, p.patient_name
");
$stmt->execute($params);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get units for statistics
$units_stmt = $conn->query("SELECT id, unit_name FROM units WHERE is_active = 1 ORDER BY unit_name");
$units = $units_stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate statistics
$total_patients = count($data);
$total_interventions = 0;
$completed_reports = 0;
$pending_reports = 0;
$advanced_reports = 0;
$follow_up_required = 0;

foreach ($data as $row) {
    $interventions = ($row['drug_compatibility'] ?? 0) + 
                    ($row['antibiotic_program'] ?? 0) + 
                    ($row['high_risk_drugs'] ?? 0) + 
                    ($row['strict_priority'] ?? 0) + 
                    ($row['error_documentation'] ?? 0) + 
                    ($row['documentation_quality'] ?? 0);
    
    $total_interventions += $interventions;
    
    if ($interventions > 0) {
        $completed_reports++;
    } else {
        $pending_reports++;
    }
    
    if (($row['documentation_quality'] ?? 0) > 0) {
        $advanced_reports++;
    }
    
    if (($row['high_risk_drugs'] ?? 0) > 0 || ($row['error_documentation'] ?? 0) > 0) {
        $follow_up_required++;
    }
}

// Buffer output to prevent any accidental output before headers
ob_start();

// Create Excel file with HTML table
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="patient_medication_tracking_' . $from_date . '_to_' . $to_date . '.xls"');
header('Cache-Control: max-age=0');
header('Pragma: public');

// Discard any buffered output that might corrupt the file
ob_end_clean();

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;
            font-size: 8pt;
        }
        table {
            border-collapse: collapse;
            width: 100%;
            font-family: 'Arial', 'Tahoma', sans-serif;
        }
        .main-table th {
            border: 1px solid #000;
            padding: 3px 2px;
            text-align: center;
            font-weight: bold;
            background-color: #4472C4;
            color: #ffffff;
            vertical-align: middle;
            font-size: 6pt;
            line-height: 1.1;
        }
        .main-table td {
            border: 1px solid #000;
            padding: 2px 1px;
            text-align: center;
            vertical-align: middle;
            font-size: 7pt;
        }
        .main-table tr:nth-child(odd) td {
            background-color: #ffffff;
        }
        .main-table tr:nth-child(even) td {
            background-color: #f2f7ff;
        }
        .date-header {
            writing-mode: vertical-rl;
            text-orientation: mixed;
            width: 30px;
            font-size: 6pt;
        }
        .intervention-cell {
            font-weight: bold;
            color: #007bff;
            font-size: 7pt;
        }
        .compact-cell {
            max-width: 50px;
            word-wrap: break-word;
            font-size: 6pt;
        }
        .stats-row td {
            background-color: #e2e3e5;
            font-weight: bold;
            font-size: 6pt;
        }
        .stats-values td {
            background-color: #f8f9fa;
            font-weight: bold;
            color: #007bff;
            font-size: 7pt;
        }
    </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;">إجراءات التدخل وإدارة الأخطاء المهنية فيما يتعلق بالأدوية</td></tr>
        <tr><td colspan="10" 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 if ($unit_id): $unit_name = ''; foreach ($units as $unit) { if ($unit['id'] == $unit_id) { $unit_name = $unit['unit_name']; break; } } echo ' | القسم: ' . $unit_name; endif; ?> | تاريخ التصدير: <?php echo date('d/m/Y H:i'); ?></td></tr>
        <tr><td colspan="10" style="height:6px; border:none;"></td></tr>
    </table>

    <!-- Main Table -->
    <table class="main-table">
        <thead>
            <tr>
                <th rowspan="2" class="date-header">تاريخ</th>
                <th rowspan="2" class="compact-cell">اسم المريض</th>
                <th rowspan="2" class="compact-cell">الرقم الطبي</th>
                <th colspan="6">إجراءات التدخل وإدارة الأخطاء المهنية فيما يتعلق بالأدوية</th>
                <th rowspan="2" class="compact-cell">وصف الدواء</th>
            </tr>
            <tr>
                <th style="background-color:#4472C4; color:#ffffff; font-size:5pt; padding:2px 1px; max-width:60px; word-wrap:break-word; line-height:1.0;">توافق الأدوية</th>
                <th style="background-color:#4472C4; color:#ffffff; font-size:5pt; padding:2px 1px; max-width:60px; word-wrap:break-word; line-height:1.0;">برنامج المضادات</th>
                <th style="background-color:#4472C4; color:#ffffff; font-size:5pt; padding:2px 1px; max-width:60px; word-wrap:break-word; line-height:1.0;">أدوية خطرة</th>
                <th style="background-color:#4472C4; color:#ffffff; font-size:5pt; padding:2px 1px; max-width:60px; word-wrap:break-word; line-height:1.0;">أولوية متشددة</th>
                <th style="background-color:#4472C4; color:#ffffff; font-size:5pt; padding:2px 1px; max-width:60px; word-wrap:break-word; line-height:1.0;">توثيق أخطاء</th>
                <th style="background-color:#4472C4; color:#ffffff; font-size:5pt; padding:2px 1px; max-width:60px; word-wrap:break-word; line-height:1.0;">تحسين توثيق</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($data)): ?>
            <tr>
                <td colspan="10" style="text-align:center; padding:20px; color:#6c757d;">
                    لا توجد بيانات في هذا النطاق الزمني
                </td>
            </tr>
            <?php else: ?>
            <?php foreach ($data as $row): ?>
            <tr>
                <td class="compact-cell"><?php echo date('d/m', strtotime($row['tracking_date'])); ?></td>
                <td class="compact-cell"><?php echo substr($row['patient_name'] ?? '', 0, 15); ?></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, 20); ?></td>
            </tr>
            <?php endforeach; ?>
            
            <?php if ($include_statistics): ?>
            <tr class="stats-row">
                <td colspan="10" style="text-align:center; font-size:8pt;">الإحصائيات</td>
            </tr>
            <tr class="stats-row">
                <td>التدخلات</td>
                <td>المرضى</td>
                <td>معلقة</td>
                <td>مكتملة</td>
                <td>متقدمة</td>
                <td>متابعة</td>
                <td colspan="5">المجموع</td>
            </tr>
            <tr class="stats-values">
                <td><?php echo $total_interventions; ?></td>
                <td><?php echo $total_patients; ?></td>
                <td><?php echo $pending_reports; ?></td>
                <td><?php echo $completed_reports; ?></td>
                <td><?php echo $advanced_reports; ?></td>
                <td><?php echo $follow_up_required; ?></td>
                <td colspan="5"><?php echo $total_interventions; ?></td>
            </tr>
            <?php endif; ?>
            <?php endif; ?>
        </tbody>
    </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 count($data); ?></td></tr>
    </table>
</body>
</html>

<?php
// Log export activity
logActivity($conn, $_SESSION['user_id'], 'تصدير جدول متابعة المرضى والأدوية Excel', 'patient_medication_tracking');

// Log export in export_logs table
try {
    $export_params = [
        'from_date' => $from_date,
        'to_date' => $to_date,
        'unit_id' => $unit_id,
        'pharmacist' => $pharmacist,
        'include_statistics' => $include_statistics
    ];
    
    $filename = "patient_medication_tracking_" . $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([
        'patient_medication_tracking',
        $_SESSION['user_id'],
        json_encode($export_params),
        count($data),
        $filename
    ]);
} catch (Exception $e) {
    error_log("Export logging error: " . $e->getMessage());
}
?>
