<?php
/**
 * SmartForex Engine - Advanced Admin Operational Interface API
 * Location: public_html/api/admin_action.php
 */

error_reporting(0);
ini_set('display_errors', 0);

define('DB_HOST', 'localhost');
define('DB_NAME', 'rakshita_relay');
define('DB_USER', 'rakshita_relay');
define('DB_PASS', 'rehman@169');

try {
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
} catch (PDOException $e) {
    exit(json_encode(['status' => 'error', 'message' => 'Node offline']));
}

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

$action = $_POST['action'] ?? '';

if ($action === 'update_balance') {
    $user_id = intval($_POST['user_id'] ?? 0);
    $amount = floatval($_POST['amount'] ?? 0);
    $operation = $_POST['operation'] ?? 'add';

    $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();

    if (!$user) { exit(json_encode(['status' => 'error', 'message' => 'User missing'])); }

    $new_balance = ($operation === 'subtract') ? (floatval($user['balance']) - $amount) : (floatval($user['balance']) + $amount);
    
    $update = $pdo->prepare("UPDATE users SET balance = ? WHERE id = ?");
    $update->execute([$new_balance, $user_id]);
    exit(json_encode(['status' => 'success', 'message' => 'Balance modified successfully']));
}

if ($action === 'fetch_history') {
    $user_id = intval($_POST['user_id'] ?? 0);
    $stmt = $pdo->prepare("SELECT symbol, type, amount, leverage, entry_price, close_price, profit_loss, status, opened_at FROM trades WHERE user_id = ? ORDER BY id DESC");
    $stmt->execute([$user_id]);
    $trades = $stmt->fetchAll();
    
    // HTML output generation for column view inside admin framework
    $html = '<table>
                <thead>
                    <tr><th>Date</th><th>Asset</th><th>Type</th><th>Margin</th><th>Lev</th><th>Entry</th><th>Close</th><th>P&L</th><th>Status</th></tr>
                </thead>
                <tbody>';
    if(empty($trades)){
        $html .= '<tr><td colspan="9" style="text-align:center;">No trades logged.</td></tr>';
    } else {
        foreach($trades as $t){
            $pnlColor = floatval($t['profit_loss']) >= 0 ? '#00ff88' : '#ff3366';
            $html .= '<tr>
                        <td>'.$t['opened_at'].'</td>
                        <td style="font-weight:bold;">'.$t['symbol'].'</td>
                        <td style="text-transform:uppercase;">'.$t['type'].'</td>
                        <td>$'.number_format($t['amount'],2).'</td>
                        <td>'.$t['leverage'].'x</td>
                        <td>$'.number_format($t['entry_price'],2).'</td>
                        <td>$'.($t['close_price'] ? number_format($t['close_price'],2) : 'Open').'</td>
                        <td style="color:'.$pnlColor.'; font-weight:bold;">$'.number_format($t['profit_loss'],2).'</td>
                        <td style="text-transform:uppercase;">'.$t['status'].'</td>
                      </tr>';
        }
    }
    $html .= '</tbody></table>';
    exit(json_encode(['status' => 'success', 'html' => $html]));
}

if ($action === 'kyc_action') {
    $user_id = intval($_POST['user_id'] ?? 0);
    $status = $_POST['status'] ?? 'approved'; // approved or rejected
    
    $update = $pdo->prepare("UPDATE users SET kyc_status = ? WHERE id = ?");
    $update->execute([$status, $user_id]);
    exit(json_encode(['status' => 'success', 'message' => 'KYC status modified to ' . $status]));
}