<?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', 'MEDICAL_RECORDS'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Handle CSV Upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
    $conn->begin_transaction();
    
    try {
        $file = $_FILES['csv_file'];
        
        if ($file['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('File upload error');
        }
        
        if (!in_array($file['type'], ['text/csv', 'text/plain', 'application/vnd.ms-excel'])) {
            throw new Exception('Invalid file type. Please upload a CSV file');
        }
        
        $handle = fopen($file['tmp_name'], 'r');
        if (!$handle) {
            throw new Exception('Could not open file');
        }
        
        // Skip header row
        fgetcsv($handle);
        
        $imported = 0;
        $skipped = 0;
        $errors = [];
        
        $insert_sql = "INSERT INTO icd10_codes (code, short_description, full_description, category, chapter, chapter_code, is_billable, is_ent_related, commonly_used, created_by, created_at)
                      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
                      ON DUPLICATE KEY UPDATE 
                        short_description = VALUES(short_description),
                        full_description = VALUES(full_description),
                        category = VALUES(category),
                        updated_at = NOW()";
        
        $stmt = $conn->prepare($insert_sql);
        
        while (($data = fgetcsv($handle)) !== FALSE) {
            if (count($data) < 3) {
                $skipped++;
                continue;
            }
            
            $code = trim($data[0]);
            $short_desc = trim($data[1]);
            $full_desc = isset($data[2]) ? trim($data[2]) : null;
            $category = isset($data[3]) ? trim($data[3]) : null;
            $chapter = isset($data[4]) ? trim($data[4]) : null;
            $chapter_code = isset($data[5]) ? trim($data[5]) : null;
            $is_billable = isset($data[6]) ? (int)$data[6] : 1;
            $is_ent = isset($data[7]) ? (int)$data[7] : 0;
            $commonly_used = isset($data[8]) ? (int)$data[8] : 0;
            
            if (empty($code) || empty($short_desc)) {
                $skipped++;
                continue;
            }
            
            $stmt->bind_param('ssssssiiii', 
                $code, $short_desc, $full_desc, $category, $chapter, $chapter_code,
                $is_billable, $is_ent, $commonly_used, $user_id
            );
            
            if ($stmt->execute()) {
                $imported++;
            } else {
                $skipped++;
                $errors[] = "Failed to import code: $code";
            }
        }
        
        fclose($handle);
        $conn->commit();
        
        $_SESSION['success_message'] = "Successfully imported $imported codes. Skipped: $skipped";
        header('Location: manage_icd10_codes.php');
        exit();
        
    } catch (Exception $e) {
        $conn->rollback();
        $error_message = $e->getMessage();
    }
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Import ICD-10 Codes')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .upload-section {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }

        .upload-area {
            border: 2px dashed #cbd5e1;
            border-radius: 12px;
            padding: 3rem;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
            background: #f9fafb;
        }

        .upload-area:hover {
            border-color: #3b82f6;
            background: #f0f9ff;
        }

        .upload-area.dragover {
            border-color: #3b82f6;
            background: #dbeafe;
        }

        .upload-icon {
            font-size: 4rem;
            color: #3b82f6;
            margin-bottom: 1rem;
        }

        .instruction-card {
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            border-radius: 12px;
            padding: 2rem;
            border-left: 4px solid #3b82f6;
        }

        .instruction-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .instruction-list li {
            padding: 0.75rem 0;
            border-bottom: 1px solid rgba(59, 130, 246, 0.1);
            display: flex;
            align-items: start;
            gap: 0.75rem;
        }

        .instruction-list li:last-child {
            border-bottom: none;
        }

        .step-number {
            background: #3b82f6;
            color: white;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.75rem;
            font-weight: 600;
            flex-shrink: 0;
        }

        .sample-table {
            font-size: 0.875rem;
            background: white;
            border-radius: 8px;
            overflow: hidden;
        }

        .sample-table th {
            background: #1e40af;
            color: white;
            font-weight: 600;
            padding: 0.75rem;
        }

        .sample-table td {
            padding: 0.75rem;
            border: 1px solid #e5e7eb;
        }

        .alert-info {
            background: #dbeafe;
            border-left: 4px solid #3b82f6;
            color: #1e40af;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h4 class="mb-1">
                                        <i class="ri-upload-2-line me-2"></i>
                                        Import ICD-10 Codes
                                    </h4>
                                    <p class="text-muted mb-0">Bulk import diagnosis codes from CSV file</p>
                                </div>
                                <a href="manage_icd10_codes.php" class="btn btn-secondary">
                                    <i class="ri-arrow-left-line me-1"></i> Back to Codes
                                </a>
                            </div>
                        </div>
                    </div>

                    <?php if (isset($error_message)): ?>
                    <div class="alert alert-danger">
                        <i class="ri-error-warning-line me-2"></i>
                        <?php echo htmlspecialchars($error_message); ?>
                    </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-lg-8">
                            <!-- Upload Section -->
                            <div class="upload-section">
                                <h5 class="mb-3">
                                    <i class="ri-file-upload-line me-2"></i>
                                    Upload CSV File
                                </h5>
                                
                                <form method="POST" enctype="multipart/form-data" id="uploadForm">
                                    <div class="upload-area" id="uploadArea">
                                        <input type="file" name="csv_file" id="csvFile" accept=".csv" hidden required>
                                        <i class="ri-upload-cloud-2-line upload-icon"></i>
                                        <h5>Drop your CSV file here</h5>
                                        <p class="text-muted">or click to browse</p>
                                        <button type="button" class="btn btn-primary mt-2" onclick="document.getElementById('csvFile').click()">
                                            <i class="ri-folder-open-line me-1"></i> Choose File
                                        </button>
                                    </div>
                                    
                                    <div id="fileInfo" class="mt-3" style="display: none;">
                                        <div class="alert alert-info">
                                            <i class="ri-file-text-line me-2"></i>
                                            Selected file: <strong id="fileName"></strong>
                                            <button type="button" class="btn-close float-end" onclick="clearFile()"></button>
                                        </div>
                                    </div>

                                    <div class="mt-3">
                                        <button type="submit" class="btn btn-success" id="uploadBtn" disabled>
                                            <i class="ri-upload-line me-1"></i> Import Codes
                                        </button>
                                    </div>
                                </form>
                            </div>

                            <!-- Sample Format -->
                            <div class="upload-section">
                                <h5 class="mb-3">
                                    <i class="ri-table-line me-2"></i>
                                    CSV File Format
                                </h5>
                                
                                <div class="alert alert-info mb-3">
                                    <strong>Required Columns:</strong> code, short_description<br>
                                    <strong>Optional Columns:</strong> full_description, category, chapter, chapter_code, is_billable, is_ent_related, commonly_used
                                </div>

                                <div class="table-responsive">
                                    <table class="sample-table table table-bordered mb-0">
                                        <thead>
                                            <tr>
                                                <th>code</th>
                                                <th>short_description</th>
                                                <th>full_description</th>
                                                <th>category</th>
                                                <th>is_ent_related</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <td>H65.0</td>
                                                <td>Acute serous otitis media</td>
                                                <td>Acute and subacute secretory otitis</td>
                                                <td>Ear Diseases</td>
                                                <td>1</td>
                                            </tr>
                                            <tr>
                                                <td>J01.0</td>
                                                <td>Acute maxillary sinusitis</td>
                                                <td>Acute antritis</td>
                                                <td>Nose & Sinus Diseases</td>
                                                <td>1</td>
                                            </tr>
                                            <tr>
                                                <td>J03.9</td>
                                                <td>Acute tonsillitis</td>
                                                <td>Tonsillitis NOS</td>
                                                <td>Throat Diseases</td>
                                                <td>1</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>

                                <div class="mt-3">
                                    <a href="download_sample_icd10.php" class="btn btn-outline-primary">
                                        <i class="ri-download-line me-1"></i> Download Sample CSV
                                    </a>
                                </div>
                            </div>
                        </div>

                        <div class="col-lg-4">
                            <!-- Instructions -->
                            <div class="instruction-card">
                                <h5 class="mb-3">
                                    <i class="ri-information-line me-2"></i>
                                    Import Instructions
                                </h5>
                                
                                <ul class="instruction-list">
                                    <li>
                                        <span class="step-number">1</span>
                                        <div>
                                            <strong>Prepare CSV File</strong>
                                            <p class="text-muted small mb-0">Ensure your CSV has the required columns: code and short_description</p>
                                        </div>
                                    </li>
                                    <li>
                                        <span class="step-number">2</span>
                                        <div>
                                            <strong>Check Format</strong>
                                            <p class="text-muted small mb-0">Use comma (,) as delimiter. First row should contain column headers</p>
                                        </div>
                                    </li>
                                    <li>
                                        <span class="step-number">3</span>
                                        <div>
                                            <strong>Boolean Values</strong>
                                            <p class="text-muted small mb-0">Use 1 for Yes/True and 0 for No/False</p>
                                        </div>
                                    </li>
                                    <li>
                                        <span class="step-number">4</span>
                                        <div>
                                            <strong>Upload File</strong>
                                            <p class="text-muted small mb-0">Drag and drop or click to select your CSV file</p>
                                        </div>
                                    </li>
                                    <li>
                                        <span class="step-number">5</span>
                                        <div>
                                            <strong>Import</strong>
                                            <p class="text-muted small mb-0">Click "Import Codes" to start the import process</p>
                                        </div>
                                    </li>
                                </ul>

                                <div class="alert alert-warning mt-3 mb-0" style="background: #fef3c7; border-color: #f59e0b;">
                                    <strong>Note:</strong> Duplicate codes will be updated with new information
                                </div>
                            </div>
                        </div>
                    </div>

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

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    const uploadArea = document.getElementById('uploadArea');
    const csvFile = document.getElementById('csvFile');
    const fileInfo = document.getElementById('fileInfo');
    const fileName = document.getElementById('fileName');
    const uploadBtn = document.getElementById('uploadBtn');

    // Click to upload
    uploadArea.addEventListener('click', () => csvFile.click());

    // File selected
    csvFile.addEventListener('change', (e) => {
        if (e.target.files.length > 0) {
            const file = e.target.files[0];
            if (file.type === 'text/csv' || file.name.endsWith('.csv')) {
                fileName.textContent = file.name;
                fileInfo.style.display = 'block';
                uploadBtn.disabled = false;
            } else {
                Swal.fire('Invalid File', 'Please select a CSV file', 'error');
                clearFile();
            }
        }
    });

    // Drag and drop
    uploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadArea.classList.add('dragover');
    });

    uploadArea.addEventListener('dragleave', () => {
        uploadArea.classList.remove('dragover');
    });

    uploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
        
        const file = e.dataTransfer.files[0];
        if (file && (file.type === 'text/csv' || file.name.endsWith('.csv'))) {
            csvFile.files = e.dataTransfer.files;
            fileName.textContent = file.name;
            fileInfo.style.display = 'block';
            uploadBtn.disabled = false;
        } else {
            Swal.fire('Invalid File', 'Please drop a CSV file', 'error');
        }
    });

    function clearFile() {
        csvFile.value = '';
        fileInfo.style.display = 'none';
        uploadBtn.disabled = true;
    }

    // Form submission
    document.getElementById('uploadForm').addEventListener('submit', function(e) {
        Swal.fire({
            title: 'Importing Codes...',
            html: 'Please wait while we import the ICD-10 codes',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
    });
    </script>

    <script src="assets/js/app.js"></script>
</body>
</html>