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

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

// Fetch insurers
$sql_insurers = "SELECT agent_id, agent_name FROM agent ORDER BY agent_name";
$result_insurers = $conn->query($sql_insurers);
$insurers = $result_insurers->fetch_all(MYSQLI_ASSOC);

// Fetch benefits
$sql_benefits = "SELECT code, benefit FROM benefit ORDER BY benefit";
$result_benefits = $conn->query($sql_benefits);
$benefits = $result_benefits->fetch_all(MYSQLI_ASSOC);

// Fetch corporates
$sql_corporates = "SELECT corp_id, corporate FROM corporate WHERE cancelled = 0 ORDER BY corporate";
$result_corporates = $conn->query($sql_corporates);
$corporates = $result_corporates->fetch_all(MYSQLI_ASSOC);

// Get available anniversary years (1-10 for example)
$years = range(1, 10);

$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Rate Sheet Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        /* Custom SweetAlert2 styling for edit rate modal */
        .swal2-popup {
            font-family: inherit !important;
        }
        
        .swal2-html-container {
            max-height: 70vh;
            overflow-y: auto;
            padding: 0.5rem 0;
        }
        
        /* Form styling */
        #editRateForm .form-label {
            margin-bottom: 0.5rem;
            color: #495057;
        }
        
        #editRateForm .form-control,
        #editRateForm .form-select {
            border-radius: 0.375rem;
            border-color: #ced4da;
            transition: all 0.15s ease-in-out;
        }
        
        #editRateForm .form-control:focus,
        #editRateForm .form-select:focus {
            border-color: #80bdff;
            box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
        }
        
        #editRateForm .input-group-text {
            border-color: #ced4da;
            color: #495057;
        }
        
        #editRateForm .input-group-text.bg-light {
            background-color: #f8f9fa;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Finance', 'title' => 'Rate Sheet Management')); ?>

                    <div class="row">
                        <div class="col-xxl-12">
                            <!-- Rate Sheet Form -->
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Add New Rate</h4>
                                </div>

                                <div class="card-body">
                                    <form id="rateForm">
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Description</label>
                                                    <input type="text" class="form-control" name="full_desc" required>
                                                </div>
                                            </div>

                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Corporate</label>
                                                    <select class="form-select" name="corp_id" id="corporateSelect">
                                                        <option value="">All Corporates</option>
                                                        <?php foreach ($corporates as $corporate): ?>
                                                            <option value="<?php echo $corporate['corp_id']; ?>">
                                                                <?php echo htmlspecialchars($corporate['corporate']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Agent Name</label>
                                                    <select class="form-select" name="agent_name" required>
                                                        <option value="">Select Agent Name</option>
                                                        <?php foreach ($insurers as $insurer): ?>
                                                            <option value="<?php echo $insurer['agent_id']; ?>">
                                                                <?php echo htmlspecialchars($insurer['agent_name']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Benefit</label>
                                                    <select class="form-select" name="benefit" required>
                                                        <option value="">Select Benefit</option>
                                                        <?php foreach ($benefits as $benefit): ?>
                                                            <option value="<?php echo $benefit['code']; ?>">
                                                                <?php echo htmlspecialchars($benefit['benefit']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Limit</label>
                                                    <input type="number" class="form-control" name="limit" 
                                                           step="0.01" min="0" required>
                                                </div>
                                            </div>

                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Premium</label>
                                                    <input type="number" class="form-control" name="premium" 
                                                           step="0.01" min="0" required>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Family Size</label>
                                                    <select class="form-select" name="family_size">
                                                        <option value="">Any Size</option>
                                                        <option value="M">M (Single person)</option>
                                                        <option value="M + 1">M + 1</option>
                                                        <option value="M + 2">M + 2</option>
                                                        <option value="M + 3">M + 3</option>
                                                        <option value="M + 4">M + 4</option>
                                                        <option value="M + 5">M + 5</option>
                                                        <option value="M + 6">M + 6</option>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Anniversary Year</label>
                                                    <select class="form-select" name="year" required>
                                                        <option value="">Select Year</option>
                                                        <?php foreach ($years as $year): ?>
                                                            <option value="<?php echo $year; ?>">
                                                                Year <?php echo $year; ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">&nbsp;</label>
                                                    <div class="d-flex justify-content-end">
                                                        <button type="submit" class="btn btn-primary">
                                                            Add Rate
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                            
                            <!-- Import Card -->
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Import Rates</h4>
                                </div>
                                
                                <div class="card-body">
                                    <form id="uploadForm" enctype="multipart/form-data">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label class="form-label">Upload Excel File</label>
                                                    <input type="file" class="form-control" name="file" 
                                                           accept=".xlsx,.xls" required>
                                                    <small class="text-muted">
                                                        Upload rates in bulk using the template format
                                                    </small>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="mb-3">
                                                    <label class="form-label">Update Existing?</label>
                                                    <select class="form-select" name="update_existing">
                                                        <option value="0">Skip existing rates</option>
                                                        <option value="1">Update existing rates</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="mb-3">
                                                    <label class="form-label">&nbsp;</label>
                                                    <button type="submit" class="btn btn-primary w-100">
                                                        Upload Rates
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                            
                                    <div class="mt-3">
                                        <a href="generate_rate_template.php" class="btn btn-soft-info btn-sm">
                                            <i class="ri-download-line align-middle"></i> Download Template
                                        </a>
                                    </div>
                                </div>
                            </div>

                            <!-- Rate Sheet Table -->
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Rate Sheet</h4>
                                    <div class="flex-shrink-0">
                                        <div class="d-flex gap-2">
                                            <select class="form-select" id="filterCorporate">
                                                <option value="">All Corporates</option>
                                                <?php foreach ($corporates as $corporate): ?>
                                                    <option value="<?php echo $corporate['corp_id']; ?>">
                                                        <?php echo htmlspecialchars($corporate['corporate']); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                            <button class="btn btn-success btn-sm" id="exportExcel">
                                                <i class="ri-file-excel-line align-bottom me-1"></i> Export
                                            </button>
                                        </div>
                                    </div>
                                </div>

                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Description</th>
                                                    <th>Corporate</th>
                                                    <th>Insurer</th>
                                                    <th>Benefit</th>
                                                    <th>Limit</th>
                                                    <th>Premium</th>
                                                    <th>Family Size</th>
                                                    <th>Year</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody id="rateTableBody">
                                                <!-- Rates will be loaded here -->
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize Select2
            $('#corporateSelect, #filterCorporate').select2({
                placeholder: "Select Corporate",
                allowClear: true
            });

            const rateForm = document.getElementById('rateForm');
            const rateTableBody = document.getElementById('rateTableBody');
            const filterCorporate = document.getElementById('filterCorporate');

            // Load rates on page load and when filter changes
            loadRates();
            filterCorporate.addEventListener('change', loadRates);

            // Handle form submission
            rateForm.addEventListener('submit', function(e) {
                e.preventDefault();

                const formData = new FormData(this);

                fetch('save_rate.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        throw new Error(data.error || 'Failed to save rate');
                    }

                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: 'Rate saved successfully!'
                    });

                    // Reset form and reload rates
                    rateForm.reset();
                    $('#corporateSelect').val('').trigger('change');
                    loadRates();
                })
                .catch(error => {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: error.message
                    });
                });
            });

            // Load rates
            function loadRates() {
                const corpId = filterCorporate.value;
                fetch('get_rates.php' + (corpId ? `?corp_id=${corpId}` : ''))
                    .then(response => response.json())
                    .then(data => {
                        if (!data.success) {
                            throw new Error(data.error || 'Failed to load rates');
                        }

                        displayRates(data.rates);
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        rateTableBody.innerHTML = `
                            <tr>
                                <td colspan="9" class="text-center text-muted">
                                    Failed to load rates: ${error.message}
                                </td>
                            </tr>
                        `;
                    });
            }

            // Display rates in table
            function displayRates(rates) {
                if (!rates.length) {
                    rateTableBody.innerHTML = `
                        <tr>
                            <td colspan="9" class="text-center text-muted">
                                No rates found
                            </td>
                        </tr>
                    `;
                    return;
                }

                // Function to format family size display
                function formatFamilySize(familySize) {
                    if (!familySize) return 'Any Size';
                    
                    const familySizeMap = {
                        'M': 'M (Single)',
                        'M + 1': 'M + 1',
                        'M + 2': 'M + 2',
                        'M + 3': 'M + 3',
                        'M + 4': 'M + 4',
                        'M + 5': 'M + 5',
                        'M + 6': 'M + 6'
                    };
                    
                    return familySizeMap[familySize] || familySize;
                }

                rateTableBody.innerHTML = rates.map(rate => `
                    <tr class="rate-row" data-id="${rate.code}">
                        <td>${rate.full_desc}</td>
                        <td>${rate.corporate_name || 'All Corporates'}</td>
                        <td>${rate.insurer_name}</td>
                        <td>${rate.benefit_name}</td>
                        <td class="text-end">${parseFloat(rate.limit).toLocaleString()}</td>
                        <td class="text-end">${parseFloat(rate.premium).toLocaleString()}</td>
                        <td>
                            <span class="badge bg-primary-subtle text-primary fs-13">
                                ${formatFamilySize(rate.family_size)}
                            </span>
                        </td>
                        <td>
                            <span class="badge bg-info-subtle text-info fs-13">
                                Year ${rate.year}
                            </span>
                        </td>
                        <td>
                            <div class="d-flex gap-2">
                                <button class="btn btn-sm btn-info edit-rate" 
                                        title="Edit" onclick="editRate('${rate.code}')">
                                    <i class="ri-edit-2-line"></i>
                                </button>
                                <button class="btn btn-sm btn-danger delete-rate" 
                                        title="Delete" onclick="deleteRate('${rate.code}')">
                                    <i class="ri-delete-bin-line"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                `).join('');
            }

// Edit rate
window.editRate = function(code) {
    fetch(`get_rate.php?id=${code}`)
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                throw new Error(data.error || 'Failed to load rate details');
            }

            // Define family size options
            const familySizeOptions = [
                { value: '', label: 'Any Size' },
                { value: 'M', label: 'M (Single person)' },
                { value: 'M + 1', label: 'M + 1 (Person + 1 dependent)' },
                { value: 'M + 2', label: 'M + 2 (Person + 2 dependents)' },
                { value: 'M + 3', label: 'M + 3 (Person + 3 dependents)' },
                { value: 'M + 4', label: 'M + 4 (Person + 4 dependents)' },
                { value: 'M + 5', label: 'M + 5 (Person + 5 dependents)' },
                { value: 'M + 6', label: 'M + 6 (Person + 6 dependents)' }
            ];
            
            // Generate year options (1-10)
            const yearOptions = Array.from({length: 10}, (_, i) => i + 1);

            // Custom CSS styles for modal
            const modalStyles = `
                <style>
                    .custom-modal .swal2-title {
                        font-size: 1.5rem !important;
                        font-weight: 600 !important;
                        color: #1f2937 !important;
                        margin-bottom: 1.5rem !important;
                    }
                    
                    .custom-modal .form-label {
                        font-weight: 500;
                        color: #4b5563;
                        margin-bottom: 0.5rem;
                        display: block;
                    }
                    
                    .custom-modal .form-control,
                    .custom-modal .form-select {
                        height: 40px;
                        padding: 0.5rem 0.75rem;
                        border-color: #d1d5db;
                        border-radius: 0.375rem;
                    }
                    
                    .custom-modal .input-group {
                        margin-bottom: 0;
                    }
                    
                    .custom-modal .input-group-text {
                        background-color: #f3f4f6;
                        border-color: #d1d5db;
                        color: #4b5563;
                    }
                    
                    .custom-modal .mb-3 {
                        margin-bottom: 1.25rem !important;
                    }
                    
                    .custom-modal .row {
                        margin-left: -10px;
                        margin-right: -10px;
                    }
                    
                    .custom-modal [class*="col-"] {
                        padding-left: 10px;
                        padding-right: 10px;
                    }
                    
                    .custom-modal .alert-info {
                        background-color: #e0f2fe;
                        border-color: #bae6fd;
                        color: #0369a1;
                        font-size: 0.875rem;
                        padding: 0.75rem 1rem;
                        border-radius: 0.375rem;
                    }
                    
                    .custom-modal .text-muted {
                        color: #6b7280 !important;
                        font-size: 0.8125rem;
                    }
                    
                    .select2-container--default .select2-selection--single {
                        height: 40px !important;
                        padding: 0.375rem 0.75rem;
                        border-color: #d1d5db !important;
                    }
                    
                    .select2-container--default .select2-selection--single .select2-selection__arrow {
                        height: 38px !important;
                    }
                    
                    .select2-dropdown {
                        border-color: #d1d5db !important;
                    }
                    
                    .select2-container {
                        width: 100% !important;
                    }
                </style>
            `;

            Swal.fire({
                title: 'Edit Rate',
                html: modalStyles + `
                    <form id="editRateForm" class="text-start">
                        <input type="hidden" name="code" value="${data.rate.code}">
                        
                        <div class="mb-3">
                            <label class="form-label">Description</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="ri-file-text-line"></i></span>
                                <input type="text" class="form-control" name="full_desc" 
                                       value="${data.rate.full_desc}" required>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Corporate</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="ri-building-line"></i></span>
                                <select class="form-select" name="corp_id" id="editCorporateSelect">
                                    <option value="">All Corporates</option>
                                    ${data.corporates.map(corp => `
                                        <option value="${corp.corp_id}" 
                                            ${data.rate.corp_id == corp.corp_id ? 'selected' : ''}>
                                            ${corp.corporate}
                                        </option>
                                    `).join('')}
                                </select>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Limit Amount</label>
                                    <div class="input-group">
                                        <span class="input-group-text">KES</span>
                                        <input type="number" class="form-control" name="limit" 
                                              value="${data.rate.limit}" step="0.01" required
                                              placeholder="0.00" min="0">
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Premium Amount</label>
                                    <div class="input-group">
                                        <span class="input-group-text">KES</span>
                                        <input type="number" class="form-control" name="premium" 
                                              value="${data.rate.premium}" step="0.01" required
                                              placeholder="0.00" min="0">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Family Size</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="ri-group-line"></i></span>
                                <select class="form-select" name="family_size" id="editFamilySizeSelect">
                                    ${familySizeOptions.map(option => `
                                        <option value="${option.value}" 
                                            ${data.rate.family_size == option.value ? 'selected' : ''}>
                                            ${option.label}
                                        </option>
                                    `).join('')}
                                </select>
                            </div>
                            <div class="form-text text-muted">
                                <i class="ri-information-line"></i> M = Main member (insured person)
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">Agent Name</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="ri-user-line"></i></span>
                                        <select class="form-select" name="agent_name" required>
                                            ${data.agents.map(agent => `
                                                <option value="${agent.agent_id}" 
                                                    ${data.rate.insurer == agent.agent_id ? 'selected' : ''}>
                                                    ${agent.agent_name}
                                                </option>
                                            `).join('')}
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">Benefit</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="ri-star-line"></i></span>
                                        <select class="form-select" name="benefit" required>
                                            ${data.benefits.map(benefit => `
                                                <option value="${benefit.code}" 
                                                    ${data.rate.benefit == benefit.code ? 'selected' : ''}>
                                                    ${benefit.benefit}
                                                </option>
                                            `).join('')}
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">Anniversary Year</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="ri-calendar-line"></i></span>
                                        <select class="form-select" name="year" required>
                                            ${yearOptions.map(year => `
                                                <option value="${year}" 
                                                    ${parseInt(data.rate.year) == year ? 'selected' : ''}>
                                                    Year ${year}
                                                </option>
                                            `).join('')}
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>

                    <div class="alert alert-info mt-3">
                        <i class="ri-information-line me-1"></i>
                        All fields with <span class="text-danger">*</span> are required
                    </div>
                `,
                width: '750px',
                padding: '2rem',
                showCancelButton: true,
                confirmButtonText: 'Save Changes',
                cancelButtonText: 'Cancel',
                confirmButtonColor: '#0ab39c',
                cancelButtonColor: '#f06548',
                customClass: {
                    container: 'custom-modal',
                    confirmButton: 'btn btn-success',
                    cancelButton: 'btn btn-danger',
                    title: 'text-primary'
                },
                buttonsStyling: false,
                didOpen: () => {
                    // Initialize Select2 for corporate dropdown
                    $('#editCorporateSelect').select2({
                        dropdownParent: $('.swal2-container'),
                        placeholder: "Select Corporate",
                        width: '100%'
                    });
                    
                    // Initialize Select2 for family size dropdown
                    $('#editFamilySizeSelect').select2({
                        dropdownParent: $('.swal2-container'),
                        placeholder: "Select Family Size",
                        width: '100%'
                    });
                    
                    // Adjust modal styling
                    $('.swal2-popup').css({
                        'max-width': '95%',
                        'border-radius': '8px'
                    });
                    
                    // Ensure form takes full width
                    $('#editRateForm').css({
                        'width': '100%'
                    });
                    
                    // Improve Select2 dropdown positioning
                    setTimeout(() => {
                        $('.select2-container--open').css('z-index', 10000);
                    }, 100);
                },
                preConfirm: () => {
                    const form = document.getElementById('editRateForm');
                    const formData = new FormData(form);
                    
                    // Validate form
                    if (!form.checkValidity()) {
                        form.reportValidity();
                        return false;
                    }
                    
                    return Object.fromEntries(formData);
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    updateRate(result.value);
                }
            });
        })
        .catch(error => {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: error.message,
                confirmButtonColor: '#0ab39c'
            });
        });
};

            // Update rate
            window.updateRate = function(rateData) {
                fetch('update_rate.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(rateData)
                })
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        throw new Error(data.error || 'Failed to update rate');
                    }

                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: 'Rate updated successfully!',
                        confirmButtonColor: '#0ab39c'
                    });

                    loadRates();
                })
                .catch(error => {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: error.message,
                        confirmButtonColor: '#0ab39c'
                    });
                });
            };

            // Delete rate
            window.deleteRate = function(code) {
                Swal.fire({
                    title: 'Are you sure?',
                    text: 'This rate will be permanently deleted',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#0ab39c',
                    confirmButtonText: 'Yes, delete it!',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        fetch('delete_rate.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({ code: code })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (!data.success) {
                                throw new Error(data.error || 'Failed to delete rate');
                            }

                            Swal.fire({
                                icon: 'success',
                                title: 'Deleted!',
                                text: 'Rate has been deleted successfully.',
                                confirmButtonColor: '#0ab39c'
                            });

                            loadRates();
                        })
                        .catch(error => {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: error.message,
                                confirmButtonColor: '#0ab39c'
                            });
                        });
                    }
                });
            };

            // Handle file upload
            const uploadForm = document.getElementById('uploadForm');
            uploadForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const formData = new FormData(this);
                
                Swal.fire({
                    title: 'Uploading...',
                    text: 'Please wait while we process your file',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                fetch('import_rates.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        throw new Error(data.error || 'Failed to import rates');
                    }
                    
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: `Imported ${data.imported} rates successfully!`,
                        confirmButtonColor: '#0ab39c'
                    });
                    
                    uploadForm.reset();
                    loadRates();
                })
                .catch(error => {
                    Swal.fire({
                        icon: 'error',
                        title: 'Import Failed',
                        text: error.message,
                        confirmButtonColor: '#0ab39c'
                    });
                });
            });

            // Export to Excel
            document.getElementById('exportExcel').addEventListener('click', function() {
                const corpId = filterCorporate.value;
                window.location.href = 'export_rates.php' + (corpId ? `?corp_id=${corpId}` : '');
            });
        });
    </script>
</body>
</html>