<?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 = "Import Patient Data";
?>

<?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/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);
        }
        
        .import-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 2rem;
            position: relative;
        }
        
        .step {
            flex: 1;
            text-align: center;
            position: relative;
        }
        
        .step-circle {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: #e2e8f0;
            color: #64748b;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 0.5rem;
            font-weight: 700;
            font-size: 1.25rem;
            transition: all 0.3s;
            position: relative;
            z-index: 2;
        }
        
        .step.active .step-circle {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            box-shadow: 0 4px 6px -1px rgba(102, 126, 234, 0.5);
        }
        
        .step.completed .step-circle {
            background: #10b981;
            color: white;
        }
        
        .step.completed .step-circle i {
            display: inline;
        }
        
        .step-circle span {
            display: inline;
        }
        
        .step.completed .step-circle span {
            display: none;
        }
        
        .step-circle i {
            display: none;
        }
        
        .step-line {
            position: absolute;
            top: 25px;
            left: 50%;
            width: 100%;
            height: 2px;
            background: #e2e8f0;
            z-index: 1;
        }
        
        .step:last-child .step-line {
            display: none;
        }
        
        .step.completed .step-line {
            background: #10b981;
        }
        
        .step-label {
            font-size: 0.875rem;
            font-weight: 600;
            color: #64748b;
        }
        
        .step.active .step-label {
            color: #667eea;
        }
        
        .upload-area {
            border: 3px dashed #cbd5e1;
            border-radius: 12px;
            padding: 4rem 2rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            background: #f8fafc;
        }
        
        .upload-area:hover {
            border-color: #667eea;
            background: #f1f5f9;
        }
        
        .upload-area.dragover {
            border-color: #764ba2;
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
        }
        
        .upload-icon {
            font-size: 4rem;
            color: #94a3b8;
            margin-bottom: 1rem;
        }
        
        .file-info {
            background: linear-gradient(135deg, #f0fdf4 0%, #ecfdf5 100%);
            padding: 1.5rem;
            border-radius: 12px;
            margin-top: 1.5rem;
            border: 1px solid #86efac;
        }
        
        .mapping-row {
            display: flex;
            align-items: center;
            padding: 1rem;
            background: #f8fafc;
            border-radius: 8px;
            margin-bottom: 0.75rem;
            border: 1px solid #e2e8f0;
        }
        
        .mapping-row:hover {
            background: #f1f5f9;
            border-color: #cbd5e1;
        }
        
        .preview-table-container {
            max-height: 500px;
            overflow-y: auto;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
        }
        
        .stat-box {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            text-align: center;
            border: 1px solid #e2e8f0;
            transition: all 0.2s;
        }
        
        .stat-box:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .stat-number.total { color: #3b82f6; }
        .stat-number.valid { color: #10b981; }
        .stat-number.error { color: #ef4444; }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            font-weight: 500;
        }
        
        .import-progress {
            display: none;
        }
        
        .progress-bar-custom {
            height: 30px;
            border-radius: 8px;
            font-size: 0.875rem;
            font-weight: 600;
        }
        
        .import-section {
            display: none;
        }
        
        .import-section.active {
            display: block;
        }
        
        .error-badge {
            background: #fee2e2;
            color: #991b1b;
            padding: 0.5rem 1rem;
            border-radius: 6px;
            font-size: 0.875rem;
            margin-bottom: 0.5rem;
            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">Import Patient Data</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 Data</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-upload-cloud-2-line me-2"></i>Patient Data Import</h4>
                                <p class="mb-0 opacity-75">Import patient records and clinical history from CSV files</p>
                            </div>
                            <div>
                                <a href="import_history.php" class="btn btn-light me-2">
                                    <i class="ri-history-line me-1"></i> Import History
                                </a>
                                <a href="list_patients.php" class="btn btn-light">
                                    <i class="ri-arrow-left-line me-1"></i> Back to Patients
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Step Indicator -->
                    <div class="import-card">
                        <div class="step-indicator">
                            <div class="step active" data-step="1">
                                <div class="step-circle">
                                    <span>1</span>
                                    <i class="ri-check-line"></i>
                                </div>
                                <div class="step-label">Upload File</div>
                                <div class="step-line"></div>
                            </div>
                            <div class="step" data-step="2">
                                <div class="step-circle">
                                    <span>2</span>
                                    <i class="ri-check-line"></i>
                                </div>
                                <div class="step-label">Map Columns</div>
                                <div class="step-line"></div>
                            </div>
                            <div class="step" data-step="3">
                                <div class="step-circle">
                                    <span>3</span>
                                    <i class="ri-check-line"></i>
                                </div>
                                <div class="step-label">Preview & Validate</div>
                                <div class="step-line"></div>
                            </div>
                            <div class="step" data-step="4">
                                <div class="step-circle">
                                    <span>4</span>
                                    <i class="ri-check-line"></i>
                                </div>
                                <div class="step-label">Import</div>
                            </div>
                        </div>

                        <!-- Step 1: Upload File -->
                        <div id="step1" class="import-section active">
                            <h5 class="mb-4">Step 1: Upload CSV File</h5>
                            
                            <div class="upload-area" id="uploadArea">
                                <i class="ri-upload-cloud-2-line upload-icon"></i>
                                <h5 class="mb-2">Drag and drop your CSV file here</h5>
                                <p class="text-muted mb-3">or click to browse your computer</p>
                                <button type="button" class="btn btn-primary" onclick="document.getElementById('csvFile').click()">
                                    <i class="ri-file-add-line me-1"></i> Choose File
                                </button>
                                <input type="file" id="csvFile" accept=".csv" style="display: none;">
                            </div>
                            
                            <div id="fileInfo" class="file-info" style="display: none;">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <i class="ri-file-excel-2-line text-success fs-4 me-2"></i>
                                        <strong id="fileName"></strong>
                                        <span class="text-muted ms-2" id="fileSize"></span>
                                    </div>
                                    <button class="btn btn-sm btn-outline-danger" id="removeFile">
                                        <i class="ri-delete-bin-line me-1"></i> Remove
                                    </button>
                                </div>
                            </div>

                            <div class="alert alert-info border-0 mt-4">
                                <div class="d-flex align-items-start">
                                    <i class="ri-information-line fs-4 me-2"></i>
                                    <div>
                                        <strong>Expected CSV Format:</strong>
                                        <p class="mb-0 mt-1">Your file should contain patient registration data, clinical visits, and consultation information. The system will automatically detect and map columns to the appropriate database fields.</p>
                                    </div>
                                </div>
                            </div>

                            <div class="text-end mt-4">
                                <button class="btn btn-primary btn-lg" id="btnStep1Next" disabled>
                                    Next: Map Columns <i class="ri-arrow-right-line ms-1"></i>
                                </button>
                            </div>
                        </div>

                        <!-- Step 2: Column Mapping -->
                        <div id="step2" class="import-section">
                            <h5 class="mb-4">Step 2: Map CSV Columns to Database Fields</h5>
                            
                            <div class="alert alert-warning border-0 mb-4">
                                <div class="d-flex align-items-start">
                                    <i class="ri-alert-line fs-4 me-2"></i>
                                    <div>
                                        Review the automatic column mapping below. Required fields are marked with a badge. You can adjust mappings using the dropdowns.
                                    </div>
                                </div>
                            </div>

                            <div id="columnMappings"></div>

                            <div class="d-flex justify-content-between mt-4">
                                <button class="btn btn-outline-secondary" id="btnStep2Back">
                                    <i class="ri-arrow-left-line me-1"></i> Back
                                </button>
                                <button class="btn btn-primary btn-lg" id="btnStep2Next">
                                    Next: Preview Data <i class="ri-arrow-right-line ms-1"></i>
                                </button>
                            </div>
                        </div>

                        <!-- Step 3: Preview & Validate -->
                        <div id="step3" class="import-section">
                            <h5 class="mb-4">Step 3: Preview and Validate Data</h5>
                            
                            <div class="row mb-4">
                                <div class="col-md-4">
                                    <div class="stat-box">
                                        <div class="stat-number total" id="totalRecords">0</div>
                                        <div class="stat-label">Total Records</div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="stat-box">
                                        <div class="stat-number valid" id="validRecords">0</div>
                                        <div class="stat-label">Valid Records</div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="stat-box">
                                        <div class="stat-number error" id="errorRecords">0</div>
                                        <div class="stat-label">Records with Errors</div>
                                    </div>
                                </div>
                            </div>

                            <div id="validationErrors" class="alert alert-danger border-0" style="display: none;">
                                <h6 class="alert-heading"><i class="ri-error-warning-line me-2"></i>Validation Errors Found:</h6>
                                <div class="error-list" id="errorList" style="max-height: 300px; overflow-y: auto;"></div>
                            </div>

                            <h6 class="mb-3">Data Preview (First 10 Records)</h6>
                            <div class="preview-table-container">
                                <table class="table table-sm table-hover mb-0" id="previewTable">
                                    <thead class="table-light sticky-top">
                                        <tr id="previewHeaders"></tr>
                                    </thead>
                                    <tbody id="previewBody"></tbody>
                                </table>
                            </div>

                            <div class="d-flex justify-content-between mt-4">
                                <button class="btn btn-outline-secondary" id="btnStep3Back">
                                    <i class="ri-arrow-left-line me-1"></i> Back
                                </button>
                                <button class="btn btn-primary btn-lg" id="btnStep3Next">
                                    Next: Import Data <i class="ri-arrow-right-line ms-1"></i>
                                </button>
                            </div>
                        </div>

                        <!-- Step 4: Import -->
                        <div id="step4" class="import-section">
                            <h5 class="mb-4">Step 4: Import Patient Data</h5>
                            
                            <div class="alert alert-info border-0 mb-4">
                                <div class="d-flex align-items-start">
                                    <i class="ri-information-line fs-4 me-2"></i>
                                    <div>
                                        Ready to import <strong id="importCount">0</strong> patient records. This process may take a few minutes depending on the file size.
                                    </div>
                                </div>
                            </div>

                            <div class="card border mb-4">
                                <div class="card-body">
                                    <h6 class="card-title mb-3">Import Options</h6>
                                    <div class="form-check mb-3">
                                        <input class="form-check-input" type="checkbox" id="skipDuplicates" checked>
                                        <label class="form-check-label" for="skipDuplicates">
                                            <strong>Skip duplicate patient records</strong><br>
                                            <small class="text-muted">Prevents importing patients that already exist (matched by Patient Number)</small>
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="updateExisting">
                                        <label class="form-check-label" for="updateExisting">
                                            <strong>Update existing patient information</strong><br>
                                            <small class="text-muted">Updates patient details if a matching Patient Number is found</small>
                                        </label>
                                    </div>
                                </div>
                            </div>

                            <div class="import-progress">
                                <div class="progress mb-3" style="height: 30px;">
                                    <div class="progress-bar progress-bar-striped progress-bar-animated bg-primary progress-bar-custom" 
                                         role="progressbar" id="importProgress" style="width: 0%">0%</div>
                                </div>
                                <p class="text-center text-muted" id="progressText">Preparing import...</p>
                            </div>

                            <div id="importResults" style="display: none;"></div>

                            <div class="d-flex justify-content-between mt-4" id="importActions">
                                <button class="btn btn-outline-secondary" id="btnStep4Back">
                                    <i class="ri-arrow-left-line me-1"></i> Back
                                </button>
                                <button class="btn btn-success btn-lg" id="btnStartImport">
                                    <i class="ri-play-fill me-1"></i> Start Import
                                </button>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

            <?php include 'layouts/footer.php'; ?>
        </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/sweetalert2/sweetalert2.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.3.0/papaparse.min.js"></script>
    <script src="assets/js/patient_import.js"></script>
    
    <!-- Move the check here, after libraries load -->
    <script>
        console.log('Page loaded, checking dependencies...');
        console.log('jQuery:', typeof $ !== 'undefined' ? 'Loaded' : 'NOT LOADED');
        console.log('Papa:', typeof Papa !== 'undefined' ? 'Loaded' : 'NOT LOADED');
        console.log('Swal:', typeof Swal !== 'undefined' ? 'Loaded' : 'NOT LOADED');
    </script>
</body>
</html>