<?php
session_start();
include '../session.php';

// Check if user has API access
$check_sql = "SELECT tbp.has_api_access 
              FROM user_bot_subscriptions ubs
              JOIN trading_bot_plans tbp ON ubs.bot_plan_id = tbp.id
              WHERE ubs.user_id = '$user_id' AND ubs.status = 'active' 
              AND tbp.has_api_access = 1
              LIMIT 1";
$check_result = mysqli_query($conn, $check_sql);

if (!$check_result || mysqli_num_rows($check_result) === 0) {
    echo json_encode(['success' => false, 'message' => 'API access not available for your current plan']);
    exit;
}

// Validate input
$required = ['key_name', 'permissions'];
foreach ($required as $field) {
    if (empty($_POST[$field])) {
        echo json_encode(['success' => false, 'message' => "Missing required field: $field"]);
        exit;
    }
}

$key_name = mysqli_real_escape_string($conn, $_POST['key_name']);
$permissions = in_array($_POST['permissions'], ['read', 'trade', 'full']) 
    ? $_POST['permissions'] 
    : 'read';
$ip_restrictions = !empty($_POST['ip_restrictions']) 
    ? mysqli_real_escape_string($conn, $_POST['ip_restrictions']) 
    : null;

// Generate API key and secret
function generateApiKey() {
    return 'sk_' . bin2hex(random_bytes(24));
}

function generateApiSecret() {
    return bin2hex(random_bytes(32));
}

$api_key = generateApiKey();
$api_secret = generateApiSecret();

// Check max API keys limit (5 per user)
$count_sql = "SELECT COUNT(*) as key_count FROM user_api_keys WHERE user_id = '$user_id' AND status = 'active'";
$count_result = mysqli_query($conn, $count_sql);
$count_row = mysqli_fetch_assoc($count_result);

if ($count_row['key_count'] >= 5) {
    echo json_encode(['success' => false, 'message' => 'Maximum of 5 active API keys allowed']);
    exit;
}

// Insert API key
$insert_sql = "INSERT INTO user_api_keys 
               (user_id, key_name, api_key, api_secret, permissions, ip_restrictions, status, created_at) 
               VALUES ('$user_id', '$key_name', '$api_key', '$api_secret', '$permissions', 
                       '$ip_restrictions', 'active', NOW())";

if (mysqli_query($conn, $insert_sql)) {
    echo json_encode([
        'success' => true,
        'message' => 'API key generated successfully',
        'api_key' => $api_key,
        'api_secret' => $api_secret, // Only shown once!
        'key_name' => $key_name,
        'permissions' => $permissions
    ]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to generate API key: ' . mysqli_error($conn)]);
}
?>