<?php
// File: ajax/calculate_premium.php

// Include database connection
include '../layouts/dbconn.php';

// Check if required data is submitted
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || 
    !isset($_POST['product_id']) || empty($_POST['product_id']) || 
    !isset($_POST['sum_insured']) || empty($_POST['sum_insured'])) {
    
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit;
}

$productId = (int)$_POST['product_id'];
$sumInsured = (float)$_POST['sum_insured'];
$selectedRiders = isset($_POST['riders']) ? $_POST['riders'] : [];

// Get product details
$productQuery = "SELECT * FROM insurance_products WHERE id = ?";
$stmt = $conn->prepare($productQuery);
$stmt->bind_param('i', $productId);
$stmt->execute();
$productResult = $stmt->get_result();

if ($productResult->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Product not found']);
    exit;
}

$product = $productResult->fetch_assoc();

// Calculate base premium
$basePremium = $sumInsured * $product['base_premium_rate'];

// Calculate premium for selected riders
$ridersPremium = 0;

foreach ($selectedRiders as $riderId) {
    $riderQuery = "SELECT * FROM product_riders WHERE id = ?";
    $stmt = $conn->prepare($riderQuery);
    $stmt->bind_param('i', $riderId);
    $stmt->execute();
    $riderResult = $stmt->get_result();
    $rider = $riderResult->fetch_assoc();
    
    if ($rider) {
        if ($rider['premium_calculation_type'] === 'fixed') {
            $riderPremium = $rider['premium_value'];
        } else { // percentage
            $riderPremium = $basePremium * ($rider['premium_value'] / 100);
        }
        
        $ridersPremium += $riderPremium;
    }
}

// Calculate tax
$taxAmount = ($basePremium + $ridersPremium) * ($product['tax_rate'] / 100);

// Calculate total premium
$totalPremium = $basePremium + $ridersPremium + $taxAmount;

// Return premium calculation
echo json_encode([
    'success' => true,
    'base_premium' => $basePremium,
    'riders_premium' => $ridersPremium,
    'tax_amount' => $taxAmount,
    'tax_rate' => $product['tax_rate'],
    'total_premium' => $totalPremium
]);
?>