<?php
/**
 * Multi-Insurer Quote Comparison Engine
 * Ultrasure Insurance Platform
 * 
 * This system allows admins to configure insurer rates and agents to generate
 * comparative quotes across multiple insurers for their clients.
 */

// ============================================================================
// 1. ADMIN: INSURER RATE CONFIGURATION
// File: admin/insurer_rates.php
// ============================================================================

session_start();
include 'layouts/dbconn.php';

// Check admin permissions
if (!isset($_SESSION['user_id']) || $_SESSION['role_name'] !== 'Super Admin') {
    header('Location: login.php');
    exit();
}

// Handle rate configuration submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['configure_rates'])) {
    $company_id = $_POST['company_id'];
    $product_id = $_POST['product_id'];
    $age_bands = $_POST['age_bands']; // JSON data
    $sum_assured_bands = $_POST['sum_assured_bands']; // JSON data
    $base_rates = $_POST['base_rates']; // JSON data
    $commission_rate = $_POST['commission_rate'];
    
    // Insert or update insurer rates
    $sql = "INSERT INTO insurer_product_rates (company_id, product_id, age_bands, sum_assured_bands, 
            base_rates, commission_rate, effective_date, is_active, created_by) 
            VALUES (?, ?, ?, ?, ?, ?, CURDATE(), 1, ?)
            ON DUPLICATE KEY UPDATE 
            age_bands = VALUES(age_bands),
            sum_assured_bands = VALUES(sum_assured_bands),
            base_rates = VALUES(base_rates),
            commission_rate = VALUES(commission_rate),
            updated_at = CURRENT_TIMESTAMP";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("iisssdi", $company_id, $product_id, $age_bands, 
                     $sum_assured_bands, $base_rates, $commission_rate, $_SESSION['user_id']);
    
    if ($stmt->execute()) {
        $success_message = "Insurer rates configured successfully!";
    } else {
        $error_message = "Error configuring rates: " . $conn->error;
    }
}

// Fetch insurance companies
$companies_sql = "SELECT company_id, company_name, short_name, is_active FROM insurance_companies WHERE is_active = 1";
$companies_result = $conn->query($companies_sql);

// Fetch product categories
$categories_sql = "SELECT category_id, category_name FROM product_categories WHERE is_active = 1";
$categories_result = $conn->query($categories_sql);

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Insurer Rate Configuration - Ultrasure</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Phosphor Icons -->
    <link href="https://unpkg.com/phosphor-icons@1.4.2/src/css/icons.css" rel="stylesheet">
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<body>
    <div class="container-fluid py-4">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h4 class="mb-0">
                            <i class="ph-buildings me-2"></i>
                            Multi-Insurer Rate Configuration
                        </h4>
                        <p class="mb-0 opacity-75">Configure rates for different insurers to enable quote comparison</p>
                    </div>
                    
                    <div class="card-body">
                        <?php if (isset($success_message)): ?>
                            <div class="alert alert-success alert-dismissible fade show">
                                <i class="ph-check-circle me-2"></i><?php echo $success_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>
                        
                        <?php if (isset($error_message)): ?>
                            <div class="alert alert-danger alert-dismissible fade show">
                                <i class="ph-warning me-2"></i><?php echo $error_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>

                        <!-- Rate Configuration Form -->
                        <form method="POST" id="rateConfigForm">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Insurance Company</label>
                                    <select name="company_id" class="form-select" required>
                                        <option value="">Select Insurance Company</option>
                                        <?php while ($company = $companies_result->fetch_assoc()): ?>
                                            <option value="<?php echo $company['company_id']; ?>">
                                                <?php echo $company['company_name']; ?>
                                            </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Product Category</label>
                                    <select name="category_id" class="form-select" required>
                                        <option value="">Select Product Category</option>
                                        <?php while ($category = $categories_result->fetch_assoc()): ?>
                                            <option value="<?php echo $category['category_id']; ?>">
                                                <?php echo $category['category_name']; ?>
                                            </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Product</label>
                                    <select name="product_id" class="form-select" required>
                                        <option value="">Select Product</option>
                                        <!-- Populated via AJAX based on category selection -->
                                    </select>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Commission Rate (%)</label>
                                    <input type="number" name="commission_rate" class="form-control" 
                                           step="0.01" min="0" max="50" required>
                                </div>
                            </div>

                            <!-- Age Band Configuration -->
                            <div class="card mt-4">
                                <div class="card-header">
                                    <h5 class="mb-0">Age Band Rates</h5>
                                    <small class="text-muted">Configure premium rates for different age groups</small>
                                </div>
                                <div class="card-body">
                                    <div id="ageBands">
                                        <div class="row age-band-row">
                                            <div class="col-md-2">
                                                <label class="form-label">Min Age</label>
                                                <input type="number" class="form-control age-min" min="0" max="100" required>
                                            </div>
                                            <div class="col-md-2">
                                                <label class="form-label">Max Age</label>
                                                <input type="number" class="form-control age-max" min="0" max="100" required>
                                            </div>
                                            <div class="col-md-3">
                                                <label class="form-label">Base Rate (KSH)</label>
                                                <input type="number" class="form-control base-rate" step="0.01" min="0" required>
                                            </div>
                                            <div class="col-md-3">
                                                <label class="form-label">Rate per 1000 Sum Assured</label>
                                                <input type="number" class="form-control rate-per-thousand" step="0.01" min="0" required>
                                            </div>
                                            <div class="col-md-2">
                                                <label class="form-label">&nbsp;</label>
                                                <button type="button" class="btn btn-outline-danger w-100 remove-age-band">
                                                    <i class="ph-trash"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <button type="button" class="btn btn-outline-primary mt-3" id="addAgeBand">
                                        <i class="ph-plus me-2"></i>Add Age Band
                                    </button>
                                </div>
                            </div>

                            <!-- Sum Assured Bands -->
                            <div class="card mt-4">
                                <div class="card-header">
                                    <h5 class="mb-0">Sum Assured Multipliers</h5>
                                    <small class="text-muted">Configure rate multipliers for different sum assured ranges</small>
                                </div>
                                <div class="card-body">
                                    <div id="sumAssuredBands">
                                        <div class="row sum-assured-row">
                                            <div class="col-md-3">
                                                <label class="form-label">Min Sum Assured</label>
                                                <input type="number" class="form-control sum-min" step="1000" min="0" required>
                                            </div>
                                            <div class="col-md-3">
                                                <label class="form-label">Max Sum Assured</label>
                                                <input type="number" class="form-control sum-max" step="1000" min="0" required>
                                            </div>
                                            <div class="col-md-3">
                                                <label class="form-label">Rate Multiplier</label>
                                                <input type="number" class="form-control rate-multiplier" step="0.01" min="0.1" max="5" value="1" required>
                                            </div>
                                            <div class="col-md-3">
                                                <label class="form-label">&nbsp;</label>
                                                <button type="button" class="btn btn-outline-danger w-100 remove-sum-band">
                                                    <i class="ph-trash"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <button type="button" class="btn btn-outline-primary mt-3" id="addSumBand">
                                        <i class="ph-plus me-2"></i>Add Sum Assured Band
                                    </button>
                                </div>
                            </div>

                            <div class="mt-4">
                                <button type="submit" name="configure_rates" class="btn btn-primary">
                                    <i class="ph-floppy-disk me-2"></i>Save Rate Configuration
                                </button>
                                <button type="button" class="btn btn-outline-secondary ms-2" onclick="resetForm()">
                                    <i class="ph-arrow-clockwise me-2"></i>Reset Form
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Existing Configurations -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Existing Rate Configurations</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped" id="ratesTable">
                                <thead>
                                    <tr>
                                        <th>Insurance Company</th>
                                        <th>Product</th>
                                        <th>Commission Rate</th>
                                        <th>Age Bands</th>
                                        <th>Sum Assured Bands</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $rates_sql = "SELECT ipr.*, ic.company_name, ip.product_name, pc.category_name 
                                                 FROM insurer_product_rates ipr
                                                 JOIN insurance_companies ic ON ipr.company_id = ic.company_id
                                                 JOIN insurance_products ip ON ipr.product_id = ip.product_id
                                                 JOIN product_categories pc ON ip.category_id = pc.category_id
                                                 ORDER BY ic.company_name, pc.category_name, ip.product_name";
                                    $rates_result = $conn->query($rates_sql);
                                    
                                    while ($rate = $rates_result->fetch_assoc()):
                                        $age_bands = json_decode($rate['age_bands'], true);
                                        $sum_bands = json_decode($rate['sum_assured_bands'], true);
                                    ?>
                                        <tr>
                                            <td><?php echo $rate['company_name']; ?></td>
                                            <td>
                                                <div><?php echo $rate['product_name']; ?></div>
                                                <small class="text-muted"><?php echo $rate['category_name']; ?></small>
                                            </td>
                                            <td><?php echo $rate['commission_rate']; ?>%</td>
                                            <td><?php echo count($age_bands); ?> bands</td>
                                            <td><?php echo count($sum_bands); ?> bands</td>
                                            <td>
                                                <span class="badge bg-<?php echo $rate['is_active'] ? 'success' : 'secondary'; ?>">
                                                    <?php echo $rate['is_active'] ? 'Active' : 'Inactive'; ?>
                                                </span>
                                            </td>
                                            <td>
                                                <button class="btn btn-sm btn-outline-primary" onclick="editRate(<?php echo $rate['rate_id']; ?>)">
                                                    <i class="ph-pencil"></i>
                                                </button>
                                                <button class="btn btn-sm btn-outline-danger" onclick="deleteRate(<?php echo $rate['rate_id']; ?>)">
                                                    <i class="ph-trash"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>

    <script>
    $(document).ready(function() {
        // Initialize DataTable
        $('#ratesTable').DataTable({
            responsive: true,
            pageLength: 25
        });

        // Load products based on category selection
        $('select[name="category_id"]').change(function() {
            const categoryId = $(this).val();
            const productSelect = $('select[name="product_id"]');
            
            productSelect.html('<option value="">Select Product</option>');
            
            if (categoryId) {
                $.ajax({
                    url: 'api/get_products.php',
                    method: 'POST',
                    data: { category_id: categoryId },
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            response.products.forEach(function(product) {
                                productSelect.append(`<option value="${product.product_id}">${product.product_name}</option>`);
                            });
                        }
                    }
                });
            }
        });

        // Add age band row
        $('#addAgeBand').click(function() {
            const ageBandHtml = `
                <div class="row age-band-row mt-3">
                    <div class="col-md-2">
                        <input type="number" class="form-control age-min" min="0" max="100" required>
                    </div>
                    <div class="col-md-2">
                        <input type="number" class="form-control age-max" min="0" max="100" required>
                    </div>
                    <div class="col-md-3">
                        <input type="number" class="form-control base-rate" step="0.01" min="0" required>
                    </div>
                    <div class="col-md-3">
                        <input type="number" class="form-control rate-per-thousand" step="0.01" min="0" required>
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-outline-danger w-100 remove-age-band">
                            <i class="ph-trash"></i>
                        </button>
                    </div>
                </div>
            `;
            $('#ageBands').append(ageBandHtml);
        });

        // Remove age band row
        $(document).on('click', '.remove-age-band', function() {
            if ($('.age-band-row').length > 1) {
                $(this).closest('.age-band-row').remove();
            } else {
                Swal.fire('Error', 'At least one age band is required', 'error');
            }
        });

        // Add sum assured band row
        $('#addSumBand').click(function() {
            const sumBandHtml = `
                <div class="row sum-assured-row mt-3">
                    <div class="col-md-3">
                        <input type="number" class="form-control sum-min" step="1000" min="0" required>
                    </div>
                    <div class="col-md-3">
                        <input type="number" class="form-control sum-max" step="1000" min="0" required>
                    </div>
                    <div class="col-md-3">
                        <input type="number" class="form-control rate-multiplier" step="0.01" min="0.1" max="5" value="1" required>
                    </div>
                    <div class="col-md-3">
                        <button type="button" class="btn btn-outline-danger w-100 remove-sum-band">
                            <i class="ph-trash"></i>
                        </button>
                    </div>
                </div>
            `;
            $('#sumAssuredBands').append(sumBandHtml);
        });

        // Remove sum assured band row
        $(document).on('click', '.remove-sum-band', function() {
            if ($('.sum-assured-row').length > 1) {
                $(this).closest('.sum-assured-row').remove();
            } else {
                Swal.fire('Error', 'At least one sum assured band is required', 'error');
            }
        });

        // Form submission
        $('#rateConfigForm').submit(function(e) {
            e.preventDefault();
            
            // Collect age bands data
            const ageBands = [];
            $('.age-band-row').each(function() {
                const ageMin = $(this).find('.age-min').val();
                const ageMax = $(this).find('.age-max').val();
                const baseRate = $(this).find('.base-rate').val();
                const ratePerThousand = $(this).find('.rate-per-thousand').val();
                
                if (ageMin && ageMax && baseRate && ratePerThousand) {
                    ageBands.push({
                        age_min: parseInt(ageMin),
                        age_max: parseInt(ageMax),
                        base_rate: parseFloat(baseRate),
                        rate_per_thousand: parseFloat(ratePerThousand)
                    });
                }
            });

            // Collect sum assured bands data
            const sumBands = [];
            $('.sum-assured-row').each(function() {
                const sumMin = $(this).find('.sum-min').val();
                const sumMax = $(this).find('.sum-max').val();
                const multiplier = $(this).find('.rate-multiplier').val();
                
                if (sumMin && sumMax && multiplier) {
                    sumBands.push({
                        sum_min: parseFloat(sumMin),
                        sum_max: parseFloat(sumMax),
                        multiplier: parseFloat(multiplier)
                    });
                }
            });

            // Add JSON data to form
            $('<input>').attr({
                type: 'hidden',
                name: 'age_bands',
                value: JSON.stringify(ageBands)
            }).appendTo(this);

            $('<input>').attr({
                type: 'hidden',
                name: 'sum_assured_bands',
                value: JSON.stringify(sumBands)
            }).appendTo(this);

            // Submit form
            this.submit();
        });
    });

    function resetForm() {
        document.getElementById('rateConfigForm').reset();
        $('.age-band-row:not(:first)').remove();
        $('.sum-assured-row:not(:first)').remove();
    }

    function editRate(rateId) {
        // Implementation for editing rates
        Swal.fire('Info', 'Edit functionality to be implemented', 'info');
    }

    function deleteRate(rateId) {
        Swal.fire({
            title: 'Are you sure?',
            text: 'This will delete the rate configuration permanently',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                // Implement delete functionality
                Swal.fire('Info', 'Delete functionality to be implemented', 'info');
            }
        });
    }
    </script>
</body>
</html>
