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

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

if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Not authorized']);
    exit;
}

try {
    $user_id = $_SESSION['user_id'];
    
    // Check if this is an update
    if (isset($_POST['cap_id'])) {
        // Update existing cap
        $sql = "UPDATE benefit_caps SET 
                cap_value = ?,
                status = ?,
                modified_by = ?,
                modified_at = NOW()
                WHERE cap_id = ?";
                
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('dsii', 
            $_POST['cap_value'],
            $_POST['status'],
            $user_id,
            $_POST['cap_id']
        );
    } else {
        // Insert new cap
        $sql = "INSERT INTO benefit_caps (
            corp_id,
            benefit_code,
            cap_type,
            cap_value,
            period,
            status,
            created_by
        ) VALUES (?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('sisdssi',
            $_POST['corp_id'],
            $_POST['benefit_code'],
            $_POST['cap_type'],
            $_POST['cap_value'],
            $_POST['period'],
            $_POST['status'],
            $user_id
        );
    }
    
    if (!$stmt->execute()) {
        throw new Exception($stmt->error);
    }
    
    // Log the activity
    $sql = "INSERT INTO activity_log (
        user_id,
        action,
        table_name,
        record_id,
        new_values,
        action_date
    ) VALUES (?, ?, 'benefit_caps', ?, ?, NOW())";
    
    $action = isset($_POST['cap_id']) ? 'UPDATE' : 'CREATE';
    $record_id = isset($_POST['cap_id']) ? $_POST['cap_id'] : $conn->insert_id;
    $new_values = json_encode($_POST);
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('isss',
        $user_id,
        $action,
        $record_id,
        $new_values
    );
    $stmt->execute();
    
    echo json_encode([
        'success' => true,
        'message' => 'Benefit cap saved successfully'
    ]);

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

$conn->close();
?>