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

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

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

// Get statistics
try {
    // Initialize variables with default values
    $total_patients = 0;
    $total_reports = 0;
    $total_antibiotics = 0;
    $active_antibiotics = 0;
    $total_users = 0;
    $reports_by_department = [];
    $reports_by_priority = [];
    $most_active_users = [];
    $monthly_trend = [];
    $antibiotic_usage = [];
    
    // Total patients
    $stmt = $conn->query("SELECT COUNT(*) as total FROM patients");
    if ($stmt) {
        $result = $stmt->fetch();
        $total_patients = $result ? $result['total'] : 0;
    }
    
    // Total reports
    $stmt = $conn->query("SELECT COUNT(*) as total FROM antibiotic_reports");
    if ($stmt) {
        $result = $stmt->fetch();
        $total_reports = $result ? $result['total'] : 0;
    }
    
    // Total antibiotics
    $stmt = $conn->query("SELECT COUNT(*) as total FROM antibiotics");
    if ($stmt) {
        $result = $stmt->fetch();
        $total_antibiotics = $result ? $result['total'] : 0;
    }
    
    // Active antibiotics
    $stmt = $conn->query("SELECT COUNT(*) as total FROM antibiotics WHERE is_active = 1");
    if ($stmt) {
        $result = $stmt->fetch();
        $active_antibiotics = $result ? $result['total'] : 0;
    }
    
    // Total users
    $stmt = $conn->query("SELECT COUNT(*) as total FROM users WHERE is_active = 1");
    if ($stmt) {
        $result = $stmt->fetch();
        $total_users = $result ? $result['total'] : 0;
    }
    
    // Reports by department - using units table
    $stmt = $conn->query("
        SELECT 
            u.unit_name as department, 
            COUNT(ar.id) as count 
        FROM antibiotic_reports ar
        LEFT JOIN units u ON ar.unit_id = u.id
        GROUP BY u.unit_name 
        ORDER BY count DESC 
        LIMIT 10
    ");
    if ($stmt) {
        $reports_by_department = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
    
    // Reports by priority - using status instead
    $stmt = $conn->query("
        SELECT 
            CASE 
                WHEN status = 'pending' THEN '" . __('pending') . "'
                WHEN status = 'completed' THEN '" . __('completed') . "'
                WHEN status = 'cancelled' THEN '" . __('cancelled') . "'
                ELSE '" . __('unknown_priority') . "'
            END as priority_ar,
            COALESCE(status, 'unknown') as priority,
            COUNT(*) as count,
            ROUND((COUNT(*) * 100.0 / GREATEST((SELECT COUNT(*) FROM antibiotic_reports), 1)), 1) as percentage
        FROM antibiotic_reports 
        GROUP BY status
    ");
    if ($stmt) {
        $reports_by_priority = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
    
    // Most active users
    $stmt = $conn->query("
        SELECT u.full_name, u.role, COUNT(al.id) as activity_count
        FROM users u
        LEFT JOIN activity_log al ON u.id = al.user_id
        WHERE u.is_active = 1
        GROUP BY u.id, u.full_name, u.role
        ORDER BY activity_count DESC
        LIMIT 5
    ");
    if ($stmt) {
        $most_active_users = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
    
    // Monthly reports trend
    $stmt = $conn->query("
        SELECT 
            DATE_FORMAT(created_at, '%Y-%m') as month,
            COUNT(*) as count
        FROM antibiotic_reports 
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
        GROUP BY DATE_FORMAT(created_at, '%Y-%m')
        ORDER BY month
    ");
    if ($stmt) {
        $monthly_trend = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
    
    // Antibiotic usage statistics
    $stmt = $conn->query("
        SELECT 
            a.antibiotic_name,
            COUNT(ar.id) as usage_count,
            0 as avg_dosage
        FROM antibiotic_reports ar
        LEFT JOIN antibiotics a ON ar.antibiotic_id = a.id
        WHERE a.antibiotic_name IS NOT NULL
        GROUP BY a.antibiotic_name
        ORDER BY usage_count DESC
        LIMIT 10
    ");
    if ($stmt) {
        $antibiotic_usage = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
    
} catch (PDOException $e) {
    $error = "خطأ في قاعدة البيانات: " . $e->getMessage();
    // Initialize with default values in case of error
    $total_patients = 0;
    $total_reports = 0;
    $total_antibiotics = 0;
    $active_antibiotics = 0;
    $total_users = 0;
    $reports_by_department = [];
    $reports_by_priority = [];
    $most_active_users = [];
    $monthly_trend = [];
    $antibiotic_usage = [];
}

include 'includes/header.php';
?>


    <!-- Header -->
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom no-print">
        <div>
            <h1 class="h3 mb-0">
                <i class="fas fa-chart-bar me-2"></i>
                <?php echo __('system_reports_statistics'); ?>
            </h1>
            <p class="text-muted mb-0"><?php echo __('comprehensive_system_overview'); ?></p>
        </div>
        <div class="btn-toolbar mb-2 mb-md-0">
            <div class="btn-group me-2">
                <button type="button" class="btn btn-outline-secondary" onclick="window.print()">
                    <i class="fas fa-print"></i> <?php echo __('print_report'); ?>
                </button>
                <button type="button" class="btn btn-outline-primary" onclick="exportToExcel()">
                    <i class="fas fa-file-excel"></i> <?php echo __('export_excel'); ?>
                </button>
            </div>
        </div>
    </div>

            <?php if (isset($error)): ?>
                <div class="alert alert-danger" role="alert">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <?php echo $error; ?>
                </div>
            <?php endif; ?>

            <!-- Advanced Filters Section -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-transparent border-0">
                    <h5 class="card-title mb-0">
                        <i class="fas fa-filter me-2 text-primary"></i>
                        <?php echo __('advanced_search'); ?>
                    </h5>
                </div>
                <div class="card-body">
                    <form id="filtersForm" method="GET">
                        <div class="row g-3">
                            <!-- Date Range -->
                            <div class="col-md-3">
                                <label class="form-label"><?php echo __('from_date'); ?></label>
                                <input type="date" class="form-control" name="date_from" id="date_from" 
                                       value="<?php echo $_GET['date_from'] ?? ''; ?>">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label"><?php echo __('to_date'); ?></label>
                                <input type="date" class="form-control" name="date_to" id="date_to" 
                                       value="<?php echo $_GET['date_to'] ?? ''; ?>">
                            </div>
                            
                            <!-- Department Filter -->
                            <div class="col-md-3">
                                <label class="form-label"><?php echo __('unit'); ?></label>
                                <select class="form-select" name="department" id="department">
                                    <option value=""><?php echo __('all_departments'); ?></option>
                                    <?php
                                    try {
                                        $stmt = $conn->query("SELECT id, unit_name FROM units WHERE is_active = 1 ORDER BY unit_name");
                                        while ($unit = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                            $selected = (isset($_GET['department']) && $_GET['department'] == $unit['id']) ? 'selected' : '';
                                            echo '<option value="' . $unit['id'] . '" ' . $selected . '>' . htmlspecialchars($unit['unit_name']) . '</option>';
                                        }
                                    } catch (Exception $e) {
                                        // Handle error silently
                                    }
                                    ?>
                                </select>
                            </div>
                            
                            <!-- Status Filter -->
                            <div class="col-md-3">
                                <label class="form-label"><?php echo __('status'); ?></label>
                                <select class="form-select" name="status" id="status">
                                    <option value=""><?php echo __('all_status'); ?></option>
                                    <option value="pending" <?php echo (isset($_GET['status']) && $_GET['status'] == 'pending') ? 'selected' : ''; ?>>
                                        <?php echo __('pending'); ?>
                                    </option>
                                    <option value="completed" <?php echo (isset($_GET['status']) && $_GET['status'] == 'completed') ? 'selected' : ''; ?>>
                                        <?php echo __('completed'); ?>
                                    </option>
                                    <option value="cancelled" <?php echo (isset($_GET['status']) && $_GET['status'] == 'cancelled') ? 'selected' : ''; ?>>
                                        <?php echo __('cancelled'); ?>
                                    </option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="row g-3 mt-2">
                            <!-- Antibiotic Filter -->
                            <div class="col-md-3">
                                <label class="form-label"><?php echo __('antibiotic'); ?></label>
                                <select class="form-select" name="antibiotic" id="antibiotic">
                                    <option value=""><?php echo __('all_antibiotics'); ?></option>
                                    <?php
                                    try {
                                        $stmt = $conn->query("SELECT id, antibiotic_name FROM antibiotics WHERE is_active = 1 ORDER BY antibiotic_name");
                                        while ($antibiotic = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                            $selected = (isset($_GET['antibiotic']) && $_GET['antibiotic'] == $antibiotic['id']) ? 'selected' : '';
                                            echo '<option value="' . $antibiotic['id'] . '" ' . $selected . '>' . htmlspecialchars($antibiotic['antibiotic_name']) . '</option>';
                                        }
                                    } catch (Exception $e) {
                                        // Handle error silently
                                    }
                                    ?>
                                </select>
                            </div>
                            
                            <!-- Pharmacist Filter -->
                            <div class="col-md-3">
                                <label class="form-label"><?php echo __('pharmacist'); ?></label>
                                <select class="form-select" name="pharmacist" id="pharmacist">
                                    <option value=""><?php echo __('all_pharmacists'); ?></option>
                                    <?php
                                    try {
                                        $stmt = $conn->query("SELECT id, full_name FROM users WHERE role IN ('pharmacist', 'admin') AND is_active = 1 ORDER BY full_name");
                                        while ($user = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                            $selected = (isset($_GET['pharmacist']) && $_GET['pharmacist'] == $user['id']) ? 'selected' : '';
                                            echo '<option value="' . $user['id'] . '" ' . $selected . '>' . htmlspecialchars($user['full_name']) . '</option>';
                                        }
                                    } catch (Exception $e) {
                                        // Handle error silently
                                    }
                                    ?>
                                </select>
                            </div>
                            
                            <!-- Quick Date Filters -->
                            <div class="col-md-3">
                                <label class="form-label"><?php echo __('quick_periods'); ?></label>
                                <select class="form-select" id="quick_period" onchange="setQuickPeriod()">
                                    <option value=""><?php echo __('select_period'); ?></option>
                                    <option value="today"><?php echo __('today'); ?></option>
                                    <option value="week"><?php echo __('this_week'); ?></option>
                                    <option value="month"><?php echo __('this_month'); ?></option>
                                    <option value="quarter"><?php echo __('this_quarter'); ?></option>
                                    <option value="year"><?php echo __('this_year'); ?></option>
                                </select>
                            </div>
                            
                            <!-- Action Buttons -->
                            <div class="col-md-3 d-flex align-items-end">
                                <div class="btn-group w-100" role="group">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-search"></i> <?php echo __('search'); ?>
                                    </button>
                                    <button type="button" class="btn btn-outline-secondary" onclick="resetFilters()">
                                        <i class="fas fa-undo"></i> <?php echo __('reset'); ?>
                                    </button>
                                    <button type="button" class="btn btn-outline-success" onclick="exportFiltered()">
                                        <i class="fas fa-download"></i> <?php echo __('export'); ?>
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Department Specific Export -->
                        <div class="row mt-3" id="departmentExportRow" style="display: none;">
                            <div class="col-12">
                                <div class="alert alert-info d-flex align-items-center">
                                    <i class="fas fa-info-circle me-2"></i>
                                    <div class="flex-grow-1">
                                        <strong><?php echo __('detailed_department_export'); ?></strong><br>
                                        <small><?php echo __('detailed_export_description'); ?></small>
                                    </div>
                                    <div class="btn-group">
                                        <button type="button" class="btn btn-info btn-sm" onclick="exportDepartmentDetailed()">
                                            <i class="fas fa-file-excel"></i> <?php echo __('detailed_export'); ?>
                                        </button>
                                        <button type="button" class="btn btn-outline-info btn-sm" onclick="exportDepartmentTemplate()">
                                            <i class="fas fa-file-alt"></i> <?php echo __('empty_template'); ?>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Statistics Cards -->
            <div class="row g-3 mb-4">
                <div class="col-xl-2 col-lg-4 col-md-6 col-sm-6">
                    <div class="card border-0 shadow-sm h-100 stats-card">
                        <div class="card-body text-center p-4">
                            <div class="stats-icon mb-3">
                                <div class="icon-wrapper bg-primary bg-opacity-10">
                                    <i class="fas fa-users text-primary"></i>
                                </div>
                            </div>
                            <h2 class="stats-number text-primary mb-2"><?php echo number_format($total_patients); ?></h2>
                            <p class="stats-label text-muted mb-0"><?php echo __('total_patients'); ?></p>
                        </div>
                    </div>
                </div>
                
                <div class="col-xl-2 col-lg-4 col-md-6 col-sm-6">
                    <div class="card border-0 shadow-sm h-100 stats-card">
                        <div class="card-body text-center p-4">
                            <div class="stats-icon mb-3">
                                <div class="icon-wrapper bg-success bg-opacity-10">
                                    <i class="fas fa-file-medical text-success"></i>
                                </div>
                            </div>
                            <h2 class="stats-number text-success mb-2"><?php echo number_format($total_reports); ?></h2>
                            <p class="stats-label text-muted mb-0"><?php echo __('total_reports'); ?></p>
                        </div>
                    </div>
                </div>
                
                <div class="col-xl-2 col-lg-4 col-md-6 col-sm-6">
                    <div class="card border-0 shadow-sm h-100 stats-card">
                        <div class="card-body text-center p-4">
                            <div class="stats-icon mb-3">
                                <div class="icon-wrapper bg-warning bg-opacity-10">
                                    <i class="fas fa-pills text-warning"></i>
                                </div>
                            </div>
                            <h2 class="stats-number text-warning mb-2"><?php echo number_format($total_antibiotics); ?></h2>
                            <p class="stats-label text-muted mb-0"><?php echo __('total_antibiotics'); ?></p>
                        </div>
                    </div>
                </div>
                
                <div class="col-xl-2 col-lg-4 col-md-6 col-sm-6">
                    <div class="card border-0 shadow-sm h-100 stats-card">
                        <div class="card-body text-center p-4">
                            <div class="stats-icon mb-3">
                                <div class="icon-wrapper bg-info bg-opacity-10">
                                    <i class="fas fa-check-circle text-info"></i>
                                </div>
                            </div>
                            <h2 class="stats-number text-info mb-2"><?php echo number_format($active_antibiotics); ?></h2>
                            <p class="stats-label text-muted mb-0"><?php echo __('active_antibiotics'); ?></p>
                        </div>
                    </div>
                </div>
                
                <div class="col-xl-2 col-lg-4 col-md-6 col-sm-6">
                    <div class="card border-0 shadow-sm h-100 stats-card">
                        <div class="card-body text-center p-4">
                            <div class="stats-icon mb-3">
                                <div class="icon-wrapper bg-secondary bg-opacity-10">
                                    <i class="fas fa-user-md text-secondary"></i>
                                </div>
                            </div>
                            <h2 class="stats-number text-secondary mb-2"><?php echo number_format($total_users); ?></h2>
                            <p class="stats-label text-muted mb-0"><?php echo __('active_users'); ?></p>
                        </div>
                    </div>
                </div>
                
                <div class="col-xl-2 col-lg-4 col-md-6 col-sm-6">
                    <div class="card border-0 shadow-sm h-100 stats-card">
                        <div class="card-body text-center p-4">
                            <div class="stats-icon mb-3">
                                <div class="icon-wrapper bg-danger bg-opacity-10">
                                    <i class="fas fa-percentage text-danger"></i>
                                </div>
                            </div>
                            <h2 class="stats-number text-danger mb-2"><?php echo $total_antibiotics > 0 ? round(($active_antibiotics / $total_antibiotics) * 100, 1) : 0; ?>%</h2>
                            <p class="stats-label text-muted mb-0"><?php echo __('activity_rate'); ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row g-4">
                <!-- Reports by Department Chart -->
                <div class="col-lg-6">
                    <div class="card border-0 shadow-sm h-100 chart-card">
                        <div class="card-header bg-transparent border-0">
                            <h5 class="card-title mb-0">
                                <i class="fas fa-hospital-alt me-2 text-primary"></i>
                                <?php echo __('reports_by_department'); ?>
                            </h5>
                        </div>
                        <div class="card-body">
                            <div style="height: 350px;">
                                <canvas id="departmentChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Priority Statistics -->
                <div class="col-lg-6">
                    <div class="card border-0 shadow-sm h-100 chart-card">
                        <div class="card-header bg-transparent border-0">
                            <h5 class="card-title mb-0">
                                <i class="fas fa-exclamation-triangle me-2 text-warning"></i>
                                <?php echo __('statistics_by_priority'); ?>
                            </h5>
                        </div>
                        <div class="card-body">
                            <?php if (!empty($reports_by_priority)): ?>
                                <?php foreach ($reports_by_priority as $priority): ?>
                                    <div class="priority-item">
                                        <div class="d-flex align-items-center">
                                            <div class="flex-shrink-0 me-3">
                                                <span class="badge bg-<?php 
                                                    echo $priority['priority'] == 'pending' ? 'warning' : 
                                                        ($priority['priority'] == 'completed' ? 'success' : 'danger'); 
                                                ?> rounded-pill px-3 py-2">
                                                    <?php echo htmlspecialchars($priority['priority_ar']); ?>
                                                </span>
                                            </div>
                                            <div class="flex-grow-1">
                                                <div class="progress">
                                                    <div class="progress-bar bg-<?php 
                                                        echo $priority['priority'] == 'pending' ? 'warning' : 
                                                            ($priority['priority'] == 'completed' ? 'success' : 'danger'); 
                                                    ?>" 
                                                    style="width: <?php echo $priority['percentage']; ?>%"></div>
                                                </div>
                                            </div>
                                            <div class="flex-shrink-0 ms-3">
                                                <span class="fw-bold fs-5"><?php echo $priority['count']; ?></span>
                                                <small class="text-muted d-block"><?php echo $priority['percentage']; ?>%</small>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="empty-state">
                                    <i class="fas fa-info-circle"></i>
                                    <p><?php echo __('no_data_available'); ?></p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row g-4 mt-2">
                <!-- Most Active Users -->
                <div class="col-lg-6">
                    <div class="card border-0 shadow-sm h-100 chart-card">
                        <div class="card-header bg-transparent border-0">
                            <h5 class="card-title mb-0">
                                <i class="fas fa-trophy me-2 text-warning"></i>
                                <?php echo __('most_active_users'); ?>
                            </h5>
                        </div>
                        <div class="card-body">
                            <?php if (!empty($most_active_users)): ?>
                                <?php foreach ($most_active_users as $index => $user): ?>
                                    <div class="user-activity-item bg-light p-3 mb-3">
                                        <div class="d-flex align-items-center">
                                            <div class="flex-shrink-0 me-3">
                                                <div class="activity-number rounded-circle bg-primary text-white d-flex align-items-center justify-content-center">
                                                    <?php echo $user['activity_count']; ?>
                                                </div>
                                            </div>
                                            <div class="flex-grow-1">
                                                <h6 class="mb-1 fw-bold"><?php echo htmlspecialchars($user['full_name']); ?></h6>
                                                <small class="text-muted">
                                                    <?php 
                                                    $role_ar = [
                                                        'admin' => __('admin_role'),
                                                        'pharmacist' => __('pharmacist_role'),
                                                        'doctor' => __('doctor_role'),
                                                        'nurse' => __('nurse_role')
                                                    ];
                                                    echo $role_ar[$user['role']] ?? $user['role']; 
                                                    ?>
                                                </small>
                                            </div>
                                            <div class="flex-shrink-0">
                                                <span class="badge bg-gradient bg-primary rounded-pill fs-6">#<?php echo $index + 1; ?></span>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="empty-state">
                                    <i class="fas fa-users"></i>
                                    <p><?php echo __('no_data_available'); ?></p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Monthly Trend Chart -->
                <div class="col-lg-6">
                    <div class="card border-0 shadow-sm h-100 chart-card">
                        <div class="card-header bg-transparent border-0">
                            <h5 class="card-title mb-0">
                                <i class="fas fa-chart-line me-2 text-success"></i>
                                <?php echo __('monthly_reports_trend'); ?>
                            </h5>
                        </div>
                        <div class="card-body">
                            <div style="height: 350px;">
                                <canvas id="trendChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Antibiotic Usage Table -->
            <div class="row mt-4">
                <div class="col-12">
                    <div class="card border-0 shadow-sm chart-card">
                        <div class="card-header bg-transparent border-0">
                            <h5 class="card-title mb-0">
                                <i class="fas fa-pills me-2 text-info"></i>
                                <?php echo __('antibiotic_usage_statistics'); ?>
                            </h5>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table table-hover mb-0">
                                    <thead>
                                        <tr>
                                            <th><?php echo __('antibiotic_name'); ?></th>
                                            <th><?php echo __('usage_count'); ?></th>
                                            <th><?php echo __('average_dosage'); ?></th>
                                            <th><?php echo __('percentage'); ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if (!empty($antibiotic_usage)): ?>
                                            <?php 
                                            $total_usage = array_sum(array_column($antibiotic_usage, 'usage_count'));
                                            foreach ($antibiotic_usage as $antibiotic): 
                                                $percentage = $total_usage > 0 ? round(($antibiotic['usage_count'] / $total_usage) * 100, 1) : 0;
                                            ?>
                                                <tr>
                                                    <td class="fw-medium"><?php echo htmlspecialchars($antibiotic['antibiotic_name']); ?></td>
                                                    <td>
                                                        <span class="badge bg-primary rounded-pill px-3 py-2">
                                                            <?php echo $antibiotic['usage_count']; ?>
                                                        </span>
                                                    </td>
                                                    <td class="fw-medium"><?php echo $antibiotic['avg_dosage'] > 0 ? $antibiotic['avg_dosage'] . ' mg' : __('no_data_available'); ?></td>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="progress me-3" style="height: 8px; width: 120px;">
                                                                <div class="progress-bar bg-info" style="width: <?php echo $percentage; ?>%"></div>
                                                            </div>
                                                            <span class="fw-bold text-info"><?php echo $percentage; ?>%</span>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <tr>
                                                <td colspan="4">
                                                    <div class="empty-state">
                                                        <i class="fas fa-pills"></i>
                                                        <p><?php echo __('no_data_available'); ?></p>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<style>
    /* Filter Section */
    .filter-card {
        background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
        border: 1px solid #e3e6f0;
    }
    
    .filter-card .card-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 15px 15px 0 0 !important;
    }
    
    .form-label {
        font-weight: 600;
        color: #495057;
        margin-bottom: 0.5rem;
    }
    
    .form-control, .form-select {
        border-radius: 8px;
        border: 1px solid #d1d3e2;
        transition: all 0.3s ease;
    }
    
    .form-control:focus, .form-select:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
    }
    
    .btn-group .btn {
        border-radius: 8px;
        font-weight: 500;
        transition: all 0.3s ease;
    }
    
    .btn-group .btn:first-child {
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
    }
    
    .btn-group .btn:last-child {
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
    }
    
    .btn-group .btn:not(:first-child):not(:last-child) {
        border-radius: 0;
    }
    
    /* Statistics Cards */
    .stats-card {
        transition: all 0.3s ease;
        border-radius: 15px !important;
        overflow: hidden;
    }
    
    .stats-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 25px rgba(0,0,0,0.15) !important;
    }
    
    .stats-icon {
        margin-bottom: 1rem;
    }
    
    .icon-wrapper {
        width: 70px;
        height: 70px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto;
        transition: all 0.3s ease;
    }
    
    .stats-card:hover .icon-wrapper {
        transform: scale(1.1);
    }
    
    .icon-wrapper i {
        font-size: 2rem;
    }
    
    .stats-number {
        font-size: 2.5rem;
        font-weight: 700;
        line-height: 1;
    }
    
    .stats-label {
        font-size: 0.9rem;
        font-weight: 500;
    }
    
    /* Chart Cards */
    .chart-card {
        border-radius: 15px !important;
        transition: all 0.3s ease;
    }
    
    .chart-card:hover {
        box-shadow: 0 8px 25px rgba(0,0,0,0.1) !important;
    }
    
    .card-header {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%) !important;
        border-radius: 15px 15px 0 0 !important;
        padding: 1.5rem !important;
    }
    
    .card-title {
        font-size: 1.1rem;
        font-weight: 600;
        margin: 0;
    }
    
    /* Priority Progress Bars */
    .priority-item {
        padding: 1rem;
        border-radius: 10px;
        background: #f8f9fa;
        margin-bottom: 1rem;
        transition: all 0.3s ease;
    }
    
    .priority-item:hover {
        background: #e9ecef;
        transform: translateX(5px);
    }
    
    .progress {
        height: 10px !important;
        border-radius: 5px;
    }
    
    .progress-bar {
        border-radius: 5px;
    }
    
    /* User Activity Cards */
    .user-activity-item {
        border-radius: 12px !important;
        border: 1px solid #e9ecef;
        transition: all 0.3s ease;
    }
    
    .user-activity-item:hover {
        border-color: #007bff;
        box-shadow: 0 4px 15px rgba(0,123,255,0.1);
    }
    
    .activity-number {
        width: 50px;
        height: 50px;
        font-size: 1.2rem;
        font-weight: 700;
    }
    
    /* Table Enhancements */
    .table {
        border-radius: 10px;
        overflow: hidden;
    }
    
    .table thead th {
        background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
        color: white;
        font-weight: 600;
        border: none;
        padding: 1rem;
    }
    
    .table tbody tr {
        transition: all 0.3s ease;
    }
    
    .table tbody tr:hover {
        background-color: #f8f9fa;
        transform: scale(1.01);
    }
    
    .table tbody td {
        padding: 1rem;
        vertical-align: middle;
    }
    
    /* Empty State */
    .empty-state {
        padding: 3rem 2rem;
        text-align: center;
        color: #6c757d;
    }
    
    .empty-state i {
        font-size: 3rem;
        margin-bottom: 1rem;
        opacity: 0.5;
    }
    
    /* Animation */
    @keyframes fadeInUp {
        from {
            opacity: 0;
            transform: translateY(30px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    .stats-card {
        animation: fadeInUp 0.6s ease forwards;
    }
    
    .stats-card:nth-child(1) { animation-delay: 0.1s; }
    .stats-card:nth-child(2) { animation-delay: 0.2s; }
    .stats-card:nth-child(3) { animation-delay: 0.3s; }
    .stats-card:nth-child(4) { animation-delay: 0.4s; }
    .stats-card:nth-child(5) { animation-delay: 0.5s; }
    .stats-card:nth-child(6) { animation-delay: 0.6s; }
    
    /* Responsive Improvements */
    @media (max-width: 768px) {
        .stats-number {
            font-size: 2rem;
        }
        
        .icon-wrapper {
            width: 60px;
            height: 60px;
        }
        
        .icon-wrapper i {
            font-size: 1.5rem;
        }
        
        .card-body {
            padding: 1.5rem !important;
        }
    }
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Department Chart
const departmentCtx = document.getElementById('departmentChart').getContext('2d');
const departmentData = [<?php echo !empty($reports_by_department) ? implode(',', array_map(function($d) { return "'" . addslashes($d['department']) . "'"; }, $reports_by_department)) : "'" . __('no_data_available') . "'"; ?>];
const departmentCounts = [<?php echo !empty($reports_by_department) ? implode(',', array_column($reports_by_department, 'count')) : '0'; ?>];

const departmentChart = new Chart(departmentCtx, {
    type: 'doughnut',
    data: {
        labels: departmentData,
        datasets: [{
            data: departmentCounts,
            backgroundColor: [
                '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', 
                '#9966FF', '#FF9F40', '#FF6384', '#C9CBCF',
                '#4BC0C0', '#FF6384'
            ],
            borderWidth: 0
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'bottom',
                labels: {
                    padding: 20,
                    usePointStyle: true
                }
            }
        }
    }
});

// Trend Chart
const trendCtx = document.getElementById('trendChart').getContext('2d');
const trendLabels = [<?php echo !empty($monthly_trend) ? implode(',', array_map(function($t) { return "'" . $t['month'] . "'"; }, $monthly_trend)) : "'" . __('no_data_available') . "'"; ?>];
const trendData = [<?php echo !empty($monthly_trend) ? implode(',', array_column($monthly_trend, 'count')) : '0'; ?>];

const trendChart = new Chart(trendCtx, {
    type: 'line',
    data: {
        labels: trendLabels,
        datasets: [{
            label: '<?php echo __('number_of_reports'); ?>',
            data: trendData,
            borderColor: '#28a745',
            backgroundColor: 'rgba(40, 167, 69, 0.1)',
            borderWidth: 3,
            fill: true,
            tension: 0.4
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: false
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                grid: {
                    color: 'rgba(0,0,0,0.1)'
                }
            },
            x: {
                grid: {
                    display: false
                }
            }
        }
    }
});

function exportToExcel() {
    window.location.href = 'export/system_reports_excel.php';
}

// Filter Functions
function setQuickPeriod() {
    const period = document.getElementById('quick_period').value;
    const dateFrom = document.getElementById('date_from');
    const dateTo = document.getElementById('date_to');
    const today = new Date();
    
    switch(period) {
        case 'today':
            const todayStr = today.toISOString().split('T')[0];
            dateFrom.value = todayStr;
            dateTo.value = todayStr;
            break;
        case 'week':
            const weekStart = new Date(today.setDate(today.getDate() - today.getDay()));
            const weekEnd = new Date(today.setDate(today.getDate() - today.getDay() + 6));
            dateFrom.value = weekStart.toISOString().split('T')[0];
            dateTo.value = weekEnd.toISOString().split('T')[0];
            break;
        case 'month':
            const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
            const monthEnd = new Date(today.getFullYear(), today.getMonth() + 1, 0);
            dateFrom.value = monthStart.toISOString().split('T')[0];
            dateTo.value = monthEnd.toISOString().split('T')[0];
            break;
        case 'quarter':
            const quarter = Math.floor(today.getMonth() / 3);
            const quarterStart = new Date(today.getFullYear(), quarter * 3, 1);
            const quarterEnd = new Date(today.getFullYear(), quarter * 3 + 3, 0);
            dateFrom.value = quarterStart.toISOString().split('T')[0];
            dateTo.value = quarterEnd.toISOString().split('T')[0];
            break;
        case 'year':
            const yearStart = new Date(today.getFullYear(), 0, 1);
            const yearEnd = new Date(today.getFullYear(), 11, 31);
            dateFrom.value = yearStart.toISOString().split('T')[0];
            dateTo.value = yearEnd.toISOString().split('T')[0];
            break;
    }
}

function resetFilters() {
    document.getElementById('filtersForm').reset();
    window.location.href = window.location.pathname;
}

function exportFiltered() {
    const form = document.getElementById('filtersForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    
    // Check if department is selected for detailed export
    const department = document.getElementById('department').value;
    if (department) {
        window.location.href = 'export/department_detailed_excel.php?' + params.toString();
    } else {
        window.location.href = 'export/system_reports_excel.php?' + params.toString();
    }
}

function exportDepartmentDetailed() {
    const form = document.getElementById('filtersForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    window.location.href = 'export/department_detailed_excel.php?' + params.toString();
}

function exportDepartmentTemplate() {
    const form = document.getElementById('filtersForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    window.location.href = 'export/department_template_excel.php?' + params.toString();
}

function exportUnified() {
    const form = document.getElementById('filtersForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    
    // إضافة معاملات التصدير الموحد
    params.append('include_reports', '1');
    params.append('include_medication_tracking', '1');
    
    // التحقق من وجود قسم محدد
    const department = document.getElementById('department').value;
    if (department) {
        params.set('unit_id', department);
    }
    
    // إضافة تواريخ افتراضية إذا لم تكن محددة
    if (!params.get('date_from')) {
        const weekAgo = new Date();
        weekAgo.setDate(weekAgo.getDate() - 7);
        params.set('from_date', weekAgo.toISOString().split('T')[0]);
    } else {
        params.set('from_date', params.get('date_from'));
    }
    
    if (!params.get('date_to')) {
        params.set('to_date', new Date().toISOString().split('T')[0]);
    } else {
        params.set('to_date', params.get('date_to'));
    }
    
    window.location.href = 'export/unified_department_excel.php?' + params.toString();
}

// Show/hide department export option
document.addEventListener('DOMContentLoaded', function() {
    const departmentSelect = document.getElementById('department');
    const exportRow = document.getElementById('departmentExportRow');
    
    function toggleDepartmentExport() {
        if (departmentSelect.value) {
            exportRow.style.display = 'block';
        } else {
            exportRow.style.display = 'none';
        }
    }
    
    departmentSelect.addEventListener('change', toggleDepartmentExport);
    toggleDepartmentExport(); // Initial check
});
</script>

</div>

<?php include 'includes/footer.php'; ?>
