<?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: dashboard.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$errors = [];
$warnings = [];
$success_count = 0;
$skip_count = 0;
$error_details = [];

// Handle template download
if (isset($_GET['download_template'])) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="insurance_providers_template.csv"');
    
    $template = [
        ['Provider Name', 'Provider Code', 'Consultation Rate', 'Contact Person', 'Contact Email', 'Contact Phone', 'Address', 'Coverage Limit', 'Co-Payment %', 'Status'],
        ['AAR Insurance Kenya', 'AAR', '2500', 'John Doe', 'contact@aar.co.ke', '0712345678', '123 Insurance Plaza, Nairobi', '1000000', '10', 'Active'],
        ['Jubilee Insurance', 'JUBILEE', '3000', 'Jane Smith', 'info@jubilee.co.ke', '0723456789', '456 Jubilee House, Nairobi', '', '15', 'Active'],
    ];
    
    $output = fopen('php://output', 'w');
    foreach ($template as $row) {
        fputcsv($output, $row);
    }
    fclose($output);
    exit();
}

// Process file upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['provider_file'])) {
    $file = $_FILES['provider_file'];
    
    if ($file['error'] === UPLOAD_ERR_OK) {
        $allowed_extensions = ['csv', 'xlsx', 'xls'];
        $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        
        if (!in_array($file_extension, $allowed_extensions)) {
            $errors[] = "Invalid file format. Please upload CSV or Excel file.";
        } else {
            // Process CSV file
            if ($file_extension === 'csv') {
                $handle = fopen($file['tmp_name'], 'r');
                
                if ($handle !== false) {
                    // Skip header row
                    $header = fgetcsv($handle);
                    
                    // Validate header
                    $required_columns = ['Provider Name', 'Provider Code', 'Consultation Rate'];
                    $missing_columns = array_diff($required_columns, $header);
                    
                    if (!empty($missing_columns)) {
                        $errors[] = "Missing required columns: " . implode(', ', $missing_columns);
                    } else {
                        $row_number = 1;
                        
                        while (($data = fgetcsv($handle)) !== false) {
                            $row_number++;
                            
                            if (count($data) < 3 || empty(trim($data[0])) || empty(trim($data[1]))) {
                                $skip_count++;
                                $error_details[] = "Row $row_number: Missing required fields (Provider Name or Code)";
                                continue;
                            }
                            
                            $provider_name = trim($data[0]);
                            $provider_code = strtoupper(trim($data[1]));
                            $consultation_rate = !empty(trim($data[2])) ? floatval(trim($data[2])) : null;
                            $contact_person = isset($data[3]) ? trim($data[3]) : null;
                            $contact_email = isset($data[4]) ? trim($data[4]) : null;
                            $contact_phone = isset($data[5]) ? trim($data[5]) : null;
                            $address = isset($data[6]) ? trim($data[6]) : null;
                            $coverage_limit = isset($data[7]) && !empty(trim($data[7])) ? floatval(trim($data[7])) : null;
                            $co_payment_percentage = isset($data[8]) && !empty(trim($data[8])) ? floatval(trim($data[8])) : null;
                            $status = isset($data[9]) ? trim($data[9]) : 'Active';
                            $is_active = (strtolower($status) === 'active') ? 1 : 0;
                            
                            // Validate provider code format
                            if (!preg_match('/^[A-Z0-9]{2,10}$/', $provider_code)) {
                                $skip_count++;
                                $error_details[] = "Row $row_number: Invalid provider code format '$provider_code'";
                                continue;
                            }
                            
                            // Validate email if provided
                            if (!empty($contact_email) && !filter_var($contact_email, FILTER_VALIDATE_EMAIL)) {
                                $warnings[] = "Row $row_number: Invalid email format for $provider_name";
                                $contact_email = null;
                            }
                            
                            // Check if provider already exists
                            $check_sql = "SELECT provider_id FROM insurance_providers WHERE provider_code = ?";
                            $stmt = $conn->prepare($check_sql);
                            $stmt->bind_param("s", $provider_code);
                            $stmt->execute();
                            $result = $stmt->get_result();
                            
                            if ($result->num_rows > 0) {
                                // Update existing provider
                                $update_sql = "UPDATE insurance_providers SET 
                                              provider_name = ?,
                                              consultation_rate = ?,
                                              contact_person = ?,
                                              email = ?,
                                              phone = ?,
                                              address = ?,
                                              coverage_limit = ?,
                                              co_payment_percentage = ?,
                                              is_active = ?,
                                              created_at = NOW()
                                              WHERE provider_code = ?";
                                
                                $stmt = $conn->prepare($update_sql);
                                $stmt->bind_param("sdssssddis",
                                    $provider_name, $consultation_rate, $contact_person, 
                                    $contact_email, $contact_phone, $address,
                                    $coverage_limit, $co_payment_percentage, $is_active,
                                    $provider_code
                                );
                                
                                if ($stmt->execute()) {
                                    $success_count++;
                                    $warnings[] = "Row $row_number: Updated existing provider '$provider_name'";
                                } else {
                                    $skip_count++;
                                    $error_details[] = "Row $row_number: Failed to update '$provider_name'";
                                }
                            } else {
                                // Insert new provider
                                $insert_sql = "INSERT INTO insurance_providers 
                                              (provider_name, provider_code, consultation_rate, 
                                               contact_person, email, phone, address,
                                               coverage_limit, co_payment_percentage, is_active, created_at) 
                                              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
                                
                                $stmt = $conn->prepare($insert_sql);
                                $stmt->bind_param("ssdssssddi",
                                    $provider_name, $provider_code, $consultation_rate,
                                    $contact_person, $contact_email, $contact_phone, $address,
                                    $coverage_limit, $co_payment_percentage, $is_active
                                );
                                
                                if ($stmt->execute()) {
                                    $success_count++;
                                    
                                    // Log activity
                                    $provider_id = $conn->insert_id;
                                    $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, 
                                                   record_type, new_values, ip_address, logged_at) 
                                                   VALUES (?, 'IMPORT', 'INSURANCE', ?, 'INSURANCE_PROVIDER', ?, ?, NOW())";
                                    
                                    $new_values = json_encode(['provider_name' => $provider_name]);
                                    $ip_address = $_SERVER['REMOTE_ADDR'];
                                    
                                    $stmt = $conn->prepare($activity_sql);
                                    $stmt->bind_param("iiss", $user_id, $provider_id, $new_values, $ip_address);
                                    $stmt->execute();
                                } else {
                                    $skip_count++;
                                    $error_details[] = "Row $row_number: Failed to insert '$provider_name' - " . $stmt->error;
                                }
                            }
                        }
                        
                        fclose($handle);
                    }
                }
            } else {
                // Handle Excel files (requires PhpSpreadsheet library)
                $errors[] = "Excel file processing requires PhpSpreadsheet library. Please convert to CSV or contact administrator.";
            }
        }
    } else {
        $errors[] = "File upload failed. Please try again.";
    }
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Import Insurance Providers')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .import-container {
            max-width: 1000px;
            margin: 0 auto;
        }
        
        .upload-card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            border: 2px dashed #d1d5db;
            padding: 3rem;
            text-align: center;
            transition: all 0.3s ease;
        }
        
        .upload-card:hover {
            border-color: #3b82f6;
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        }
        
        .upload-card.dragover {
            background: #eff6ff;
            border-color: #3b82f6;
        }
        
        .upload-icon {
            width: 80px;
            height: 80px;
            margin: 0 auto 1.5rem;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 2.5rem;
        }
        
        .file-input-wrapper {
            position: relative;
            display: inline-block;
            margin-top: 1.5rem;
        }
        
        .file-input {
            position: absolute;
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .file-label {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 0.75rem 2rem;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .file-label:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.4);
        }
        
        .template-section {
            background: #f8fafc;
            border-radius: 12px;
            padding: 1.5rem;
            margin-top: 2rem;
            border: 1px solid #e2e8f0;
        }
        
        .instruction-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border-left: 4px solid #3b82f6;
        }
        
        .step-number {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 32px;
            height: 32px;
            background: #3b82f6;
            color: white;
            border-radius: 50%;
            font-weight: bold;
            margin-right: 1rem;
        }
        
        .result-card {
            padding: 1.5rem;
            border-radius: 12px;
            margin-bottom: 1rem;
        }
        
        .result-success {
            background: #d1fae5;
            border: 1px solid #6ee7b7;
        }
        
        .result-warning {
            background: #fef3c7;
            border: 1px solid #fcd34d;
        }
        
        .result-error {
            background: #fee2e2;
            border: 1px solid #fca5a5;
        }
        
        .selected-file {
            display: inline-flex;
            align-items: center;
            background: #eff6ff;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            margin-top: 1rem;
            border: 1px solid #93c5fd;
        }
        
        .selected-file i {
            font-size: 1.5rem;
            margin-right: 0.75rem;
            color: #3b82f6;
        }
    </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">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Import Insurance Providers</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_insurance_providers.php">Insurance Providers</a></li>
                                        <li class="breadcrumb-item active">Import</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="import-container">
                        <!-- Results Section -->
                        <?php if ($success_count > 0 || $skip_count > 0): ?>
                        <div class="row mb-4">
                            <?php if ($success_count > 0): ?>
                            <div class="col-md-6">
                                <div class="result-card result-success">
                                    <h5 class="mb-2">
                                        <i class="ri-checkbox-circle-line me-2"></i>
                                        Successfully Processed
                                    </h5>
                                    <p class="mb-0 fs-4 fw-bold"><?php echo $success_count; ?> provider(s)</p>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if ($skip_count > 0): ?>
                            <div class="col-md-6">
                                <div class="result-card result-warning">
                                    <h5 class="mb-2">
                                        <i class="ri-error-warning-line me-2"></i>
                                        Skipped/Errors
                                    </h5>
                                    <p class="mb-0 fs-4 fw-bold"><?php echo $skip_count; ?> row(s)</p>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>

                        <?php if (!empty($errors)): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <strong><i class="ri-error-warning-line me-2"></i>Errors:</strong>
                            <ul class="mb-0 mt-2">
                                <?php foreach ($errors as $error): ?>
                                    <li><?php echo htmlspecialchars($error); ?></li>
                                <?php endforeach; ?>
                            </ul>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                        <?php endif; ?>

                        <?php if (!empty($warnings)): ?>
                        <div class="alert alert-warning alert-dismissible fade show" role="alert">
                            <strong><i class="ri-information-line me-2"></i>Warnings:</strong>
                            <ul class="mb-0 mt-2" style="max-height: 300px; overflow-y: auto;">
                                <?php foreach (array_slice($warnings, 0, 10) as $warning): ?>
                                    <li><?php echo htmlspecialchars($warning); ?></li>
                                <?php endforeach; ?>
                                <?php if (count($warnings) > 10): ?>
                                    <li><em>... and <?php echo count($warnings) - 10; ?> more</em></li>
                                <?php endif; ?>
                            </ul>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                        <?php endif; ?>

                        <?php if (!empty($error_details)): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <strong><i class="ri-error-warning-line me-2"></i>Error Details:</strong>
                            <ul class="mb-0 mt-2" style="max-height: 300px; overflow-y: auto;">
                                <?php foreach (array_slice($error_details, 0, 10) as $detail): ?>
                                    <li><?php echo htmlspecialchars($detail); ?></li>
                                <?php endforeach; ?>
                                <?php if (count($error_details) > 10): ?>
                                    <li><em>... and <?php echo count($error_details) - 10; ?> more errors</em></li>
                                <?php endif; ?>
                            </ul>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                        <?php endif; ?>

                        <!-- Instructions -->
                        <div class="instruction-card">
                            <h5 class="mb-3"><i class="ri-information-line me-2"></i>Import Instructions</h5>
                            <div class="mb-2">
                                <span class="step-number">1</span>
                                <strong>Download the template</strong> - Click the button below to get the CSV template
                            </div>
                            <div class="mb-2">
                                <span class="step-number">2</span>
                                <strong>Fill in your data</strong> - Add your insurance provider information to the template
                            </div>
                            <div class="mb-2">
                                <span class="step-number">3</span>
                                <strong>Upload the file</strong> - Select your filled CSV file and click Import
                            </div>
                            <div class="mt-3">
                                <a href="?download_template=1" class="btn btn-outline-primary">
                                    <i class="ri-download-2-line me-1"></i> Download Template
                                </a>
                            </div>
                        </div>

                        <!-- Upload Section -->
                        <form method="POST" enctype="multipart/form-data" id="uploadForm">
                            <div class="upload-card" id="uploadCard">
                                <div class="upload-icon">
                                    <i class="ri-file-excel-2-line"></i>
                                </div>
                                <h4 class="mb-2">Upload Insurance Providers File</h4>
                                <p class="text-muted mb-0">Drag and drop your CSV file here</p>
                                <p class="text-muted">or</p>
                                
                                <div class="file-input-wrapper">
                                    <input type="file" 
                                           name="provider_file" 
                                           id="providerFile" 
                                           class="file-input" 
                                           accept=".csv,.xlsx,.xls"
                                           required>
                                    <label for="providerFile" class="file-label">
                                        <i class="ri-upload-2-line me-2"></i>Choose File
                                    </label>
                                </div>
                                
                                <div id="selectedFile" class="selected-file" style="display: none;">
                                    <i class="ri-file-line"></i>
                                    <span id="fileName"></span>
                                    <button type="button" class="btn-close ms-3" id="removeFile"></button>
                                </div>
                                
                                <p class="text-muted mt-3 mb-0">
                                    <small>Supported formats: CSV, Excel (.xlsx, .xls) | Max size: 5MB</small>
                                </p>
                            </div>
                            
                            <div class="text-center mt-4">
                                <a href="list_insurance_providers.php" class="btn btn-secondary me-2">
                                    <i class="ri-arrow-left-line me-1"></i> Cancel
                                </a>
                                <button type="submit" class="btn btn-primary btn-lg" id="importBtn" disabled>
                                    <i class="ri-upload-cloud-line me-2"></i> Import Providers
                                </button>
                            </div>
                        </form>

                        <!-- Template Format Section -->
                        <div class="template-section">
                            <h5 class="mb-3"><i class="ri-table-line me-2"></i>Template Format</h5>
                            <div class="table-responsive">
                                <table class="table table-bordered table-sm">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Provider Name*</th>
                                            <th>Provider Code*</th>
                                            <th>Consultation Rate*</th>
                                            <th>Contact Person</th>
                                            <th>Contact Email</th>
                                            <th>Contact Phone</th>
                                            <th>Address</th>
                                            <th>Coverage Limit</th>
                                            <th>Co-Payment %</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td>AAR Insurance</td>
                                            <td>AAR</td>
                                            <td>2500</td>
                                            <td>John Doe</td>
                                            <td>contact@aar.co.ke</td>
                                            <td>0712345678</td>
                                            <td>123 Insurance Plaza</td>
                                            <td>1000000</td>
                                            <td>10</td>
                                            <td>Active</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            <p class="text-muted mb-0 mt-2">
                                <small>* Required fields | Status: Active/Inactive | Provider Code: 2-10 uppercase letters/numbers</small>
                            </p>
                        </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>
    document.addEventListener('DOMContentLoaded', function() {
        const uploadCard = document.getElementById('uploadCard');
        const fileInput = document.getElementById('providerFile');
        const selectedFile = document.getElementById('selectedFile');
        const fileName = document.getElementById('fileName');
        const removeFile = document.getElementById('removeFile');
        const importBtn = document.getElementById('importBtn');
        const uploadForm = document.getElementById('uploadForm');
        
        // Drag and drop functionality
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            uploadCard.addEventListener(eventName, preventDefaults, false);
        });
        
        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }
        
        ['dragenter', 'dragover'].forEach(eventName => {
            uploadCard.addEventListener(eventName, () => {
                uploadCard.classList.add('dragover');
            });
        });
        
        ['dragleave', 'drop'].forEach(eventName => {
            uploadCard.addEventListener(eventName, () => {
                uploadCard.classList.remove('dragover');
            });
        });
        
        uploadCard.addEventListener('drop', function(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            
            if (files.length > 0) {
                fileInput.files = files;
                displayFileName(files[0]);
            }
        });
        
        // File input change
        fileInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                displayFileName(this.files[0]);
            }
        });
        
        // Display selected file
        function displayFileName(file) {
            fileName.textContent = file.name;
            selectedFile.style.display = 'inline-flex';
            importBtn.disabled = false;
            
            // Validate file size (5MB)
            if (file.size > 5 * 1024 * 1024) {
                Swal.fire({
                    icon: 'error',
                    title: 'File Too Large',
                    text: 'File size must be less than 5MB'
                });
                resetFileInput();
            }
        }
        
        // Remove file
        removeFile.addEventListener('click', function() {
            resetFileInput();
        });
        
        function resetFileInput() {
            fileInput.value = '';
            selectedFile.style.display = 'none';
            importBtn.disabled = true;
        }
        
        // Form submission
        uploadForm.addEventListener('submit', function(e) {
            if (!fileInput.files.length) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'No File Selected',
                    text: 'Please select a file to import'
                });
                return false;
            }
            
            importBtn.disabled = true;
            importBtn.innerHTML = '<i class="ri-loader-4-line ri-spin me-2"></i> Importing...';
        });
    });
    </script>

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