<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: index.php');
    exit();
}

$page_title = "Patient Import History";

// Fetch import history from activity_log table
$import_query = "
    SELECT 
        al.log_id,
        al.user_id,
        al.action,
        al.module,
        al.record_id,
        al.old_values,
        al.new_values,
        al.ip_address,
        al.user_agent,
        al.logged_at,
        u.full_name as imported_by
    FROM activity_log al
    LEFT JOIN users u ON al.user_id = u.user_id
    WHERE al.module = 'patients' AND al.action = 'IMPORT'
    ORDER BY al.logged_at DESC
    LIMIT 100
";

$import_result = mysqli_query($conn, $import_query);
$import_history = [];

if ($import_result) {
    while ($row = mysqli_fetch_assoc($import_result)) {
        $import_history[] = $row;
    }
}

// Calculate summary statistics
$total_imports = count($import_history);
$total_imported = 0;
$total_errors = 0;
$total_skipped = 0;
$last_import_date = null;

foreach ($import_history as $import) {
    // Parse from new_values JSON
    if ($import['new_values']) {
        $values = json_decode($import['new_values'], true);
        if (isset($values['imported'])) {
            $total_imported += intval($values['imported']);
        }
        if (isset($values['errors'])) {
            $total_errors += intval($values['errors']);
        }
        if (isset($values['skipped'])) {
            $total_skipped += intval($values['skipped']);
        }
    }
}

if ($total_imports > 0) {
    $last_import_date = $import_history[0]['logged_at'];
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            transition: transform 0.2s;
            margin-bottom: 1.5rem;
            text-align: center;
        }
        
        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.15);
        }
        
        .stat-icon {
            width: 56px;
            height: 56px;
            border-radius: 12px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 1.75rem;
            margin-bottom: 1rem;
        }
        
        .stat-icon.imports {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .stat-icon.patients {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
        }
        
        .stat-icon.errors {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            color: white;
        }
        
        .stat-icon.date {
            background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
            color: white;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            font-weight: 500;
        }
        
        .content-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .import-status-badge {
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            display: inline-block;
        }
        
        .import-status-badge.success {
            background: #d1fae5;
            color: #065f46;
        }
        
        .import-status-badge.partial {
            background: #fef3c7;
            color: #92400e;
        }
        
        .import-status-badge.failed {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .import-summary {
            display: flex;
            gap: 0.75rem;
            flex-wrap: wrap;
        }
        
        .summary-badge {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .summary-badge.imported {
            background: #d1fae5;
            color: #065f46;
        }
        
        .summary-badge.skipped {
            background: #fef3c7;
            color: #92400e;
        }
        
        .summary-badge.errors {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .table-actions {
            white-space: nowrap;
        }
        
        .empty-state {
            text-align: center;
            padding: 4rem 2rem;
        }
        
        .empty-icon {
            font-size: 5rem;
            color: #cbd5e1;
            margin-bottom: 1.5rem;
        }
        
        .btn-import-new {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            transition: all 0.2s;
        }
        
        .btn-import-new:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(102, 126, 234, 0.5);
            color: white;
        }
        
        .date-badge {
            background: #f1f5f9;
            padding: 0.5rem 1rem;
            border-radius: 6px;
            display: inline-block;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Patient Import History</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_patients.php">Patients</a></li>
                                        <li class="breadcrumb-item active">Import History</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h4 class="mb-2"><i class="ri-history-line me-2"></i>Import History</h4>
                                <p class="mb-0 opacity-75">View and track all patient data imports</p>
                            </div>
                            <div>
                                <a href="patient_import.php" class="btn btn-light btn-lg">
                                    <i class="ri-upload-cloud-2-line me-1"></i> Import New Data
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Summary Statistics -->
                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon imports">
                                    <i class="ri-upload-cloud-2-line"></i>
                                </div>
                                <div class="stat-value"><?php echo $total_imports; ?></div>
                                <div class="stat-label">Total Imports</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon patients">
                                    <i class="ri-user-add-line"></i>
                                </div>
                                <div class="stat-value"><?php echo number_format($total_imported); ?></div>
                                <div class="stat-label">Patients Imported</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon errors">
                                    <i class="ri-error-warning-line"></i>
                                </div>
                                <div class="stat-value"><?php echo number_format($total_errors); ?></div>
                                <div class="stat-label">Total Errors</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon date">
                                    <i class="ri-calendar-check-line"></i>
                                </div>
                                <div class="stat-value">
                                    <?php 
                                    if ($last_import_date) {
                                        $diff = time() - strtotime($last_import_date);
                                        $days = floor($diff / (60 * 60 * 24));
                                        if ($days == 0) {
                                            echo 'Today';
                                        } elseif ($days == 1) {
                                            echo 'Yesterday';
                                        } elseif ($days < 7) {
                                            echo $days . ' days ago';
                                        } else {
                                            echo date('M d, Y', strtotime($last_import_date));
                                        }
                                    } else {
                                        echo 'Never';
                                    }
                                    ?>
                                </div>
                                <div class="stat-label">Last Import</div>
                            </div>
                        </div>
                    </div>

                    <!-- Import History Table -->
                    <div class="content-card">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h5 class="mb-0"><i class="ri-list-check-2 me-2"></i>Import Records</h5>
                            <button class="btn btn-import-new" onclick="window.location.href='patient_import.php'">
                                <i class="ri-add-line me-1"></i> New Import
                            </button>
                        </div>

                        <?php if (empty($import_history)): ?>
                            <!-- Empty State -->
                            <div class="empty-state">
                                <i class="ri-inbox-line empty-icon"></i>
                                <h5 class="text-muted mb-2">No Import History</h5>
                                <p class="text-muted mb-4">You haven't imported any patient data yet.</p>
                                <a href="patient_import.php" class="btn btn-import-new btn-lg">
                                    <i class="ri-upload-cloud-2-line me-1"></i> Import Your First File
                                </a>
                            </div>
                        <?php else: ?>
                            <!-- Data Table -->
                            <div class="table-responsive">
                                <table class="table table-hover align-middle" id="importHistoryTable">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Import Date & Time</th>
                                            <th>Imported By</th>
                                            <th>Summary</th>
                                            <th>Status</th>
                                            <th class="text-center">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($import_history as $import): 
                                            // Parse import details from JSON
                                            $values = json_decode($import['new_values'], true);
                                            
                                            $imported_count = isset($values['imported']) ? intval($values['imported']) : 0;
                                            $skipped_count = isset($values['skipped']) ? intval($values['skipped']) : 0;
                                            $errors_count = isset($values['errors']) ? intval($values['errors']) : 0;
                                            
                                            // Determine status
                                            $status = 'success';
                                            $status_text = 'Success';
                                            if ($errors_count > 0 && $imported_count > 0) {
                                                $status = 'partial';
                                                $status_text = 'Partial Success';
                                            } elseif ($errors_count > 0 && $imported_count == 0) {
                                                $status = 'failed';
                                                $status_text = 'Failed';
                                            }
                                        ?>
                                            <tr>
                                                <td>
                                                    <div class="date-badge">
                                                        <strong><?php echo date('M d, Y', strtotime($import['logged_at'])); ?></strong>
                                                        <br>
                                                        <small class="text-muted">
                                                            <i class="ri-time-line"></i>
                                                            <?php echo date('h:i A', strtotime($import['logged_at'])); ?>
                                                        </small>
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <i class="ri-user-line text-muted me-2 fs-5"></i>
                                                        <div>
                                                            <strong><?php echo htmlspecialchars($import['imported_by']); ?></strong>
                                                            <?php if ($import['ip_address']): ?>
                                                                <br>
                                                                <small class="text-muted">
                                                                    <i class="ri-global-line"></i>
                                                                    <?php echo htmlspecialchars($import['ip_address']); ?>
                                                                </small>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="import-summary">
                                                        <?php if ($imported_count > 0): ?>
                                                            <span class="summary-badge imported">
                                                                <i class="ri-check-line"></i>
                                                                <?php echo $imported_count; ?> Imported
                                                            </span>
                                                        <?php endif; ?>
                                                        <?php if ($skipped_count > 0): ?>
                                                            <span class="summary-badge skipped">
                                                                <i class="ri-skip-forward-line"></i>
                                                                <?php echo $skipped_count; ?> Skipped
                                                            </span>
                                                        <?php endif; ?>
                                                        <?php if ($errors_count > 0): ?>
                                                            <span class="summary-badge errors">
                                                                <i class="ri-error-warning-line"></i>
                                                                <?php echo $errors_count; ?> Errors
                                                            </span>
                                                        <?php endif; ?>
                                                    </div>
                                                </td>
                                                <td>
                                                    <span class="import-status-badge <?php echo $status; ?>">
                                                        <?php if ($status == 'success'): ?>
                                                            <i class="ri-checkbox-circle-line"></i>
                                                        <?php elseif ($status == 'partial'): ?>
                                                            <i class="ri-alert-line"></i>
                                                        <?php else: ?>
                                                            <i class="ri-close-circle-line"></i>
                                                        <?php endif; ?>
                                                        <?php echo $status_text; ?>
                                                    </span>
                                                </td>
                                                <td class="text-center table-actions">
                                                    <button class="btn btn-sm btn-outline-primary" 
                                                            onclick='viewImportDetails(<?php echo json_encode($import); ?>)'
                                                            title="View Details">
                                                        <i class="ri-eye-line"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>

                </div>
            </div>

            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Import Details Modal -->
    <div class="modal fade" id="importDetailsModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="ri-information-line me-2"></i>Import Details
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="importDetailsContent">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="ri-close-line me-1"></i> Close
                    </button>
                </div>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize DataTable
            $('#importHistoryTable').DataTable({
                order: [[0, 'desc']],
                pageLength: 25,
                language: {
                    search: "Search imports:",
                    lengthMenu: "Show _MENU_ imports per page",
                    info: "Showing _START_ to _END_ of _TOTAL_ imports",
                    infoEmpty: "No imports to show",
                    infoFiltered: "(filtered from _MAX_ total imports)",
                    emptyTable: "No import history available",
                    zeroRecords: "No matching imports found"
                },
                columnDefs: [
                    { orderable: false, targets: 4 } // Actions column
                ]
            });
        });

        function viewImportDetails(importData) {
            const modal = new bootstrap.Modal(document.getElementById('importDetailsModal'));
            modal.show();

            const values = JSON.parse(importData.new_values || '{}');
            const imported = values.imported || 0;
            const skipped = values.skipped || 0;
            const errors = values.errors || 0;
            const filename = values.filename || 'Unknown';
            
            const html = `
                <div class="row mb-4">
                    <div class="col-md-6">
                        <div class="border-start border-4 border-primary ps-3">
                            <strong class="text-muted d-block mb-1">Import Date & Time</strong>
                            <div>${new Date(importData.logged_at).toLocaleString()}</div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="border-start border-4 border-primary ps-3">
                            <strong class="text-muted d-block mb-1">Imported By</strong>
                            <div>
                                <i class="ri-user-line me-1"></i>
                                ${importData.imported_by}
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="row mb-4">
                    <div class="col-md-4">
                        <div class="text-center p-3 border rounded">
                            <div class="fs-2 fw-bold text-success mb-1">${imported}</div>
                            <div class="text-muted small">Patients Imported</div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="text-center p-3 border rounded">
                            <div class="fs-2 fw-bold text-warning mb-1">${skipped}</div>
                            <div class="text-muted small">Records Skipped</div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="text-center p-3 border rounded">
                            <div class="fs-2 fw-bold text-danger mb-1">${errors}</div>
                            <div class="text-muted small">Errors Encountered</div>
                        </div>
                    </div>
                </div>
                
                <div class="alert alert-light border mb-3">
                    <strong class="d-block mb-2">
                        <i class="ri-file-line me-1"></i>
                        File Information:
                    </strong>
                    <p class="mb-0">${filename}</p>
                </div>
                
                ${importData.ip_address ? `
                    <div class="text-muted small">
                        <i class="ri-global-line me-1"></i>
                        IP Address: ${importData.ip_address}
                    </div>
                ` : ''}
            `;
            
            $('#importDetailsContent').html(html);
        }
    </script>
</body>
</html>