<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../includes/lang.php';
require_once __DIR__ . '/../db/config.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => __('unauthorized')]);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

if (!$input || empty($input['symbol']) || empty($input['amount'])) {
    echo json_encode(['success' => false, 'error' => __('fill_all_fields')]);
    exit;
}

$userId = $_SESSION['user_id'];
$symbol = strtoupper($input['symbol']);
$poolName = $input['pool_name'];
$amount = (float)$input['amount'];
$apy = (float)str_replace('%', '', $input['apy']);
$periodStr = $input['period'];
$dailyProfit = $apy / 365;

// Check balance
$stmt = db()->prepare("SELECT available FROM user_balances WHERE user_id = ? AND symbol = ?");
$stmt->execute([$userId, $symbol]);
$balance = $stmt->fetch();

if (!$balance || $balance['available'] < $amount) {
    echo json_encode(['success' => false, 'error' => __('insufficient_balance')]);
    exit;
}

try {
    $db = db();
    $db->beginTransaction();

    // Deduct balance
    $stmt = $db->prepare("UPDATE user_balances SET available = available - ?, frozen = frozen + ? WHERE user_id = ? AND symbol = ?");
    $stmt->execute([$amount, $amount, $userId, $symbol]);

    // Create staking record
    $period = 0;
    if (preg_match('/(\d+)/', $periodStr, $matches)) {
        $period = (int)$matches[1];
    } else {
        $period = 0; // flexible
    }
    
    $startDate = date('Y-m-d');
    $endDate = date('Y-m-d', strtotime("+$period days"));
    if ($period == 0) $endDate = '2099-12-31';

    $stmt = $db->prepare("INSERT INTO staking_records (user_id, plan_name, amount, symbol, daily_profit, period, status, start_date, end_date, last_settle_time, ip_address) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?)");
    $stmt->execute([$userId, $poolName, $amount, $symbol, $dailyProfit, $period, 'running', $startDate, $endDate, getRealIP()]);

    // Add transaction record
    $stmt = $db->prepare("INSERT INTO transactions (user_id, symbol, type, amount, status, ip_address) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([$userId, $symbol, 'mining_invest', $amount, 'completed', getRealIP()]);

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