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

// Check if user is admin
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Insufficient permissions. Not Authorized.']);
    exit;
}

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

try {
    // Validate required fields
    $required = ['corp_id', 'category_code', 'benefit_code'];
    foreach ($required as $field) {
        if (!isset($_POST[$field]) || empty($_POST[$field])) {
            throw new Exception("Missing required field: $field");
        }
    }

    // Start transaction
    $conn->begin_transaction();

    // Check if rule exists
    $sql = "SELECT rule_id FROM benefit_rules 
            WHERE corp_id = ? AND category_code = ? AND benefit_code = ?";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('sss', $_POST['corp_id'], $_POST['category_code'], $_POST['benefit_code']);
    $stmt->execute();
    $result = $stmt->get_result();
    $existing = $result->fetch_assoc();

    if ($existing) {
        // Update existing rule
        $sql = "UPDATE benefit_rules SET 
                is_waitingperiod = ?,
                waiting_days = ?,
                waiting_months = ?,
                is_autogrowth = ?,
                autogrowth_rate_type = ?,
                autogrowth_rate = ?,
                autogrowth_min = ?,
                autogrowth_max = ?,
                is_buffer = ?,
                buffer_type = ?,
                buffer_limit = ?,
                is_frequency = ?,
                frequency_limit = ?,
                updated_by = ?,
                updated_at = CURRENT_TIMESTAMP
                WHERE rule_id = ?";

        $stmt = $conn->prepare($sql);
        $stmt->bind_param('iiiiidiiisdiiis', 
            $_POST['is_waitingperiod'] ?? 0,
            $_POST['waiting_days'] ?? null,
            $_POST['waiting_months'] ?? null,
            $_POST['is_autogrowth'] ?? 0,
            $_POST['autogrowth_rate_type'] ?? null,
            $_POST['autogrowth_rate'] ?? null,
            $_POST['autogrowth_min'] ?? null,
            $_POST['autogrowth_max'] ?? null,
            $_POST['is_buffer'] ?? 0,
            $_POST['buffer_type'] ?? null,
            $_POST['buffer_limit'] ?? null,
            $_POST['is_frequency'] ?? 0,
            $_POST['frequency_limit'] ?? null,
            $_SESSION['user_id'],
            $existing['rule_id']
        );

    } else {
        // Insert new rule
        $sql = "INSERT INTO benefit_rules (
                corp_id, category_code, benefit_code,
                is_waitingperiod, waiting_days, waiting_months,
                is_autogrowth, autogrowth_rate_type, autogrowth_rate,
                autogrowth_min, autogrowth_max,
                is_buffer, buffer_type, buffer_limit,
                is_frequency, frequency_limit,
                created_by
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        $stmt = $conn->prepare($sql);
        $stmt->bind_param('sssiiiisiiisdiiis',
            $_POST['corp_id'],
            $_POST['category_code'],
            $_POST['benefit_code'],
            $_POST['is_waitingperiod'] ?? 0,
            $_POST['waiting_days'] ?? null,
            $_POST['waiting_months'] ?? null,
            $_POST['is_autogrowth'] ?? 0,
            $_POST['autogrowth_rate_type'] ?? null,
            $_POST['autogrowth_rate'] ?? null,
            $_POST['autogrowth_min'] ?? null,
            $_POST['autogrowth_max'] ?? null,
            $_POST['is_buffer'] ?? 0,
            $_POST['buffer_type'] ?? null,
            $_POST['buffer_limit'] ?? null,
            $_POST['is_frequency'] ?? 0,
            $_POST['frequency_limit'] ?? null,
            $_SESSION['user_id']
        );
    }

    if (!$stmt->execute()) {
        throw new Exception("Failed to save rule: " . $stmt->error);
    }

    // Log the action
    $action = $existing ? 'UPDATE' : 'CREATE';
    $sql = "INSERT INTO activity_log (
            user_id, action, table_name, record_id, new_values, action_date
        ) VALUES (?, ?, 'benefit_rules', ?, ?, NOW())";
        
    $stmt = $conn->prepare($sql);
    $newValues = json_encode($_POST);
    $recordId = $existing ? $existing['rule_id'] : $conn->insert_id;
    $stmt->bind_param('ssss', $_SESSION['user_id'], $action, $recordId, $newValues);
    $stmt->execute();

    // Commit transaction
    $conn->commit();

    echo json_encode(['success' => true, 'message' => 'Benefit rule saved successfully']);

} catch (Exception $e) {
    if ($conn->inTransaction()) {
        $conn->rollback();
    }
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}

$conn->close();
?>