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

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Not authenticated']);
    exit;
}

try {
    // Get input data
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['corp_id']) || !isset($data['member'])) {
        throw new Exception('Missing required data');
    }

    // Log incoming data
    error_log("Received data for premium calculation: " . print_r($data, true));

    // Initialize calculator
    $calculator = new PremiumCalculator($conn, $data['corp_id']);

    // Structure member data for validation
    $member_data = [
        'relation' => $data['member']['relation'],
        'age' => (int)$data['member']['age'],
        'benefits' => $data['member']['benefits']
    ];

    // Validate member data
    $validation_errors = $calculator->validateMemberLimits($member_data);
    if (!empty($validation_errors)) {
        throw new Exception(implode(", ", $validation_errors));
    }

    // Calculate premium
    $premium_details = $calculator->calculatePremium($member_data);

    // Return premium details
    echo json_encode([
        'success' => true,
        'premium_details' => $premium_details,
        'total_premium' => $premium_details['total_premium'],
        'grand_total' => $premium_details['grand_total']
    ]);

} catch (Exception $e) {
    error_log("Error in premium calculation: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>