<?php
/**
 * SmartForex Engine - Financial Request Routing & Support Chat Pipeline
 * Location: public_html/api/assets_handler.php
 */
require_once __DIR__ . '/../includes/functions.php';
header('Content-Type: application/json');
check_user_auth();

// GET Requests handler (For fetching data via URL queries)
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $action = $_GET['action'] ?? '';

    // 1. FETCH COMBINED TRANSACTION LOGS (DEPOSIT, WITHDRAW, P&L)
    if ($action === 'fetch_combined_statement') {
        try {
            // Iss single query se deposit, withdrawal aur trades (P&L) sab sequence wise niklenge
            $stmt = $pdo->prepare("
                SELECT created_at AS date_time, type, amount, status 
                FROM transactions 
                WHERE user_id = ? 
                ORDER BY created_at DESC
            ");
            $stmt->execute([$_SESSION['user_id']]);
            $ledger = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Response return matrix
            $response = [];
            foreach ($ledger as $row) {
                // Formatting according to the frontend logic
                $type = $row['type'];
                if ($type === 'trade' || $type === 'pnl') {
                    $type = (floatval($row['amount']) >= 0) ? 'trade_profit' : 'trade_loss';
                }
                
                $response[] = [
                    'date'   => $row['date_time'],
                    'type'   => $type,
                    'amount' => abs(floatval($row['amount'])),
                    'status' => $row['status']
                ];
            }

            echo json_encode($response);
        } catch (PDOException $e) {
            echo json_encode(['status' => 'error', 'message' => 'Database pipeline error: ' . $e->getMessage()]);
        }
        exit;
    }

    // 2. FETCH SECURE CHAT LOGS LOOP
    if ($action === 'get_chat_stream') {
        try {
            $stmt = $pdo->prepare("SELECT sender, message_text, media_file, created_at FROM support_chats WHERE user_id = ? ORDER BY created_at ASC");
            $stmt->execute([$_SESSION['user_id']]);
            echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
        } catch (PDOException $e) {
            echo json_encode([]);
        }
        exit;
    }
}

// POST Requests handler (For form submissions)
$action = $_POST['action'] ?? '';

// 3. EXECUTE USER DEPOSIT REQUEST Node
if ($action === 'user_deposit') {
    $amount = floatval($_POST['amount'] ?? 0);
    if ($amount <= 0 || !isset($_FILES['proof_img'])) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid asset params matrix.']); exit;
    }

    $ext = pathinfo($_FILES['proof_img']['name'], PATHINFO_EXTENSION);
    $filename = 'proof_' . uniqid() . '.' . $ext;
    $target = __DIR__ . '/../uploads/' . $filename;

    if (move_uploaded_file($_FILES['proof_img']['tmp_name'], $target)) {
        $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, status, proof_file) VALUES (?, 'deposit', ?, 'pending', ?)");
        $stmt->execute([$_SESSION['user_id'], $amount, $filename]);
        echo json_encode(['status' => 'success', 'message' => 'Transaction proof uploaded successfully! Awaiting validation check.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Failed to serialize image payload container sector.']);
    }
    exit;
}

// 4. EXECUTE USER WITHDRAWAL REQUEST Node
if ($action === 'user_withdrawal') {
    $amount = floatval($_POST['amount'] ?? 0);
    $address = $_POST['address'] ?? '';

    if ($amount <= 0 || empty($address)) {
        echo json_encode(['status' => 'error', 'message' => 'Required execution fields empty.']); exit;
    }

    $chk = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
    $chk->execute([$_SESSION['user_id']]);
    $uBal = floatval($chk->fetchColumn());

    if ($amount > $uBal) {
        echo json_encode(['status' => 'error', 'message' => 'Insufficient wallet structural resource parameters.']); exit;
    }

    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, status, wallet_address) VALUES (?, 'withdrawal', ?, 'pending', ?)");
    $stmt->execute([$_SESSION['user_id'], $amount, $address]);
    echo json_encode(['status' => 'success', 'message' => 'Withdrawal settlement parameters staged. Verification pending.']);
    exit;
}

// 5. TRANSMIT NEW CHAT MESSAGE TO DATABASE LAYER
if ($action === 'send_chat_message') {
    $msg = trim($_POST['msg'] ?? '');
    $uploaded_file = null;

    // Handle Media Attachment upload loop safely
    if (isset($_FILES['chat_media']) && $_FILES['chat_media']['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($_FILES['chat_media']['name'], PATHINFO_EXTENSION);
        $uploaded_file = 'chat_' . uniqid() . '.' . $ext;
        $target = __DIR__ . '/../uploads/' . $uploaded_file;
        move_uploaded_file($_FILES['chat_media']['tmp_name'], $target);
    }

    if (empty($msg) && !$uploaded_file) {
        echo json_encode(['status' => 'error', 'message' => 'Payload vector cannot be null.']); exit;
    }

    try {
        $stmt = $pdo->prepare("INSERT INTO support_chats (user_id, sender, message_text, media_file) VALUES (?, 'user', ?, ?)");
        $stmt->execute([$_SESSION['user_id'], $msg, $uploaded_file]);
        echo json_encode(['status' => 'success']);
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

// Fallback message for unrecognized protocols
echo json_encode(['status' => 'error', 'message' => 'Unhandled financial/support routing endpoint context.']);