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

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

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

$user_id = $_SESSION['user_id'];
$agent_id = $_SESSION['user_id']; // Assuming agent_id is same as user_id
$success_message = '';
$error_message = '';

// Get parameters
$customer_id = isset($_GET['customer_id']) ? (int)$_GET['customer_id'] : 0;
$lead_id = isset($_GET['lead_id']) ? (int)$_GET['lead_id'] : 0;
$product_id = isset($_GET['product_id']) ? (int)$_GET['product_id'] : 0;

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        // Validate required fields
        $required_fields = ['product_id', 'quote_type', 'coverage_amount', 'premium_frequency'];
        foreach ($required_fields as $field) {
            if (empty($_POST[$field])) {
                throw new Exception("Please fill in all required fields.");
            }
        }

        // Generate quote number
        $quote_number = generateQuoteNumber();
        
        // Check if quote number already exists
        $check_quote_sql = "SELECT quote_id FROM quotes WHERE quote_number = ?";
        $check_stmt = $conn->prepare($check_quote_sql);
        $check_stmt->bind_param("s", $quote_number);
        $check_stmt->execute();
        if ($check_stmt->get_result()->num_rows > 0) {
            throw new Exception("Quote number conflict. Please try again.");
        }
        $check_stmt->close();

        // Get product details for calculation
        $product_sql = "SELECT ip.*, pc.category_name, ic.company_name 
                       FROM insurance_products ip
                       LEFT JOIN product_categories pc ON ip.category_id = pc.category_id
                       LEFT JOIN insurance_companies ic ON ip.company_id = ic.company_id
                       WHERE ip.product_id = ? AND ip.is_active = 1";
        $product_stmt = $conn->prepare($product_sql);
        $product_stmt->bind_param("i", $_POST['product_id']);
        $product_stmt->execute();
        $product = $product_stmt->get_result()->fetch_assoc();
        $product_stmt->close();

        if (!$product) {
            throw new Exception("Selected product is not available.");
        }

        // Prepare quote data
        $customer_id = !empty($_POST['customer_id']) ? (int)$_POST['customer_id'] : null;
        $lead_id = !empty($_POST['lead_id']) ? (int)$_POST['lead_id'] : null;
        $product_id = (int)$_POST['product_id'];
        $quote_type = $_POST['quote_type'];
        $coverage_amount = (float)$_POST['coverage_amount'];
        $premium_frequency = $_POST['premium_frequency'];
        $validity_days = !empty($_POST['validity_days']) ? (int)$_POST['validity_days'] : 30;
        
        // Calculate premium based on product and coverage
        $premium_calculation = calculatePremium($product, $coverage_amount, $_POST);
        
        $base_premium = $premium_calculation['base_premium'];
        $risk_premium = $premium_calculation['risk_premium'];
        $loading_amount = $premium_calculation['loading_amount'];
        $discount_amount = $premium_calculation['discount_amount'];
        $total_premium = $premium_calculation['total_premium'];
        $commission_amount = ($total_premium * $product['commission_rate']) / 100;
        
        // Calculate additional charges
        $policy_fee = calculatePolicyFee($total_premium);
        $stamp_duty = calculateStampDuty($total_premium);
        $tax_amount = calculateTax($total_premium);
        $final_premium = $total_premium + $policy_fee + $stamp_duty + $tax_amount;

        // Prepare insured details
        $insured_details = [
            'primary_insured' => [
                'name' => trim($_POST['primary_name']),
                'date_of_birth' => $_POST['primary_dob'],
                'gender' => $_POST['primary_gender'],
                'occupation' => trim($_POST['primary_occupation']),
                'relationship' => 'SELF'
            ]
        ];

        // Add dependents if family/group quote
        if (in_array($quote_type, ['FAMILY', 'GROUP']) && !empty($_POST['dependents'])) {
            $insured_details['dependents'] = [];
            foreach ($_POST['dependents'] as $index => $dependent) {
                if (!empty($dependent['name'])) {
                    $insured_details['dependents'][] = [
                        'name' => trim($dependent['name']),
                        'date_of_birth' => $dependent['dob'],
                        'gender' => $dependent['gender'],
                        'relationship' => $dependent['relationship']
                    ];
                }
            }
        }

        // Prepare risk factors
        $risk_factors = [
            'age' => calculateAge($_POST['primary_dob']),
            'occupation_risk' => $_POST['occupation_risk'] ?? 'LOW',
            'medical_history' => $_POST['medical_history'] ?? 'NONE',
            'lifestyle_factors' => $_POST['lifestyle_factors'] ?? []
        ];

        $special_conditions = trim($_POST['special_conditions']);
        $expires_at = date('Y-m-d H:i:s', strtotime("+{$validity_days} days"));

        // Insert quote - Fixed SQL and bind_param
        $insert_sql = "INSERT INTO quotes (
            quote_number, customer_id, lead_id, product_id, agent_id, quote_type,
            insured_details, coverage_amount, premium_frequency, base_premium,
            risk_premium, loading_amount, discount_amount, total_premium,
            commission_amount, policy_fee, stamp_duty, tax_amount, final_premium,
            risk_factors, special_conditions, validity_days, status, expires_at,
            created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'ACTIVE', ?, NOW())";

        $stmt = $conn->prepare($insert_sql);
        
        $insured_details_json = json_encode($insured_details);
        $risk_factors_json = json_encode($risk_factors);

        // Fixed bind_param with correct type string (24 parameters)
        $stmt->bind_param("siiiissddddddddddddsiss", 
            $quote_number,           // s
            $customer_id,           // i (can be null)
            $lead_id,              // i (can be null)
            $product_id,           // i
            $agent_id,             // i
            $quote_type,           // s
            $insured_details_json, // s
            $coverage_amount,      // d
            $premium_frequency,    // s
            $base_premium,         // d
            $risk_premium,         // d
            $loading_amount,       // d
            $discount_amount,      // d
            $total_premium,        // d
            $commission_amount,    // d
            $policy_fee,           // d
            $stamp_duty,           // d
            $tax_amount,           // d
            $final_premium,        // d
            $risk_factors_json,    // s
            $special_conditions,   // s
            $validity_days,        // i
            $expires_at            // s
        );

        if ($stmt->execute()) {
            $quote_id = $conn->insert_id;
            
            // Log activity - Fixed function call
            logActivity($conn, $user_id, 'CREATE', 'QUOTE', $quote_id, null, [
                'quote_number' => $quote_number,
                'product_id' => $product_id,
                'coverage_amount' => $coverage_amount,
                'total_premium' => $total_premium
            ]);

            $success_message = "Quote '{$quote_number}' has been successfully generated.";
            
            // Redirect to quote view
            header("Location: view_quote.php?id={$quote_id}&success=created");
            exit();
        } else {
            throw new Exception("Failed to generate quote. Please try again.");
        }

    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

// Get customers for dropdown
$customers_sql = "SELECT customer_id, customer_number, first_name, last_name, email, phone_primary 
                 FROM customers WHERE is_active = 1 ORDER BY first_name, last_name";
$customers_result = $conn->query($customers_sql);

// Get leads for dropdown
$leads_sql = "SELECT lead_id, lead_number, first_name, last_name, email, phone, product_interest 
             FROM leads WHERE status IN ('NEW', 'CONTACTED', 'QUALIFIED') ORDER BY created_at DESC";
$leads_result = $conn->query($leads_sql);

// Get products for dropdown
$products_sql = "SELECT ip.product_id, ip.product_name, ip.product_code, ip.base_premium, 
                        ip.commission_rate, ip.age_range_min, ip.age_range_max,
                        pc.category_name, ic.company_name
                FROM insurance_products ip
                LEFT JOIN product_categories pc ON ip.category_id = pc.category_id
                LEFT JOIN insurance_companies ic ON ip.company_id = ic.company_id
                WHERE ip.is_active = 1 
                ORDER BY pc.category_name, ip.product_name";
$products_result = $conn->query($products_sql);

// Helper functions
function generateQuoteNumber() {
    $prefix = 'ULT-Q';
    $date = date('Ymd');
    $random = str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
    return $prefix . $date . $random;
}

function calculateAge($dob) {
    $birth_date = new DateTime($dob);
    $today = new DateTime();
    return $today->diff($birth_date)->y;
}

function calculatePremium($product, $coverage_amount, $form_data) {
    $base_premium = $product['base_premium'] ?? 0;
    
    // If base premium is 0, calculate based on coverage amount and rate
    if ($base_premium == 0) {
        $rate = 0.05; // 5% default rate - should be configurable
        $base_premium = $coverage_amount * $rate;
    }
    
    // Apply frequency multiplier
    $frequency_multipliers = [
        'MONTHLY' => 12,
        'QUARTERLY' => 4,
        'SEMI_ANNUAL' => 2,
        'ANNUAL' => 1
    ];
    
    $multiplier = $frequency_multipliers[$form_data['premium_frequency']] ?? 1;
    $base_premium = $base_premium / $multiplier;
    
    // Calculate risk adjustments
    $risk_premium = 0;
    $loading_amount = 0;
    $discount_amount = 0;
    
    // Age-based adjustments
    if (!empty($form_data['primary_dob'])) {
        $age = calculateAge($form_data['primary_dob']);
        if ($age > 50) {
            $loading_amount += $base_premium * 0.1; // 10% loading for age > 50
        }
        if ($age < 25) {
            $discount_amount += $base_premium * 0.05; // 5% discount for young people
        }
    }
    
    // Occupation risk adjustments
    $occupation_risk = $form_data['occupation_risk'] ?? 'LOW';
    switch ($occupation_risk) {
        case 'HIGH':
            $loading_amount += $base_premium * 0.2; // 20% loading
            break;
        case 'MEDIUM':
            $loading_amount += $base_premium * 0.1; // 10% loading
            break;
        case 'LOW':
        default:
            // No adjustment
            break;
    }
    
    $total_premium = $base_premium + $risk_premium + $loading_amount - $discount_amount;
    
    return [
        'base_premium' => $base_premium,
        'risk_premium' => $risk_premium,
        'loading_amount' => $loading_amount,
        'discount_amount' => $discount_amount,
        'total_premium' => max($total_premium, 0) // Ensure non-negative
    ];
}

function calculatePolicyFee($premium) {
    return max($premium * 0.005, 100); // 0.5% or minimum KSH 100
}

function calculateStampDuty($premium) {
    return $premium * 0.002; // 0.2%
}

function calculateTax($premium) {
    return $premium * 0.16; // 16% VAT
}

// Simple activity logging function
function logActivity($conn, $user_id, $action, $module, $record_id, $old_values, $new_values) {
    $sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values, logged_at) 
            VALUES (?, ?, ?, ?, ?, NOW())";
    $stmt = $conn->prepare($sql);
    $new_values_json = json_encode($new_values);
    $stmt->bind_param("issis", $user_id, $action, $module, $record_id, $new_values_json);
    $stmt->execute();
    $stmt->close();
}

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Generate Quote - Ultrasure Insurance Platform')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <!-- Flatpickr CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <style>
        .quote-wizard {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .wizard-step {
            display: none;
        }
        
        .wizard-step.active {
            display: block;
        }
        
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 2rem;
        }
        
        .step-item {
            flex: 1;
            text-align: center;
            position: relative;
        }
        
        .step-item:not(:last-child)::after {
            content: '';
            position: absolute;
            top: 15px;
            right: -50%;
            width: 100%;
            height: 2px;
            background: rgba(255,255,255,0.3);
            z-index: 1;
        }
        
        .step-item.completed::after {
            background: #28a745;
        }
        
        .step-circle {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: rgba(255,255,255,0.3);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 0.5rem;
            position: relative;
            z-index: 2;
        }
        
        .step-item.active .step-circle {
            background: #ffc107;
            color: #000;
        }
        
        .step-item.completed .step-circle {
            background: #28a745;
        }
        
        .section-card {
            border: none;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-radius: 15px;
            margin-bottom: 1.5rem;
        }
        
        .section-header {
            background: #f8f9fa;
            padding: 1rem 1.5rem;
            border-radius: 15px 15px 0 0;
            border-bottom: 1px solid #dee2e6;
        }
        
        .premium-calculator {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border-radius: 15px;
            padding: 1.5rem;
        }
        
        .premium-breakdown {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 1rem;
        }
        
        .dependent-row {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1rem;
            border-left: 4px solid #007bff;
        }
        
        .required-field::after {
            content: " *";
            color: #e74c3c;
            font-weight: bold;
        }
        
        .btn-wizard {
            border-radius: 25px;
            padding: 0.75rem 2rem;
            font-weight: 600;
            min-width: 120px;
        }
        
        .product-card {
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 1rem;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .product-card:hover {
            border-color: #007bff;
            box-shadow: 0 4px 15px rgba(0,123,255,0.2);
        }
        
        .product-card.selected {
            border-color: #007bff;
            background: #f8f9ff;
        }
        
        .risk-factor-card {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 10px;
            padding: 1rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Generate Insurance Quote</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_quotes.php">Quotes</a></li>
                                        <li class="breadcrumb-item active">Generate Quote</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Success/Error Messages -->
                    <?php if ($success_message): ?>
                    <div class="row">
                        <div class="col-12">
                            <div class="alert alert-success alert-dismissible fade show" role="alert">
                                <i class="ri-check-circle-line me-2"></i>
                                <?php echo htmlspecialchars($success_message); ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <?php if ($error_message): ?>
                    <div class="row">
                        <div class="col-12">
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <i class="ri-error-warning-line me-2"></i>
                                <?php echo htmlspecialchars($error_message); ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Quote Wizard -->
                    <div class="row">
                        <div class="col-12">
                            <div class="quote-wizard">
                                <h5 class="mb-3">
                                    <i class="ri-calculator-line me-2"></i>
                                    Quote Generation Wizard
                                </h5>
                                
                                <!-- Step Indicator -->
                                <div class="step-indicator">
                                    <div class="step-item active" data-step="1">
                                        <div class="step-circle">1</div>
                                        <small>Customer & Product</small>
                                    </div>
                                    <div class="step-item" data-step="2">
                                        <div class="step-circle">2</div>
                                        <small>Coverage Details</small>
                                    </div>
                                    <div class="step-item" data-step="3">
                                        <div class="step-circle">3</div>
                                        <small>Risk Assessment</small>
                                    </div>
                                    <div class="step-item" data-step="4">
                                        <div class="step-circle">4</div>
                                        <small>Review & Generate</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <form method="POST" id="quoteForm" novalidate>
                        <!-- Step 1: Customer & Product Selection -->
                        <div class="wizard-step active" id="step1">
                            <div class="row">
                                <div class="col-xl-8">
                                    <div class="card section-card">
                                        <div class="section-header">
                                            <h5 class="mb-0">
                                                <i class="ri-user-line me-2"></i>
                                                Customer & Product Selection
                                            </h5>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Customer (Optional)</label>
                                                    <select class="form-select" name="customer_id" id="customer_id">
                                                        <option value="">Select Existing Customer</option>
                                                        <?php if ($customers_result): ?>
                                                        <?php while($customer = $customers_result->fetch_assoc()): ?>
                                                            <option value="<?php echo $customer['customer_id']; ?>" 
                                                                    data-email="<?php echo $customer['email']; ?>"
                                                                    data-phone="<?php echo $customer['phone_primary']; ?>"
                                                                    <?php echo ($customer_id == $customer['customer_id']) ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($customer['first_name'] . ' ' . $customer['last_name'] . ' (' . $customer['customer_number'] . ')'); ?>
                                                            </option>
                                                        <?php endwhile; ?>
                                                        <?php endif; ?>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Lead (Optional)</label>
                                                    <select class="form-select" name="lead_id" id="lead_id">
                                                        <option value="">Select Lead</option>
                                                        <?php if ($leads_result): ?>
                                                        <?php while($lead = $leads_result->fetch_assoc()): ?>
                                                            <option value="<?php echo $lead['lead_id']; ?>" 
                                                                    data-email="<?php echo $lead['email']; ?>"
                                                                    data-phone="<?php echo $lead['phone']; ?>"
                                                                    data-interest="<?php echo $lead['product_interest']; ?>"
                                                                    <?php echo ($lead_id == $lead['lead_id']) ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($lead['first_name'] . ' ' . $lead['last_name'] . ' (' . $lead['lead_number'] . ')'); ?>
                                                            </option>
                                                        <?php endwhile; ?>
                                                        <?php endif; ?>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label required-field">Quote Type</label>
                                                    <select class="form-select" name="quote_type" id="quote_type" required>
                                                        <option value="">Select Quote Type</option>
                                                        <option value="INDIVIDUAL">Individual</option>
                                                        <option value="FAMILY">Family</option>
                                                        <option value="GROUP">Group</option>
                                                        <option value="CORPORATE">Corporate</option>
                                                    </select>
                                                    <div class="invalid-feedback">Please select a quote type.</div>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label required-field">Premium Frequency</label>
                                                    <select class="form-select" name="premium_frequency" id="premium_frequency" required>
                                                        <option value="">Select Frequency</option>
                                                        <option value="ANNUAL">Annual</option>
                                                        <option value="SEMI_ANNUAL">Semi-Annual</option>
                                                        <option value="QUARTERLY">Quarterly</option>
                                                        <option value="MONTHLY">Monthly</option>
                                                    </select>
                                                    <div class="invalid-feedback">Please select premium frequency.</div>
                                                </div>
                                            </div>

                                            <div class="mb-3">
                                                <label class="form-label required-field">Insurance Product</label>
                                                <div class="row" id="productGrid">
                                                    <?php if ($products_result): ?>
                                                    <?php while($product = $products_result->fetch_assoc()): ?>
                                                    <div class="col-md-6 col-lg-4 mb-3">
                                                        <div class="product-card" data-product-id="<?php echo $product['product_id']; ?>" 
                                                             <?php echo ($product_id == $product['product_id']) ? 'selected' : ''; ?>>
                                                            <div class="form-check">
                                                                <input class="form-check-input" type="radio" name="product_id" 
                                                                       value="<?php echo $product['product_id']; ?>" 
                                                                       id="product_<?php echo $product['product_id']; ?>" required
                                                                       data-base-premium="<?php echo $product['base_premium']; ?>"
                                                                       data-commission="<?php echo $product['commission_rate']; ?>"
                                                                       data-age-min="<?php echo $product['age_range_min']; ?>"
                                                                       data-age-max="<?php echo $product['age_range_max']; ?>"
                                                                       <?php echo ($product_id == $product['product_id']) ? 'checked' : ''; ?>>
                                                                <label class="form-check-label w-100" for="product_<?php echo $product['product_id']; ?>">
                                                                    <h6 class="mb-1"><?php echo htmlspecialchars($product['product_name']); ?></h6>
                                                                    <p class="text-muted small mb-1"><?php echo htmlspecialchars($product['company_name']); ?></p>
                                                                    <span class="badge bg-primary"><?php echo htmlspecialchars($product['category_name']); ?></span>
                                                                    <?php if($product['base_premium']): ?>
                                                                    <div class="mt-2">
                                                                        <small class="text-success fw-bold">Base: KSH <?php echo number_format($product['base_premium'], 2); ?></small>
                                                                    </div>
                                                                    <?php endif; ?>
                                                                </label>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <?php endwhile; ?>
                                                    <?php endif; ?>
                                                </div>
                                                <div class="invalid-feedback">Please select an insurance product.</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-xl-4">
                                    <div class="card section-card">
                                        <div class="section-header">
                                            <h5 class="mb-0">
                                                <i class="ri-information-line me-2"></i>
                                                Quick Info
                                            </h5>
                                        </div>
                                        <div class="card-body">
                                            <div id="selectedCustomerInfo" class="mb-3" style="display: none;">
                                                <h6 class="text-primary">Selected Customer</h6>
                                                <div id="customerDetails"></div>
                                            </div>
                                            
                                            <div id="selectedProductInfo" class="mb-3" style="display: none;">
                                                <h6 class="text-primary">Selected Product</h6>
                                                <div id="productDetails"></div>
                                            </div>
                                            
                                            <div class="alert alert-info">
                                                <h6 class="alert-heading">
                                                    <i class="ri-lightbulb-line me-2"></i>
                                                    Tips
                                                </h6>
                                                <ul class="mb-0 small">
                                                    <li>You can quote for existing customers or leads</li>
                                                    <li>Leave customer/lead empty for walk-in quotes</li>
                                                    <li>Family quotes can include multiple dependents</li>
                                                    <li>Group quotes are for organizations</li>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Step 2: Coverage Details -->
                        <div class="wizard-step" id="step2">
                            <div class="row">
                                <div class="col-xl-8">
                                   <div class="card section-card">
                                       <div class="section-header">
                                           <h5 class="mb-0">
                                               <i class="ri-shield-check-line me-2"></i>
                                               Coverage Details
                                           </h5>
                                       </div>
                                       <div class="card-body">
                                           <!-- Primary Insured -->
                                           <div class="mb-4">
                                               <h6 class="text-primary mb-3">Primary Insured Details</h6>
                                               <div class="row">
                                                   <div class="col-md-6 mb-3">
                                                       <label class="form-label required-field">Full Name</label>
                                                       <input type="text" class="form-control" name="primary_name" 
                                                              id="primary_name" required placeholder="Enter full name">
                                                       <div class="invalid-feedback">Please enter the insured's name.</div>
                                                   </div>
                                                   
                                                   <div class="col-md-3 mb-3">
                                                       <label class="form-label required-field">Date of Birth</label>
                                                       <input type="date" class="form-control" name="primary_dob" 
                                                              id="primary_dob" required>
                                                       <div class="invalid-feedback">Please enter date of birth.</div>
                                                   </div>
                                                   
                                                   <div class="col-md-3 mb-3">
                                                       <label class="form-label required-field">Gender</label>
                                                       <select class="form-select" name="primary_gender" required>
                                                           <option value="">Select</option>
                                                           <option value="MALE">Male</option>
                                                           <option value="FEMALE">Female</option>
                                                           <option value="OTHER">Other</option>
                                                       </select>
                                                       <div class="invalid-feedback">Please select gender.</div>
                                                   </div>
                                               </div>
                                               
                                               <div class="row">
                                                   <div class="col-md-6 mb-3">
                                                       <label class="form-label">Occupation</label>
                                                       <input type="text" class="form-control" name="primary_occupation" 
                                                              placeholder="Enter occupation">
                                                   </div>
                                                   
                                                   <div class="col-md-6 mb-3">
                                                       <label class="form-label required-field">Coverage Amount (KSH)</label>
                                                       <input type="number" class="form-control" name="coverage_amount" 
                                                              id="coverage_amount" min="1000" step="1000" required 
                                                              placeholder="Enter coverage amount">
                                                       <div class="invalid-feedback">Please enter coverage amount.</div>
                                                   </div>
                                               </div>
                                           </div>

                                           <!-- Dependents Section -->
                                           <div id="dependentsSection" style="display: none;">
                                               <div class="d-flex justify-content-between align-items-center mb-3">
                                                   <h6 class="text-primary mb-0">Dependents</h6>
                                                   <button type="button" class="btn btn-sm btn-outline-primary" 
                                                           onclick="addDependent()">
                                                       <i class="ri-add-line me-1"></i> Add Dependent
                                                   </button>
                                               </div>
                                               <div id="dependentsList"></div>
                                           </div>
                                       </div>
                                   </div>
                               </div>

                               <div class="col-xl-4">
                                   <div class="card section-card">
                                       <div class="section-header">
                                           <h5 class="mb-0">
                                               <i class="ri-calculator-line me-2"></i>
                                               Premium Calculator
                                           </h5>
                                       </div>
                                       <div class="card-body">
                                           <div class="premium-calculator">
                                               <h6 class="mb-3">Estimated Premium</h6>
                                               <div id="premiumBreakdown">
                                                   <div class="d-flex justify-content-between mb-2">
                                                       <span>Base Premium:</span>
                                                       <span id="basePremiumDisplay">KSH 0.00</span>
                                                   </div>
                                                   <div class="d-flex justify-content-between mb-2">
                                                       <span>Risk Loading:</span>
                                                       <span id="riskLoadingDisplay">KSH 0.00</span>
                                                   </div>
                                                   <div class="d-flex justify-content-between mb-2">
                                                       <span>Discount:</span>
                                                       <span id="discountDisplay" class="text-success">- KSH 0.00</span>
                                                   </div>
                                                   <hr class="my-2">
                                                   <div class="d-flex justify-content-between fw-bold fs-5">
                                                       <span>Total Premium:</span>
                                                       <span id="totalPremiumDisplay">KSH 0.00</span>
                                                   </div>
                                                   <small class="text-white-50 d-block mt-1" id="frequencyNote">
                                                       Select frequency for calculation
                                                   </small>
                                               </div>
                                           </div>
                                           
                                           <div class="premium-breakdown mt-3">
                                               <h6 class="mb-2">Additional Charges</h6>
                                               <div class="d-flex justify-content-between small mb-1">
                                                   <span>Policy Fee:</span>
                                                   <span id="policyFeeDisplay">KSH 0.00</span>
                                               </div>
                                               <div class="d-flex justify-content-between small mb-1">
                                                   <span>Stamp Duty:</span>
                                                   <span id="stampDutyDisplay">KSH 0.00</span>
                                               </div>
                                               <div class="d-flex justify-content-between small mb-2">
                                                   <span>VAT (16%):</span>
                                                   <span id="vatDisplay">KSH 0.00</span>
                                               </div>
                                               <hr class="my-2">
                                               <div class="d-flex justify-content-between fw-bold">
                                                   <span>Final Premium:</span>
                                                   <span id="finalPremiumDisplay">KSH 0.00</span>
                                               </div>
                                           </div>
                                       </div>
                                   </div>
                               </div>
                           </div>
                       </div>

                       <!-- Step 3: Risk Assessment -->
                       <div class="wizard-step" id="step3">
                           <div class="row">
                               <div class="col-xl-8">
                                   <div class="card section-card">
                                       <div class="section-header">
                                           <h5 class="mb-0">
                                               <i class="ri-shield-cross-line me-2"></i>
                                               Risk Assessment
                                           </h5>
                                       </div>
                                       <div class="card-body">
                                           <div class="row">
                                               <div class="col-md-6 mb-3">
                                                   <label class="form-label">Occupation Risk Level</label>
                                                   <select class="form-select" name="occupation_risk" id="occupation_risk">
                                                       <option value="LOW">Low Risk</option>
                                                       <option value="MEDIUM">Medium Risk</option>
                                                       <option value="HIGH">High Risk</option>
                                                   </select>
                                                   <div class="form-text">
                                                       Select based on occupational hazards
                                                   </div>
                                               </div>
                                               
                                               <div class="col-md-6 mb-3">
                                                   <label class="form-label">Medical History</label>
                                                   <select class="form-select" name="medical_history" id="medical_history">
                                                       <option value="NONE">No Known Medical Issues</option>
                                                       <option value="MINOR">Minor Medical Conditions</option>
                                                       <option value="CHRONIC">Chronic Conditions</option>
                                                       <option value="SERIOUS">Serious Medical History</option>
                                                   </select>
                                               </div>
                                           </div>

                                           <div class="mb-3">
                                               <label class="form-label">Lifestyle Factors</label>
                                               <div class="row">
                                                   <div class="col-md-3">
                                                       <div class="form-check">
                                                           <input class="form-check-input" type="checkbox" 
                                                                  name="lifestyle_factors[]" value="SMOKING" 
                                                                  id="smoking">
                                                           <label class="form-check-label" for="smoking">
                                                               Smoking
                                                           </label>
                                                       </div>
                                                   </div>
                                                   <div class="col-md-3">
                                                       <div class="form-check">
                                                           <input class="form-check-input" type="checkbox" 
                                                                  name="lifestyle_factors[]" value="DRINKING" 
                                                                  id="drinking">
                                                           <label class="form-check-label" for="drinking">
                                                               Heavy Drinking
                                                           </label>
                                                       </div>
                                                   </div>
                                                   <div class="col-md-3">
                                                       <div class="form-check">
                                                           <input class="form-check-input" type="checkbox" 
                                                                  name="lifestyle_factors[]" value="SPORTS" 
                                                                  id="sports">
                                                           <label class="form-check-label" for="sports">
                                                               Extreme Sports
                                                           </label>
                                                       </div>
                                                   </div>
                                                   <div class="col-md-3">
                                                       <div class="form-check">
                                                           <input class="form-check-input" type="checkbox" 
                                                                  name="lifestyle_factors[]" value="TRAVEL" 
                                                                  id="travel">
                                                           <label class="form-check-label" for="travel">
                                                               Frequent Travel
                                                           </label>
                                                       </div>
                                                   </div>
                                               </div>
                                           </div>

                                           <div class="mb-3">
                                               <label class="form-label">Special Conditions/Notes</label>
                                               <textarea class="form-control" name="special_conditions" rows="3" 
                                                         placeholder="Any special conditions, exclusions, or notes for this quote"></textarea>
                                           </div>

                                           <div class="risk-factor-card">
                                               <h6 class="mb-2">
                                                   <i class="ri-alert-line me-2"></i>
                                                   Risk Assessment Summary
                                               </h6>
                                               <div id="riskSummary">
                                                   <div class="d-flex justify-content-between">
                                                       <span>Age Factor:</span>
                                                       <span id="ageFactor" class="badge bg-success">Low Risk</span>
                                                   </div>
                                                   <div class="d-flex justify-content-between mt-1">
                                                       <span>Occupation:</span>
                                                       <span id="occupationFactor" class="badge bg-success">Low Risk</span>
                                                   </div>
                                                   <div class="d-flex justify-content-between mt-1">
                                                       <span>Medical:</span>
                                                       <span id="medicalFactor" class="badge bg-success">Low Risk</span>
                                                   </div>
                                                   <div class="d-flex justify-content-between mt-1">
                                                       <span>Overall Risk:</span>
                                                       <span id="overallRisk" class="badge bg-success">Low Risk</span>
                                                   </div>
                                               </div>
                                           </div>
                                       </div>
                                   </div>
                               </div>

                               <div class="col-xl-4">
                                   <div class="card section-card">
                                       <div class="section-header">
                                           <h5 class="mb-0">
                                               <i class="ri-settings-line me-2"></i>
                                               Quote Settings
                                           </h5>
                                       </div>
                                       <div class="card-body">
                                           <div class="mb-3">
                                               <label class="form-label">Quote Validity (Days)</label>
                                               <input type="number" class="form-control" name="validity_days" 
                                                      value="30" min="1" max="90">
                                               <div class="form-text">Quote will expire after this period</div>
                                           </div>

                                           <div class="alert alert-warning">
                                               <h6 class="alert-heading">
                                                   <i class="ri-information-line me-2"></i>
                                                   Important Notes
                                               </h6>
                                               <ul class="mb-0 small">
                                                   <li>Higher risk factors may increase premium</li>
                                                   <li>Medical examination may be required</li>
                                                   <li>Final premium subject to underwriting</li>
                                                   <li>Quote is valid for 30 days by default</li>
                                               </ul>
                                           </div>
                                       </div>
                                   </div>
                               </div>
                           </div>
                       </div>

                       <!-- Step 4: Review & Generate -->
                       <div class="wizard-step" id="step4">
                           <div class="row">
                               <div class="col-xl-8">
                                   <div class="card section-card">
                                       <div class="section-header">
                                           <h5 class="mb-0">
                                               <i class="ri-file-list-line me-2"></i>
                                               Quote Review & Summary
                                           </h5>
                                       </div>
                                       <div class="card-body">
                                           <div id="quoteSummary">
                                               <!-- Quote summary will be populated by JavaScript -->
                                           </div>
                                       </div>
                                   </div>
                               </div>

                               <div class="col-xl-4">
                                   <div class="card section-card">
                                       <div class="section-header">
                                           <h5 class="mb-0">
                                               <i class="ri-money-dollar-circle-line me-2"></i>
                                               Final Premium Calculation
                                           </h5>
                                       </div>
                                       <div class="card-body">
                                           <div id="finalPremiumSummary">
                                               <!-- Final premium summary will be populated by JavaScript -->
                                           </div>
                                           
                                           <div class="alert alert-success mt-3">
                                               <h6 class="alert-heading">
                                                   <i class="ri-check-line me-2"></i>
                                                   Ready to Generate
                                               </h6>
                                               <p class="mb-0 small">
                                                   Please review all details above before generating the quote.
                                                   Once generated, the quote will be saved and can be sent to the customer.
                                               </p>
                                           </div>
                                       </div>
                                   </div>
                               </div>
                           </div>
                       </div>

                       <!-- Navigation Buttons -->
                       <div class="row">
                           <div class="col-12">
                               <div class="card">
                                   <div class="card-body">
                                       <div class="d-flex justify-content-between">
                                           <button type="button" class="btn btn-secondary btn-wizard" 
                                                   id="prevBtn" onclick="changeStep(-1)" style="display: none;">
                                               <i class="ri-arrow-left-line me-2"></i>
                                               Previous
                                           </button>
                                           
                                           <div class="ms-auto">
                                               <button type="button" class="btn btn-primary btn-wizard me-2" 
                                                       id="nextBtn" onclick="changeStep(1)">
                                                   Next
                                                   <i class="ri-arrow-right-line ms-2"></i>
                                               </button>
                                               
                                               <button type="submit" class="btn btn-success btn-wizard" 
                                                       id="submitBtn" style="display: none;">
                                                   <i class="ri-send-plane-line me-2"></i>
                                                   Generate Quote
                                               </button>
                                           </div>
                                       </div>
                                   </div>
                               </div>
                           </div>
                       </div>
                   </form>

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

   <?php include 'layouts/vendor-scripts.php'; ?>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <!-- Select2 JS -->
   <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
   
   <!-- Flatpickr JS -->
   <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
   
   <!-- SweetAlert2 -->
   <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
   
   <script>
       let currentStep = 1;
       const totalSteps = 4;
       let dependentCount = 0;
       
       $(document).ready(function() {
           // Initialize Select2 for dropdowns
           $('.form-select').select2({
               theme: 'bootstrap-5',
               width: '100%'
           });
           
           // Initialize date picker
           flatpickr('[type="date"]', {
               dateFormat: "Y-m-d",
               allowInput: true,
               maxDate: "today"
           });
           
           // Product card selection
           $('.product-card').on('click', function() {
               $('.product-card').removeClass('selected');
               $(this).addClass('selected');
               $(this).find('input[type="radio"]').prop('checked', true);
               updateProductInfo();
               calculatePremium();
           });
           
           // Customer/Lead selection
           $('#customer_id, #lead_id').on('change', function() {
               if ($(this).val()) {
                   // Clear the other selection
                   if ($(this).attr('id') === 'customer_id') {
                       $('#lead_id').val('').trigger('change');
                   } else {
                       $('#customer_id').val('').trigger('change');
                   }
                   updateCustomerInfo();
               }
           });
           
           // Quote type change
           $('#quote_type').on('change', function() {
               const quoteType = $(this).val();
               if (quoteType === 'FAMILY' || quoteType === 'GROUP') {
                   $('#dependentsSection').show();
               } else {
                   $('#dependentsSection').hide();
                   $('#dependentsList').empty();
                   dependentCount = 0;
               }
               calculatePremium();
           });
           
           // Premium calculation triggers
           $('#coverage_amount, #premium_frequency, #primary_dob, #occupation_risk, #medical_history').on('change', function() {
               calculatePremium();
           });
           
           // Lifestyle factors change
           $('input[name="lifestyle_factors[]"]').on('change', function() {
               updateRiskAssessment();
               calculatePremium();
           });
           
           // Form validation
           $('#quoteForm').on('submit', function(e) {
               if (!validateCurrentStep()) {
                   e.preventDefault();
                   e.stopPropagation();
               }
           });
           
           // Initialize
           updateStepDisplay();
           calculatePremium();
       });
       
       function changeStep(direction) {
           if (direction === 1) {
               // Moving forward - validate current step
               if (!validateCurrentStep()) {
                   return;
               }
               
               if (currentStep < totalSteps) {
                   currentStep++;
               }
           } else {
               // Moving backward
               if (currentStep > 1) {
                   currentStep--;
               }
           }
           
           updateStepDisplay();
           
           // Update summary on last step
           if (currentStep === 4) {
               updateQuoteSummary();
           }
       }
       
       function updateStepDisplay() {
           // Hide all steps
           $('.wizard-step').removeClass('active');
           
           // Show current step
           $(`#step${currentStep}`).addClass('active');
           
           // Update step indicators
           $('.step-item').each(function(index) {
               const stepNum = index + 1;
               $(this).removeClass('active completed');
               
               if (stepNum === currentStep) {
                   $(this).addClass('active');
               } else if (stepNum < currentStep) {
                   $(this).addClass('completed');
               }
           });
           
           // Update navigation buttons
           $('#prevBtn').toggle(currentStep > 1);
           $('#nextBtn').toggle(currentStep < totalSteps);
           $('#submitBtn').toggle(currentStep === totalSteps);
       }
       
       function validateCurrentStep() {
           let isValid = true;
           const currentStepElement = $(`#step${currentStep}`);
           
           // Reset validation
           currentStepElement.find('.is-invalid').removeClass('is-invalid');
           
           // Validate required fields in current step
           currentStepElement.find('[required]').each(function() {
               if (!$(this).val()) {
                   $(this).addClass('is-invalid');
                   isValid = false;
               }
           });
           
           // Step-specific validation
           switch (currentStep) {
               case 1:
                   if (!$('input[name="product_id"]:checked').length) {
                       Swal.fire({
                           icon: 'warning',
                           title: 'Product Required',
                           text: 'Please select an insurance product.',
                           confirmButtonText: 'OK'
                       });
                       isValid = false;
                   }
                   break;
                   
               case 2:
                   const coverageAmount = parseFloat($('#coverage_amount').val());
                   if (coverageAmount < 1000) {
                       $('#coverage_amount').addClass('is-invalid');
                       isValid = false;
                   }
                   
                   // Validate age if DOB is provided
                   const dob = $('#primary_dob').val();
                   if (dob) {
                       const age = calculateAge(dob);
                       const selectedProduct = $('input[name="product_id"]:checked');
                       if (selectedProduct.length) {
                           const minAge = parseInt(selectedProduct.data('age-min'));
                           const maxAge = parseInt(selectedProduct.data('age-max'));
                           
                           if (age < minAge || age > maxAge) {
                               Swal.fire({
                                   icon: 'warning',
                                   title: 'Age Restriction',
                                   text: `Age must be between ${minAge} and ${maxAge} years for this product.`,
                                   confirmButtonText: 'OK'
                               });
                               $('#primary_dob').addClass('is-invalid');
                               isValid = false;
                           }
                       }
                   }
                   break;
           }
           
           return isValid;
       }
       
       function updateCustomerInfo() {
           const customerId = $('#customer_id').val();
           const leadId = $('#lead_id').val();
           
           if (customerId) {
               const selectedOption = $('#customer_id option:selected');
               const customerName = selectedOption.text();
               const email = selectedOption.data('email');
               const phone = selectedOption.data('phone');
               
               $('#customerDetails').html(`
                   <p class="mb-1"><strong>${customerName}</strong></p>
                   <p class="mb-1 small text-muted">📧 ${email}</p>
                   <p class="mb-0 small text-muted">📞 ${phone}</p>
               `);
               $('#selectedCustomerInfo').show();
               
               // Auto-fill primary name if not already filled
               if (!$('#primary_name').val()) {
                   const nameParts = customerName.split(' ');
                   const cleanName = nameParts.slice(0, -1).join(' '); // Remove customer number
                   $('#primary_name').val(cleanName);
               }
           } else if (leadId) {
               const selectedOption = $('#lead_id option:selected');
               const leadName = selectedOption.text();
               const email = selectedOption.data('email');
               const phone = selectedOption.data('phone');
               const interest = selectedOption.data('interest');
               
               $('#customerDetails').html(`
                   <p class="mb-1"><strong>${leadName}</strong></p>
                   <p class="mb-1 small text-muted">📧 ${email}</p>
                   <p class="mb-1 small text-muted">📞 ${phone}</p>
                   <p class="mb-0 small text-primary">Interest: ${interest}</p>
               `);
               $('#selectedCustomerInfo').show();
               
               // Auto-fill primary name if not already filled
               if (!$('#primary_name').val()) {
                   const nameParts = leadName.split(' ');
                   const cleanName = nameParts.slice(0, -1).join(' '); // Remove lead number
                   $('#primary_name').val(cleanName);
               }
           } else {
               $('#selectedCustomerInfo').hide();
           }
       }
       
       function updateProductInfo() {
           const selectedProduct = $('input[name="product_id"]:checked');
           
           if (selectedProduct.length) {
               const productCard = selectedProduct.closest('.product-card');
               const productName = productCard.find('h6').text();
               const companyName = productCard.find('.text-muted').text();
               const category = productCard.find('.badge').text();
               const basePremium = selectedProduct.data('base-premium');
               const commission = selectedProduct.data('commission');
               
               $('#productDetails').html(`
                   <p class="mb-1"><strong>${productName}</strong></p>
                   <p class="mb-1 small text-muted">${companyName}</p>
                   <p class="mb-1"><span class="badge bg-primary">${category}</span></p>
                   ${basePremium ? `<p class="mb-1 small text-success">Base: KSH ${formatNumber(basePremium)}</p>` : ''}
                   <p class="mb-0 small text-info">Commission: ${commission}%</p>
               `);
               $('#selectedProductInfo').show();
           } else {
               $('#selectedProductInfo').hide();
           }
       }
       
       function addDependent() {
           dependentCount++;
           const dependentHtml = `
               <div class="dependent-row" id="dependent_${dependentCount}">
                   <div class="d-flex justify-content-between align-items-center mb-2">
                       <h6 class="mb-0">Dependent ${dependentCount}</h6>
                       <button type="button" class="btn btn-sm btn-outline-danger" 
                               onclick="removeDependent(${dependentCount})">
                           <i class="ri-close-line"></i>
                       </button>
                   </div>
                   <div class="row">
                       <div class="col-md-4 mb-2">
                           <input type="text" class="form-control form-control-sm" 
                                  name="dependents[${dependentCount}][name]" placeholder="Full Name" required>
                       </div>
                       <div class="col-md-3 mb-2">
                           <input type="date" class="form-control form-control-sm" 
                                  name="dependents[${dependentCount}][dob]" required>
                       </div>
                       <div class="col-md-2 mb-2">
                           <select class="form-select form-select-sm" name="dependents[${dependentCount}][gender]" required>
                               <option value="">Gender</option>
                               <option value="MALE">Male</option>
                               <option value="FEMALE">Female</option>
                           </select>
                       </div>
                       <div class="col-md-3 mb-2">
                           <select class="form-select form-select-sm" name="dependents[${dependentCount}][relationship]" required>
                               <option value="">Relationship</option>
                               <option value="SPOUSE">Spouse</option>
                               <option value="CHILD">Child</option>
                               <option value="PARENT">Parent</option>
                               <option value="SIBLING">Sibling</option>
                               <option value="OTHER">Other</option>
                           </select>
                       </div>
                   </div>
               </div>
           `;
           
           $('#dependentsList').append(dependentHtml);
           
           // Initialize date picker for new dependent
           flatpickr(`input[name="dependents[${dependentCount}][dob]"]`, {
               dateFormat: "Y-m-d",
               allowInput: true,
               maxDate: "today"
           });
       }
       
       function removeDependent(id) {
           $(`#dependent_${id}`).remove();
           calculatePremium();
       }
       
       function calculatePremium() {
           const selectedProduct = $('input[name="product_id"]:checked');
           const coverageAmount = parseFloat($('#coverage_amount').val()) || 0;
           const frequency = $('#premium_frequency').val();
           const dob = $('#primary_dob').val();
           const occupationRisk = $('#occupation_risk').val();
           const medicalHistory = $('#medical_history').val();
           
           if (!selectedProduct.length || !coverageAmount || !frequency) {
               return;
           }
           
           let basePremium = parseFloat(selectedProduct.data('base-premium')) || 0;
           
           // If no base premium, calculate from coverage amount
           if (basePremium === 0) {
               basePremium = coverageAmount * 0.05; // 5% default rate
           }
           
           // Apply frequency multiplier
           const frequencyMultipliers = {
               'MONTHLY': 12,
               'QUARTERLY': 4,
               'SEMI_ANNUAL': 2,
               'ANNUAL': 1
           };
           
           basePremium = basePremium / (frequencyMultipliers[frequency] || 1);
           
           // Calculate risk adjustments
           let riskLoading = 0;
           let discount = 0;
           
           // Age-based adjustments
           if (dob) {
               const age = calculateAge(dob);
               if (age > 50) {
                   riskLoading += basePremium * 0.1; // 10% loading
               }
               if (age < 25) {
                   discount += basePremium * 0.05; // 5% discount
               }
           }
           
           // Occupation risk
           switch (occupationRisk) {
               case 'HIGH':
                   riskLoading += basePremium * 0.2; // 20% loading
                   break;
               case 'MEDIUM':
                   riskLoading += basePremium * 0.1; // 10% loading
                   break;
           }
           
           // Medical history
           switch (medicalHistory) {
               case 'SERIOUS':
                   riskLoading += basePremium * 0.25; // 25% loading
                   break;
               case 'CHRONIC':
                   riskLoading += basePremium * 0.15; // 15% loading
                   break;
               case 'MINOR':
                   riskLoading += basePremium * 0.05; // 5% loading
                   break;
           }
           
           // Lifestyle factors
           const lifestyleFactors = $('input[name="lifestyle_factors[]"]:checked').length;
           riskLoading += basePremium * (lifestyleFactors * 0.05); // 5% per factor
           
           // Count dependents
           const dependents = $('#dependentsList .dependent-row').length;
           const totalPremium = (basePremium + riskLoading - discount) * (1 + dependents * 0.5);
           
           // Calculate additional charges
           const policyFee = Math.max(totalPremium * 0.005, 100);
           const stampDuty = totalPremium * 0.002;
           const vat = totalPremium * 0.16;
           const finalPremium = totalPremium + policyFee + stampDuty + vat;
           
           // Update displays
           $('#basePremiumDisplay').text(`KSH ${formatNumber(basePremium)}`);
           $('#riskLoadingDisplay').text(`KSH ${formatNumber(riskLoading)}`);
           $('#discountDisplay').text(`- KSH ${formatNumber(discount)}`);
           $('#totalPremiumDisplay').text(`KSH ${formatNumber(totalPremium)}`);
           $('#policyFeeDisplay').text(`KSH ${formatNumber(policyFee)}`);
           $('#stampDutyDisplay').text(`KSH ${formatNumber(stampDuty)}`);
           $('#vatDisplay').text(`KSH ${formatNumber(vat)}`);
           $('#finalPremiumDisplay').text(`KSH ${formatNumber(finalPremium)}`);
           
           // Update frequency note
           const frequencyMap = {
               'MONTHLY': 'Monthly',
               'QUARTERLY': 'Quarterly',
               'SEMI_ANNUAL': 'Semi-Annual',
               'ANNUAL': 'Annual'
           };
           $('#frequencyNote').text(`${frequencyMap[frequency] || ''} premium calculation`);
           
           // Update risk assessment
           updateRiskAssessment();
       }
       
       function updateRiskAssessment() {
           const dob = $('#primary_dob').val();
           const occupationRisk = $('#occupation_risk').val();
           const medicalHistory = $('#medical_history').val();
           const lifestyleFactors = $('input[name="lifestyle_factors[]"]:checked').length;
           
           // Age factor
           let ageFactor = 'Low Risk';
           let ageClass = 'bg-success';
           if (dob) {
               const age = calculateAge(dob);
               if (age > 60) {
                   ageFactor = 'High Risk';
                   ageClass = 'bg-danger';
               } else if (age > 45) {
                   ageFactor = 'Medium Risk';
                   ageClass = 'bg-warning';
               }
           }
           
           // Occupation factor
           const occupationMap = {
               'HIGH': ['High Risk', 'bg-danger'],
               'MEDIUM': ['Medium Risk', 'bg-warning'],
               'LOW': ['Low Risk', 'bg-success']
           };
           const [occupationText, occupationClass] = occupationMap[occupationRisk] || ['Low Risk', 'bg-success'];
           
           // Medical factor
           const medicalMap = {
               'SERIOUS': ['High Risk', 'bg-danger'],
               'CHRONIC': ['Medium Risk', 'bg-warning'],
               'MINOR': ['Low Risk', 'bg-success'],
               'NONE': ['Low Risk', 'bg-success']
           };
           const [medicalText, medicalClass] = medicalMap[medicalHistory] || ['Low Risk', 'bg-success'];
           
           // Overall risk
           let overallRisk = 'Low Risk';
           let overallClass = 'bg-success';
           const riskScore = (occupationRisk === 'HIGH' ? 3 : occupationRisk === 'MEDIUM' ? 2 : 1) +
                            (medicalHistory === 'SERIOUS' ? 3 : medicalHistory === 'CHRONIC' ? 2 : 1) +
                            lifestyleFactors;
           
           if (riskScore >= 6) {
               overallRisk = 'High Risk';
               overallClass = 'bg-danger';
           } else if (riskScore >= 4) {
               overallRisk = 'Medium Risk';
               overallClass = 'bg-warning';
           }
           
           // Update display
           $('#ageFactor').removeClass('bg-success bg-warning bg-danger').addClass(ageClass).text(ageFactor);
           $('#occupationFactor').removeClass('bg-success bg-warning bg-danger').addClass(occupationClass).text(occupationText);
           $('#medicalFactor').removeClass('bg-success bg-warning bg-danger').addClass(medicalClass).text(medicalText);
           $('#overallRisk').removeClass('bg-success bg-warning bg-danger').addClass(overallClass).text(overallRisk);
       }
       
       function updateQuoteSummary() {
           const customerName = $('#primary_name').val() || 'Not specified';
           const selectedProduct = $('input[name="product_id"]:checked');
           const productName = selectedProduct.length ? selectedProduct.closest('.product-card').find('h6').text() : 'Not selected';
           const coverageAmount = $('#coverage_amount').val() || '0';
           const quoteType = $('#quote_type').val() || 'Not selected';
           const frequency = $('#premium_frequency').val() || 'Not selected';
           const validity = $('input[name="validity_days"]').val() || '30';
           
           const summaryHtml = `
               <div class="row">
                   <div class="col-md-6">
                       <h6 class="text-primary mb-3">Quote Details</h6>
                       <table class="table table-sm">
                           <tr><td><strong>Primary Insured:</strong></td><td>${customerName}</td></tr>
                           <tr><td><strong>Product:</strong></td><td>${productName}</td></tr>
                           <tr><td><strong>Quote Type:</strong></td><td>${quoteType}</td></tr>
                           <tr><td><strong>Coverage Amount:</strong></td><td>KSH ${formatNumber(coverageAmount)}</td></tr>
                           <tr><td><strong>Premium Frequency:</strong></td><td>${frequency}</td></tr>
                           <tr><td><strong>Validity:</strong></td><td>${validity} days</td></tr>
                       </table>
                   </div>
                   <div class="col-md-6">
                       <h6 class="text-primary mb-3">Risk Assessment</h6>
                       <div class="mb-2">
                           <span>Age Factor: </span>
                           <span id="summaryAgeFactor" class="badge">${$('#ageFactor').text()}</span>
                       </div>
                       <div class="mb-2">
                           <span>Occupation: </span>
                           <span id="summaryOccupationFactor" class="badge">${$('#occupationFactor').text()}</span>
                       </div>
                       <div class="mb-2">
                           <span>Medical: </span>
                           <span id="summaryMedicalFactor" class="badge">${$('#medicalFactor').text()}</span>
                       </div>
                       <div class="mb-2">
                           <span>Overall Risk: </span>
                           <span id="summaryOverallRisk" class="badge">${$('#overallRisk').text()}</span>
                       </div>
                   </div>
               </div>
           `;
           
           const finalPremiumSummaryHtml = `
               <div class="premium-breakdown">
                   <div class="d-flex justify-content-between mb-2">
                       <span>Base Premium:</span>
                       <span>${$('#basePremiumDisplay').text()}</span>
                   </div>
                   <div class="d-flex justify-content-between mb-2">
                       <span>Risk Loading:</span>
                       <span>${$('#riskLoadingDisplay').text()}</span>
                   </div>
                   <div class="d-flex justify-content-between mb-2">
                       <span>Discount:</span>
                       <span class="text-success">${$('#discountDisplay').text()}</span>
                   </div>
                   <hr>
                   <div class="d-flex justify-content-between mb-2 fw-bold">
                       <span>Subtotal:</span>
                       <span>${$('#totalPremiumDisplay').text()}</span>
                   </div>
                   <div class="d-flex justify-content-between mb-1 small">
                       <span>Policy Fee:</span>
                       <span>${$('#policyFeeDisplay').text()}</span>
                   </div>
                   <div class="d-flex justify-content-between mb-1 small">
                       <span>Stamp Duty:</span>
                       <span>${$('#stampDutyDisplay').text()}</span>
                   </div>
                   <div class="d-flex justify-content-between mb-2 small">
                       <span>VAT (16%):</span>
                       <span>${$('#vatDisplay').text()}</span>
                   </div>
                   <hr>
                   <div class="d-flex justify-content-between fw-bold fs-5 text-success">
                       <span>TOTAL PREMIUM:</span>
                       <span>${$('#finalPremiumDisplay').text()}</span>
                   </div>
               </div>
           `;
           
           $('#quoteSummary').html(summaryHtml);
           $('#finalPremiumSummary').html(finalPremiumSummaryHtml);
           
           // Copy badge classes
           $('#summaryAgeFactor').addClass($('#ageFactor').attr('class').replace('badge ', ''));
           $('#summaryOccupationFactor').addClass($('#occupationFactor').attr('class').replace('badge ', ''));
           $('#summaryMedicalFactor').addClass($('#medicalFactor').attr('class').replace('badge ', ''));
           $('#summaryOverallRisk').addClass($('#overallRisk').attr('class').replace('badge ', ''));
       }
       
       function calculateAge(dateString) {
           const today = new Date();
           const birthDate = new Date(dateString);
           let age = today.getFullYear() - birthDate.getFullYear();
           const monthDiff = today.getMonth() - birthDate.getMonth();
           
           if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
               age--;
           }
           
           return age;
       }
       
       function formatNumber(num) {
           if (!num || num === '') return '0.00';
           return parseFloat(num).toLocaleString('en-US', {
               minimumFractionDigits: 2,
               maximumFractionDigits: 2
           });
       }
   </script>
   
   <!-- App js -->
   <script src="assets/js/app.js"></script>
</body>
</html>