<?php
/**
 * Agent Multi-Insurer Quote Comparison Interface
 * File: quotes/multi_insurer_comparison.php
 * 
 * This interface allows agents to generate comparative quotes from multiple insurers
 * and present them to clients in a professional format.
 */

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

// Check agent permissions
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role_name'], ['Super Admin', 'Insurance Agent', 'Senior Agent'])) {
    header('Location: ../login.php');
    exit();
}

$agent_id = $_SESSION['user_id'];
$agent_name = $_SESSION['full_name'];

// Handle quote generation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_quotes'])) {
    $customer_data = [
        'first_name' => $_POST['first_name'],
        'last_name' => $_POST['last_name'],
        'email' => $_POST['email'],
        'phone' => $_POST['phone'],
        'date_of_birth' => $_POST['date_of_birth'],
        'gender' => $_POST['gender']
    ];
    
    $quote_params = [
        'product_category' => $_POST['product_category'],
        'sum_assured' => (float)$_POST['sum_assured'],
        'policy_term' => (int)$_POST['policy_term'],
        'premium_frequency' => $_POST['premium_frequency'],
        'dependents' => isset($_POST['dependents']) ? $_POST['dependents'] : []
    ];
    
    $selected_insurers = $_POST['selected_insurers'] ?? [];
    
    if (!empty($selected_insurers)) {
        // Generate comparison number
        $comparison_number = 'CMP-' . date('Ymd') . '-' . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
        
        // Calculate quotes for each selected insurer
        $insurer_quotes = generateMultiInsurerQuotes($conn, $customer_data, $quote_params, $selected_insurers);
        
        // Store comparison in database
        $customer_details_json = json_encode($customer_data);
        $quote_params_json = json_encode($quote_params);
        $insurer_quotes_json = json_encode($insurer_quotes);
        $valid_until = date('Y-m-d H:i:s', strtotime('+30 days'));
        
        $insert_sql = "INSERT INTO multi_insurer_quotes (comparison_number, agent_id, product_category, 
                      customer_details, quote_parameters, insurer_quotes, status, valid_until) 
                      VALUES (?, ?, ?, ?, ?, ?, 'ACTIVE', ?)";
        
        $stmt = $conn->prepare($insert_sql);
        $stmt->bind_param("sisssss", $comparison_number, $agent_id, $quote_params['product_category'],
                         $customer_details_json, $quote_params_json, $insurer_quotes_json, $valid_until);
        
        if ($stmt->execute()) {
            $comparison_id = $conn->insert_id;
            $success_message = "Multi-insurer quotes generated successfully!";
            $generated_quotes = $insurer_quotes;
        } else {
            $error_message = "Error generating quotes: " . $conn->error;
        }
    } else {
        $error_message = "Please select at least one insurer for comparison.";
    }
}

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

// Fetch available insurers with active rates
$insurers_sql = "SELECT DISTINCT ic.company_id, ic.company_name, ic.short_name, ic.logo_url
                FROM insurance_companies ic
                JOIN insurer_product_rates ipr ON ic.company_id = ipr.company_id
                WHERE ic.is_active = 1 AND ipr.is_active = 1
                ORDER BY ic.company_name";
$insurers_result = $conn->query($insurers_sql);

/**
 * Generate quotes from multiple insurers
 */
function generateMultiInsurerQuotes($conn, $customer_data, $quote_params, $selected_insurers) {
    $quotes = [];
    $customer_age = calculateAge($customer_data['date_of_birth']);
    
    foreach ($selected_insurers as $company_id) {
        // Get insurer details and rates
        $insurer_sql = "SELECT ic.*, ipr.age_bands, ipr.sum_assured_bands, ipr.commission_rate
                       FROM insurance_companies ic
                       JOIN insurer_product_rates ipr ON ic.company_id = ipr.company_id
                       JOIN insurance_products ip ON ipr.product_id = ip.product_id
                       JOIN product_categories pc ON ip.category_id = pc.category_id
                       WHERE ic.company_id = ? AND pc.category_code = ? AND ipr.is_active = 1
                       LIMIT 1";
        
        $stmt = $conn->prepare($insurer_sql);
        $stmt->bind_param("is", $company_id, $quote_params['product_category']);
        $stmt->execute();
        $insurer_data = $stmt->get_result()->fetch_assoc();
        
        if ($insurer_data) {
            $quote = calculateInsurerQuote($insurer_data, $customer_data, $quote_params, $customer_age);
            $quotes[] = $quote;
        }
    }
    
    // Sort quotes by premium amount (lowest first)
    usort($quotes, function($a, $b) {
        return $a['annual_premium'] <=> $b['annual_premium'];
    });
    
    return $quotes;
}

/**
 * Calculate quote for a specific insurer
 */
function calculateInsurerQuote($insurer_data, $customer_data, $quote_params, $customer_age) {
    $age_bands = json_decode($insurer_data['age_bands'], true);
    $sum_bands = json_decode($insurer_data['sum_assured_bands'], true);
    
    // Find applicable age band
    $age_rate = null;
    foreach ($age_bands as $band) {
        if ($customer_age >= $band['age_min'] && $customer_age <= $band['age_max']) {
            $age_rate = $band;
            break;
        }
    }
    
    // Find applicable sum assured band
    $sum_multiplier = 1.0;
    foreach ($sum_bands as $band) {
        if ($quote_params['sum_assured'] >= $band['sum_min'] && $quote_params['sum_assured'] <= $band['sum_max']) {
            $sum_multiplier = $band['multiplier'];
            break;
        }
    }
    
    if (!$age_rate) {
        throw new Exception("No age band found for age {$customer_age}");
    }
    
    // Calculate base premium
    $base_premium = $age_rate['base_rate'];
    $sum_assured_premium = ($quote_params['sum_assured'] / 1000) * $age_rate['rate_per_thousand'];
    $adjusted_premium = ($base_premium + $sum_assured_premium) * $sum_multiplier;
    
    // Apply gender loading (example: 10% loading for males in some products)
    $gender_loading = ($customer_data['gender'] === 'MALE') ? 1.1 : 1.0;
    $final_premium = $adjusted_premium * $gender_loading;
    
    // Calculate premiums for different frequencies
    $annual_premium = $final_premium;
    $monthly_premium = $annual_premium / 12;
    $quarterly_premium = $annual_premium / 4;
    $semi_annual_premium = $annual_premium / 2;
    
    // Calculate commission
    $commission_amount = ($annual_premium * $insurer_data['commission_rate']) / 100;
    
    return [
        'company_id' => $insurer_data['company_id'],
        'company_name' => $insurer_data['company_name'],
        'short_name' => $insurer_data['short_name'],
        'logo_url' => $insurer_data['logo_url'],
        'annual_premium' => round($annual_premium, 2),
        'monthly_premium' => round($monthly_premium, 2),
        'quarterly_premium' => round($quarterly_premium, 2),
        'semi_annual_premium' => round($semi_annual_premium, 2),
        'commission_rate' => $insurer_data['commission_rate'],
        'commission_amount' => round($commission_amount, 2),
        'age_band_used' => $age_rate,
        'sum_multiplier_used' => $sum_multiplier,
        'calculation_details' => [
            'base_premium' => $base_premium,
            'sum_assured_premium' => $sum_assured_premium,
            'gender_loading' => $gender_loading,
            'final_calculation' => "({$base_premium} + {$sum_assured_premium}) × {$sum_multiplier} × {$gender_loading} = {$final_premium}"
        ]
    ];
}

/**
 * Calculate age from date of birth
 */
function calculateAge($date_of_birth) {
    $dob = new DateTime($date_of_birth);
    $today = new DateTime();
    return $today->diff($dob)->y;
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multi-Insurer Quote Comparison - 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">
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        .insurer-card {
            border: 2px solid #e9ecef;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .insurer-card:hover {
            border-color: #0d6efd;
            box-shadow: 0 4px 12px rgba(13, 110, 253, 0.15);
        }
        .insurer-card.selected {
            border-color: #0d6efd;
            background-color: #f8f9ff;
        }
        .quote-result-card {
            border-left: 4px solid #0d6efd;
            margin-bottom: 1rem;
        }
        .quote-result-card.best-quote {
            border-left-color: #198754;
            background-color: #f8fff8;
        }
        .premium-display {
            font-size: 1.5rem;
            font-weight: bold;
            color: #0d6efd;
        }
        .best-quote .premium-display {
            color: #198754;
        }
        .calculation-details {
            font-size: 0.85rem;
            color: #6c757d;
        }
        .step-indicator {
            display: flex;
            justify-content: center;
            margin-bottom: 2rem;
        }
        .step {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 1rem;
            position: relative;
        }
        .step.active {
            background-color: #0d6efd;
            color: white;
        }
        .step.completed {
            background-color: #198754;
            color: white;
        }
        .step::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 100%;
            width: 2rem;
            height: 2px;
            background-color: #e9ecef;
            transform: translateY(-50%);
        }
        .step:last-child::after {
            display: none;
        }
        .step.completed::after {
            background-color: #198754;
        }
    </style>
</head>

<body>
    <div class="container-fluid py-4">
        <!-- Step Indicator -->
        <div class="step-indicator">
            <div class="step active" data-step="1">
                <i class="ph-user"></i>
            </div>
            <div class="step" data-step="2">
                <i class="ph-buildings"></i>
            </div>
            <div class="step" data-step="3">
                <i class="ph-calculator"></i>
            </div>
        </div>

        <?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; ?>

        <!-- Quote Generation Form -->
        <?php if (!isset($generated_quotes)): ?>
        <div class="row">
            <div class="col-lg-8 mx-auto">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h4 class="mb-0">
                            <i class="ph-chart-bar me-2"></i>
                            Multi-Insurer Quote Comparison
                        </h4>
                        <p class="mb-0 opacity-75">Generate comparative quotes from multiple insurance companies</p>
                    </div>

                    <div class="card-body">
                        <form method="POST" id="quoteForm">
                            <!-- Step 1: Customer Information -->
                            <div class="step-content" id="step1">
                                <h5 class="mb-4">
                                    <i class="ph-user me-2"></i>Customer Information
                                </h5>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">First Name</label>
                                        <input type="text" name="first_name" class="form-control" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Last Name</label>
                                        <input type="text" name="last_name" class="form-control" required>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Email</label>
                                        <input type="email" name="email" class="form-control">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Phone Number</label>
                                        <input type="tel" name="phone" class="form-control" required>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Date of Birth</label>
                                        <input type="date" name="date_of_birth" class="form-control" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Gender</label>
                                        <select name="gender" class="form-select" required>
                                            <option value="">Select Gender</option>
                                            <option value="MALE">Male</option>
                                            <option value="FEMALE">Female</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Product Category</label>
                                        <select name="product_category" class="form-select" required>
                                            <option value="">Select Product Category</option>
                                            <?php while ($category = $categories_result->fetch_assoc()): ?>
                                                <option value="<?php echo $category['category_code']; ?>">
                                                    <?php echo $category['category_name']; ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Sum Assured (KSH)</label>
                                        <input type="number" name="sum_assured" class="form-control" 
                                               min="10000" step="1000" required>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Policy Term (Years)</label>
                                        <select name="policy_term" class="form-select" required>
                                            <option value="1">1 Year</option>
                                            <option value="2">2 Years</option>
                                            <option value="3">3 Years</option>
                                            <option value="5">5 Years</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Premium Frequency</label>
                                        <select name="premium_frequency" class="form-select" required>
                                            <option value="ANNUAL">Annual</option>
                                            <option value="SEMI_ANNUAL">Semi-Annual</option>
                                            <option value="QUARTERLY">Quarterly</option>
                                            <option value="MONTHLY">Monthly</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="text-end">
                                    <button type="button" class="btn btn-primary" onclick="nextStep(2)">
                                        Next: Select Insurers <i class="ph-arrow-right ms-1"></i>
                                    </button>
                                </div>
                            </div>

                            <!-- Step 2: Insurer Selection -->
                            <div class="step-content d-none" id="step2">
                                <h5 class="mb-4">
                                    <i class="ph-buildings me-2"></i>Select Insurance Companies
                                </h5>
                                
                                <p class="text-muted mb-4">Choose the insurance companies you want to compare quotes from:</p>
                                
                                <div class="row">
                                    <?php 
                                    $insurers_result->data_seek(0); // Reset result pointer
                                    while ($insurer = $insurers_result->fetch_assoc()): 
                                    ?>
                                        <div class="col-md-6 col-lg-4 mb-3">
                                            <div class="card insurer-card h-100" onclick="toggleInsurer(<?php echo $insurer['company_id']; ?>)">
                                                <div class="card-body text-center">
                                                    <input type="checkbox" name="selected_insurers[]" 
                                                           value="<?php echo $insurer['company_id']; ?>" 
                                                           id="insurer_<?php echo $insurer['company_id']; ?>" 
                                                           class="form-check-input d-none">
                                                    
                                                    <?php if ($insurer['logo_url']): ?>
                                                        <img src="<?php echo $insurer['logo_url']; ?>" 
                                                             alt="<?php echo $insurer['company_name']; ?>" 
                                                             class="img-fluid mb-3" style="max-height: 60px;">
                                                    <?php else: ?>
                                                        <div class="bg-light rounded p-3 mb-3">
                                                            <i class="ph-buildings fs-1 text-muted"></i>
                                                        </div>
                                                    <?php endif; ?>
                                                    
                                                    <h6 class="card-title"><?php echo $insurer['company_name']; ?></h6>
                                                    <p class="card-text text-muted small"><?php echo $insurer['short_name']; ?></p>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endwhile; ?>
                                </div>

                                <div class="d-flex justify-content-between">
                                    <button type="button" class="btn btn-outline-secondary" onclick="prevStep(1)">
                                        <i class="ph-arrow-left me-1"></i> Back
                                    </button>
                                    <button type="button" class="btn btn-primary" onclick="nextStep(3)">
                                        Generate Quotes <i class="ph-calculator ms-1"></i>
                                    </button>
                                </div>
                            </div>

                            <!-- Step 3: Review and Generate -->
                            <div class="step-content d-none" id="step3">
                                <h5 class="mb-4">
                                    <i class="ph-calculator me-2"></i>Review and Generate Quotes
                                </h5>

                                <div class="card bg-light mb-4">
                                    <div class="card-body">
                                        <h6>Quote Summary</h6>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <p class="mb-1"><strong>Customer:</strong> <span id="review-customer"></span></p>
                                                <p class="mb-1"><strong>Product:</strong> <span id="review-product"></span></p>
                                                <p class="mb-1"><strong>Sum Assured:</strong> <span id="review-sum"></span></p>
                                            </div>
                                            <div class="col-md-6">
                                                <p class="mb-1"><strong>Age:</strong> <span id="review-age"></span></p>
                                                <p class="mb-1"><strong>Policy Term:</strong> <span id="review-term"></span></p>
                                                <p class="mb-1"><strong>Selected Insurers:</strong> <span id="review-insurers"></span></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="d-flex justify-content-between">
                                    <button type="button" class="btn btn-outline-secondary" onclick="prevStep(2)">
                                        <i class="ph-arrow-left me-1"></i> Back
                                    </button>
                                    <button type="submit" name="generate_quotes" class="btn btn-success">
                                        <i class="ph-lightning me-1"></i> Generate Comparative Quotes
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <?php else: ?>
        <!-- Quote Results Display -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-success text-white d-print-none">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h4 class="mb-0">
                                    <i class="ph-check-circle me-2"></i>
                                    Multi-Insurer Quote Comparison Results
                                </h4>
                                <p class="mb-0 opacity-75">Comparison generated on <?php echo date('F j, Y \a\t g:i A'); ?></p>
                            </div>
                            <div>
                                <button class="btn btn-light btn-sm me-2" onclick="window.print()">
                                    <i class="ph-printer me-1"></i> Print
                                </button>
                                <button class="btn btn-outline-light btn-sm" onclick="exportToPDF()">
                                    <i class="ph-file-pdf me-1"></i> Export PDF
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="card-body">
                        <!-- Customer Information Header -->
                        <div class="row mb-4">
                            <div class="col-lg-8">
                                <h5>Quote prepared for:</h5>
                                <div class="row">
                                    <div class="col-md-6">
                                        <p class="mb-1"><strong>Name:</strong> <?php echo $customer_data['first_name'] . ' ' . $customer_data['last_name']; ?></p>
                                        <p class="mb-1"><strong>Email:</strong> <?php echo $customer_data['email']; ?></p>
                                        <p class="mb-1"><strong>Phone:</strong> <?php echo $customer_data['phone']; ?></p>
                                    </div>
                                    <div class="col-md-6">
                                        <p class="mb-1"><strong>Age:</strong> <?php echo calculateAge($customer_data['date_of_birth']); ?> years</p>
                                        <p class="mb-1"><strong>Gender:</strong> <?php echo ucfirst(strtolower($customer_data['gender'])); ?></p>
                                        <p class="mb-1"><strong>Product:</strong> <?php echo $quote_params['product_category']; ?></p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-4 text-end">
                                <div class="bg-light p-3 rounded">
                                    <h6>Coverage Details</h6>
                                    <p class="mb-1"><strong>Sum Assured:</strong> KSH <?php echo number_format($quote_params['sum_assured']); ?></p>
                                    <p class="mb-1"><strong>Policy Term:</strong> <?php echo $quote_params['policy_term']; ?> Year(s)</p>
                                    <p class="mb-0"><strong>Premium Frequency:</strong> <?php echo ucfirst(str_replace('_', ' ', strtolower($quote_params['premium_frequency']))); ?></p>
                                </div>
                            </div>
                        </div>

                        <!-- Quote Comparison Results -->
                        <h5 class="mb-3">Premium Comparison</h5>
                        <div class="row">
                            <?php foreach ($generated_quotes as $index => $quote): ?>
                                <div class="col-lg-6 mb-3">
                                    <div class="card quote-result-card <?php echo $index === 0 ? 'best-quote' : ''; ?>">
                                        <div class="card-body">
                                            <?php if ($index === 0): ?>
                                                <div class="badge bg-success float-end">Best Quote</div>
                                            <?php endif; ?>
                                            
                                            <div class="d-flex align-items-center mb-3">
                                                <?php if ($quote['logo_url']): ?>
                                                    <img src="<?php echo $quote['logo_url']; ?>" 
                                                         alt="<?php echo $quote['company_name']; ?>" 
                                                         class="me-3" style="max-height: 40px;">
                                                <?php endif; ?>
                                                <div>
                                                    <h6 class="mb-0"><?php echo $quote['company_name']; ?></h6>
                                                    <small class="text-muted"><?php echo $quote['short_name']; ?></small>
                                                </div>
                                            </div>

                                            <div class="premium-display mb-2">
                                                KSH <?php 
                                                    $premium_key = strtolower($quote_params['premium_frequency']) . '_premium';
                                                    echo number_format($quote[$premium_key], 2); 
                                                ?>
                                                <small class="text-muted fs-6">/ <?php echo ucfirst(str_replace('_', ' ', strtolower($quote_params['premium_frequency']))); ?></small>
                                            </div>

                                            <div class="row small mb-3">
                                                <div class="col-6">
                                                    <strong>Annual:</strong> KSH <?php echo number_format($quote['annual_premium'], 2); ?>
                                                </div>
                                                <div class="col-6">
                                                    <strong>Monthly:</strong> KSH <?php echo number_format($quote['monthly_premium'], 2); ?>
                                                </div>
                                            </div>

                                            <div class="calculation-details">
                                                <strong>Commission:</strong> <?php echo $quote['commission_rate']; ?>% 
                                                (KSH <?php echo number_format($quote['commission_amount'], 2); ?>)
                                            </div>

                                            <div class="mt-3">
                                                <button class="btn btn-sm btn-outline-primary" onclick="selectQuote(<?php echo $quote['company_id']; ?>)">
                                                    <i class="ph-check me-1"></i> Select This Quote
                                                </button>
                                                <button class="btn btn-sm btn-outline-secondary" onclick="showCalculationDetails(<?php echo $index; ?>)">
                                                    <i class="ph-info me-1"></i> Details
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <!-- Actions -->
                        <div class="row mt-4 d-print-none">
                            <div class="col-12">
                                <div class="bg-light p-3 rounded">
                                    <h6>Next Steps</h6>
                                    <div class="btn-group" role="group">
                                        <button class="btn btn-primary" onclick="convertToPolicy()">
                                            <i class="ph-shield-check me-1"></i> Convert to Policy
                                        </button>
                                        <button class="btn btn-outline-primary" onclick="saveAsQuote()">
                                            <i class="ph-floppy-disk me-1"></i> Save as Quote
                                        </button>
                                        <button class="btn btn-outline-secondary" onclick="emailToCustomer()">
                                            <i class="ph-envelope me-1"></i> Email to Customer
                                        </button>
                                        <button class="btn btn-outline-secondary" onclick="shareViaWhatsApp()">
                                            <i class="ph-whatsapp-logo me-1"></i> Share via WhatsApp
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card-footer text-muted d-print-none">
                        <small>
                            <i class="ph-info me-1"></i>
                            This quote is valid for 30 days from the date of generation. 
                            Premium rates are subject to underwriting and final approval by the selected insurance company.
                            Generated by <?php echo $agent_name; ?> (Agent Code: <?php echo $_SESSION['agent_code']; ?>)
                        </small>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </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://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

    <script>
    let currentStep = 1;

    function nextStep(step) {
        // Validate current step
        if (step === 2 && !validateStep1()) {
            return;
        }
        if (step === 3 && !validateStep2()) {
            return;
        }

        // Hide current step
        document.getElementById(`step${currentStep}`).classList.add('d-none');
        
        // Show next step
        document.getElementById(`step${step}`).classList.remove('d-none');
        
        // Update step indicators
        updateStepIndicators(step);
        
        // Update review if going to step 3
        if (step === 3) {
            updateReview();
        }
        
        currentStep = step;
    }

    function prevStep(step) {
        document.getElementById(`step${currentStep}`).classList.add('d-none');
        document.getElementById(`step${step}`).classList.remove('d-none');
        updateStepIndicators(step);
        currentStep = step;
    }

    function validateStep1() {
        const requiredFields = ['first_name', 'last_name', 'phone', 'date_of_birth', 'gender', 'product_category', 'sum_assured'];
        let isValid = true;

        requiredFields.forEach(field => {
            const input = document.querySelector(`[name="${field}"]`);
            if (!input.value.trim()) {
                input.classList.add('is-invalid');
                isValid = false;
            } else {
                input.classList.remove('is-invalid');
            }
        });

        if (!isValid) {
            Swal.fire('Error', 'Please fill in all required fields', 'error');
        }

        return isValid;
    }

    function validateStep2() {
        const selectedInsurers = document.querySelectorAll('input[name="selected_insurers[]"]:checked');
        if (selectedInsurers.length === 0) {
            Swal.fire('Error', 'Please select at least one insurance company', 'error');
            return false;
        }
        return true;
    }

    function updateStepIndicators(activeStep) {
        document.querySelectorAll('.step').forEach((step, index) => {
            const stepNumber = index + 1;
            step.classList.remove('active', 'completed');
            
            if (stepNumber < activeStep) {
                step.classList.add('completed');
            } else if (stepNumber === activeStep) {
                step.classList.add('active');
            }
        });
    }

    function toggleInsurer(companyId) {
        const checkbox = document.getElementById(`insurer_${companyId}`);
        const card = checkbox.closest('.insurer-card');
        
        checkbox.checked = !checkbox.checked;
        
        if (checkbox.checked) {
            card.classList.add('selected');
        } else {
            card.classList.remove('selected');
        }
    }

    function updateReview() {
        const firstName = document.querySelector('[name="first_name"]').value;
        const lastName = document.querySelector('[name="last_name"]').value;
        const dob = document.querySelector('[name="date_of_birth"]').value;
        const productCategory = document.querySelector('[name="product_category"]').value;
        const sumAssured = document.querySelector('[name="sum_assured"]').value;
        const policyTerm = document.querySelector('[name="policy_term"]').value;
        
        // Calculate age
        const age = calculateAge(dob);
        
        // Get selected insurers
        const selectedInsurers = [];
        document.querySelectorAll('input[name="selected_insurers[]"]:checked').forEach(checkbox => {
            const card = checkbox.closest('.insurer-card');
            const companyName = card.querySelector('.card-title').textContent;
            selectedInsurers.push(companyName);
        });

        // Update review display
        document.getElementById('review-customer').textContent = `${firstName} ${lastName}`;
        document.getElementById('review-product').textContent = productCategory;
        document.getElementById('review-sum').textContent = `KSH ${parseInt(sumAssured).toLocaleString()}`;
        document.getElementById('review-age').textContent = `${age} years`;
        document.getElementById('review-term').textContent = `${policyTerm} year(s)`;
        document.getElementById('review-insurers').textContent = selectedInsurers.join(', ');
    }

    function calculateAge(dateOfBirth) {
        const dob = new Date(dateOfBirth);
        const today = new Date();
        let age = today.getFullYear() - dob.getFullYear();
        const monthDiff = today.getMonth() - dob.getMonth();
        
        if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < dob.getDate())) {
            age--;
        }
        
        return age;
    }

    // Quote result functions
    function selectQuote(companyId) {
        Swal.fire({
            title: 'Select Quote',
            text: 'Do you want to proceed with this quote?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, proceed',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                // Redirect to policy creation or quote saving
                window.location.href = `../policies/issue_policy.php?quote_company=${companyId}&comparison_id=<?php echo $comparison_id ?? ''; ?>`;
            }
        });
    }

    function showCalculationDetails(quoteIndex) {
        const quotes = <?php echo json_encode($generated_quotes ?? []); ?>;
        const quote = quotes[quoteIndex];
        
        if (quote) {
            Swal.fire({
                title: `${quote.company_name} - Calculation Details`,
                html: `
                    <div class="text-start">
                        <h6>Rate Structure Used:</h6>
                        <p><strong>Age Band:</strong> ${quote.age_band_used.age_min} - ${quote.age_band_used.age_max} years</p>
                        <p><strong>Base Rate:</strong> KSH ${quote.age_band_used.base_rate}</p>
                        <p><strong>Rate per 1000:</strong> KSH ${quote.age_band_used.rate_per_thousand}</p>
                        <p><strong>Sum Assured Multiplier:</strong> ${quote.sum_multiplier_used}</p>
                        
                        <h6 class="mt-3">Calculation Formula:</h6>
                        <p class="small text-muted">${quote.calculation_details.final_calculation}</p>
                        
                        <h6 class="mt-3">Premium Breakdown:</h6>
                        <table class="table table-sm">
                            <tr><td>Annual Premium:</td><td>KSH ${quote.annual_premium.toLocaleString()}</td></tr>
                            <tr><td>Semi-Annual:</td><td>KSH ${quote.semi_annual_premium.toLocaleString()}</td></tr>
                            <tr><td>Quarterly:</td><td>KSH ${quote.quarterly_premium.toLocaleString()}</td></tr>
                            <tr><td>Monthly:</td><td>KSH ${quote.monthly_premium.toLocaleString()}</td></tr>
                        </table>
                        
                        <h6 class="mt-3">Commission Details:</h6>
                        <p><strong>Rate:</strong> ${quote.commission_rate}%</p>
                        <p><strong>Amount:</strong> KSH ${quote.commission_amount.toLocaleString()}</p>
                    </div>
                `,
                width: '600px',
                confirmButtonText: 'Close'
            });
        }
    }

    function convertToPolicy() {
        Swal.fire({
            title: 'Convert to Policy',
            text: 'Which quote would you like to convert to a policy?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Select from comparison',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                // Show quote selection modal or redirect to policy creation
                Swal.fire('Info', 'Please select a quote from the comparison above to proceed with policy creation.', 'info');
            }
        });
    }

    function saveAsQuote() {
        Swal.fire({
            title: 'Save Quote',
            input: 'textarea',
            inputLabel: 'Add notes (optional)',
            inputPlaceholder: 'Enter any additional notes for this quote...',
            showCancelButton: true,
            confirmButtonText: 'Save Quote',
            cancelButtonText: 'Cancel',
            inputValidator: (value) => {
                // Optional validation
            }
        }).then((result) => {
            if (result.isConfirmed) {
                // Save quote logic here
                const notes = result.value || '';
                
                $.ajax({
                    url: '../api/save_quote_comparison.php',
                    method: 'POST',
                    data: {
                        comparison_id: '<?php echo $comparison_id ?? ''; ?>',
                        notes: notes,
                        action: 'save'
                    },
                    success: function(response) {
                        Swal.fire('Success', 'Quote comparison saved successfully!', 'success');
                    },
                    error: function() {
                        Swal.fire('Error', 'Failed to save quote comparison.', 'error');
                    }
                });
            }
        });
    }

    function emailToCustomer() {
        const customerEmail = '<?php echo $customer_data['email'] ?? ''; ?>';
        
        if (!customerEmail) {
            Swal.fire('Error', 'Customer email not provided.', 'error');
            return;
        }

        Swal.fire({
            title: 'Email Quote Comparison',
            html: `
                <div class="text-start">
                    <label class="form-label">Email Subject:</label>
                    <input type="text" id="email-subject" class="form-control mb-3" 
                           value="Your Insurance Quote Comparison from Ultrasure">
                    
                    <label class="form-label">Email Message:</label>
                    <textarea id="email-message" class="form-control" rows="4">
Dear <?php echo ($customer_data['first_name'] ?? '') . ' ' . ($customer_data['last_name'] ?? ''); ?>,

Thank you for your interest in our insurance products. Please find attached your personalized quote comparison from multiple insurance providers.

We have carefully selected the best options based on your requirements. Please review the attached comparison and let us know if you have any questions.

Best regards,
<?php echo $_SESSION['full_name']; ?>
Ultrasure Insurance Platform
                    </textarea>
                </div>
            `,
            showCancelButton: true,
            confirmButtonText: 'Send Email',
            cancelButtonText: 'Cancel',
            preConfirm: () => {
                const subject = document.getElementById('email-subject').value;
                const message = document.getElementById('email-message').value;
                
                if (!subject.trim() || !message.trim()) {
                    Swal.showValidationMessage('Please fill in both subject and message');
                    return false;
                }
                
                return { subject, message };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                const { subject, message } = result.value;
                
                $.ajax({
                    url: '../api/email_quote_comparison.php',
                    method: 'POST',
                    data: {
                        comparison_id: '<?php echo $comparison_id ?? ''; ?>',
                        customer_email: customerEmail,
                        subject: subject,
                        message: message
                    },
                    success: function(response) {
                        Swal.fire('Success', 'Quote comparison emailed successfully!', 'success');
                    },
                    error: function() {
                        Swal.fire('Error', 'Failed to send email.', 'error');
                    }
                });
            }
        });
    }

    function shareViaWhatsApp() {
        const customerPhone = '<?php echo $customer_data['phone'] ?? ''; ?>';
        const customerName = '<?php echo ($customer_data['first_name'] ?? '') . ' ' . ($customer_data['last_name'] ?? ''); ?>';
        
        const message = `Hello ${customerName}! 

I've prepared a comprehensive insurance quote comparison for you with multiple providers. Here are the key highlights:

📋 Coverage: KSH <?php echo number_format($quote_params['sum_assured'] ?? 0); ?>
📅 Term: <?php echo $quote_params['policy_term'] ?? ''; ?> year(s)

The quotes range from KSH <?php echo isset($generated_quotes) ? number_format(min(array_column($generated_quotes, 'annual_premium'))) : '0'; ?> to KSH <?php echo isset($generated_quotes) ? number_format(max(array_column($generated_quotes, 'annual_premium'))) : '0'; ?> annually.

I'll send you the detailed comparison document shortly. Please let me know if you have any questions or would like to proceed with any of the quotes.

Best regards,
<?php echo $_SESSION['full_name']; ?>
Ultrasure Insurance`;

        const whatsappUrl = `https://wa.me/${customerPhone.replace(/[^0-9]/g, '')}?text=${encodeURIComponent(message)}`;
        window.open(whatsappUrl, '_blank');
    }

    function exportToPDF() {
        Swal.fire({
            title: 'Generating PDF...',
            text: 'Please wait while we prepare your quote comparison.',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        // Create PDF using jsPDF
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF();
        
        // Add content to PDF
        doc.setFontSize(20);
        doc.text('Multi-Insurer Quote Comparison', 20, 30);
        
        doc.setFontSize(12);
        doc.text('Generated by Ultrasure Insurance Platform', 20, 40);
        doc.text(`Date: ${new Date().toLocaleDateString()}`, 20, 50);
        
        // Customer information
        doc.setFontSize(14);
        doc.text('Customer Information:', 20, 70);
        doc.setFontSize(10);
        doc.text(`Name: <?php echo ($customer_data['first_name'] ?? '') . ' ' . ($customer_data['last_name'] ?? ''); ?>`, 20, 80);
        doc.text(`Email: <?php echo $customer_data['email'] ?? ''; ?>`, 20, 90);
        doc.text(`Phone: <?php echo $customer_data['phone'] ?? ''; ?>`, 20, 100);
        
        // Coverage details
        doc.setFontSize(14);
        doc.text('Coverage Details:', 20, 120);
        doc.setFontSize(10);
        doc.text(`Sum Assured: KSH <?php echo number_format($quote_params['sum_assured'] ?? 0); ?>`, 20, 130);
        doc.text(`Policy Term: <?php echo $quote_params['policy_term'] ?? ''; ?> year(s)`, 20, 140);
        doc.text(`Premium Frequency: <?php echo ucfirst(str_replace('_', ' ', strtolower($quote_params['premium_frequency'] ?? ''))); ?>`, 20, 150);
        
        // Quote comparison
        doc.setFontSize(14);
        doc.text('Premium Comparison:', 20, 170);
        
        <?php if (isset($generated_quotes)): ?>
        let yPos = 180;
        const quotes = <?php echo json_encode($generated_quotes); ?>;
        
        quotes.forEach((quote, index) => {
            doc.setFontSize(12);
            doc.text(`${index + 1}. ${quote.company_name}`, 20, yPos);
            doc.setFontSize(10);
            doc.text(`Annual Premium: KSH ${quote.annual_premium.toLocaleString()}`, 30, yPos + 10);
            doc.text(`Monthly Premium: KSH ${quote.monthly_premium.toLocaleString()}`, 30, yPos + 20);
            doc.text(`Commission: ${quote.commission_rate}% (KSH ${quote.commission_amount.toLocaleString()})`, 30, yPos + 30);
            
            yPos += 45;
            
            if (yPos > 250) {
                doc.addPage();
                yPos = 30;
            }
        });
        <?php endif; ?>
        
        // Footer
        const pageCount = doc.internal.getNumberOfPages();
        for (let i = 1; i <= pageCount; i++) {
            doc.setPage(i);
            doc.setFontSize(8);
            doc.text(`Generated by <?php echo $_SESSION['full_name']; ?> - Ultrasure Insurance Platform`, 20, 285);
            doc.text(`Page ${i} of ${pageCount}`, 180, 285);
        }
        
        // Save the PDF
        doc.save(`quote-comparison-${new Date().toISOString().split('T')[0]}.pdf`);
        
        Swal.close();
        Swal.fire('Success', 'PDF exported successfully!', 'success');
    }

    // Form validation on submit
    document.getElementById('quoteForm').addEventListener('submit', function(e) {
        const submitBtn = e.target.querySelector('button[type="submit"]');
        submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Generating Quotes...';
        submitBtn.disabled = true;
    });

    // Auto-calculate age when date of birth changes
    document.querySelector('[name="date_of_birth"]').addEventListener('change', function() {
        const age = calculateAge(this.value);
        if (age < 18 || age > 80) {
            Swal.fire('Warning', 'Please verify the date of birth. Age should be between 18 and 80 years.', 'warning');
        }
    });
    </script>
</body>
</html>

<?php
// ============================================================================
// 3. API ENDPOINTS FOR AJAX FUNCTIONALITY
// ============================================================================

/*
// File: api/get_products.php
<?php
session_start();
include '../layouts/dbconn.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['category_id'])) {
    $category_id = $_POST['category_id'];
    
    $sql = "SELECT product_id, product_name, description FROM insurance_products 
            WHERE category_id = ? AND is_active = 1 
            ORDER BY product_name";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $category_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $products = [];
    while ($row = $result->fetch_assoc()) {
        $products[] = $row;
    }
    
    echo json_encode(['success' => true, 'products' => $products]);
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
}
?>

// File: api/save_quote_comparison.php
<?php
session_start();
include '../layouts/dbconn.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $comparison_id = $_POST['comparison_id'];
    $notes = $_POST['notes'] ?? '';
    $action = $_POST['action'];
    
    if ($action === 'save') {
        $sql = "UPDATE multi_insurer_quotes SET notes = ?, status = 'ACTIVE' WHERE comparison_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("si", $notes, $comparison_id);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'Quote comparison saved successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to save quote comparison']);
        }
    }
}
?>

// File: api/email_quote_comparison.php
<?php
session_start();
include '../layouts/dbconn.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $comparison_id = $_POST['comparison_id'];
    $customer_email = $_POST['customer_email'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];
    
    // Get comparison details
    $sql = "SELECT * FROM multi_insurer_quotes WHERE comparison_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $comparison_id);
    $stmt->execute();
    $comparison = $stmt->get_result()->fetch_assoc();
    
    if ($comparison) {
        // Generate PDF attachment (simplified version)
        // In production, use a proper PDF library or service
        
        // Send email using your preferred email service
        // This is a placeholder - implement with your email provider
        
        // Log communication
        $log_sql = "INSERT INTO communication_log (recipient_type, recipient_id, communication_type, 
                   subject, message, recipient_contact, status, sent_by) 
                   VALUES ('CUSTOMER', NULL, 'EMAIL', ?, ?, ?, 'SENT', ?)";
        
        $log_stmt = $conn->prepare($log_sql);
        $log_stmt->bind_param("sssi", $subject, $message, $customer_email, $_SESSION['user_id']);
        $log_stmt->execute();
        
        echo json_encode(['success' => true, 'message' => 'Email sent successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Comparison not found']);
    }
}
?>
*/

?>