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

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

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

try {
    // Get form data
    $full_desc = $_POST['full_desc'] ?? '';
    $corp_id = $_POST['corp_id'] ?? null;
    $agent_name = $_POST['agent_name'] ?? null; // This is actually the insurer/agent ID
    $benefit = $_POST['benefit'] ?? null;
    $limit = $_POST['limit'] ?? null;
    $premium = $_POST['premium'] ?? null;
    $family_size = $_POST['family_size'] ?? null;
    $year = $_POST['year'] ?? null;
    
    // Set agent_name as insurer to maintain compatibility with database schema
    $insurer = $agent_name;

    // Validate required fields
    if (empty($full_desc)) {
        throw new Exception('Description is required');
    }

    if (empty($agent_name)) {
        throw new Exception('Agent is required');
    }

    if (empty($benefit)) {
        throw new Exception('Benefit is required');
    }

    if (!is_numeric($limit) || $limit <= 0) {
        throw new Exception('Limit must be a positive number');
    }

    if (!is_numeric($premium) || $premium <= 0) {
        throw new Exception('Premium must be a positive number');
    }

    if (empty($year) || !is_numeric($year)) {
        throw new Exception('Year is required and must be a number');
    }

    // Check if a rate with the same properties already exists
    $sql_check = "SELECT COUNT(*) as count FROM insuring_rates 
                WHERE benefit = ? 
                AND " . ($corp_id ? "corp_id = ?" : "corp_id IS NULL") . "
                AND " . ($family_size ? "family_size = ?" : "family_size IS NULL") . "
                AND year = ?";

    $stmt_check = $conn->prepare($sql_check);
    
    if ($corp_id && $family_size) {
        $stmt_check->bind_param('issi', $benefit, $corp_id, $family_size, $year);
    } elseif ($corp_id && !$family_size) {
        $stmt_check->bind_param('isi', $benefit, $corp_id, $year);
    } elseif (!$corp_id && $family_size) {
        $stmt_check->bind_param('isi', $benefit, $family_size, $year);
    } else {
        $stmt_check->bind_param('ii', $benefit, $year);
    }
    
    $stmt_check->execute();
    $result_check = $stmt_check->get_result();
    $row_check = $result_check->fetch_assoc();

    if ($row_check['count'] > 0) {
        throw new Exception('A rate with these properties already exists');
    }

    // Insert new rate
    $sql = "INSERT INTO insuring_rates 
            (full_desc, corp_id, benefit, `limit`, family_size, premium, client, year, insurer)
            VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?)";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ssidsdii', $full_desc, $corp_id, $benefit, $limit, $family_size, $premium, $year, $insurer);
    $stmt->execute();

    if ($stmt->affected_rows === 0) {
        throw new Exception('Failed to insert rate');
    }

    $rateId = $stmt->insert_id;

    // Log activity
    $sql_log = "INSERT INTO activity_log 
                (user_id, action, table_name, record_id, new_values, ip_address, user_agent)
                VALUES (?, 'CREATE', 'insuring_rates', ?, ?, ?, ?)";
    
    $stmt_log = $conn->prepare($sql_log);
    $user_id = $_SESSION['user_id'];
    $new_values = json_encode($_POST);
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    
    $stmt_log->bind_param('sisss', $user_id, $rateId, $new_values, $ip_address, $user_agent);
    $stmt_log->execute();

    // Return success
    echo json_encode(['success' => true, 'rate_id' => $rateId]);

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}

$conn->close();
?>