<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

require_once '../config/database.php';
require_once '../utils/helpers.php';

$token = getAuthToken();
$user = getUserFromToken($token);

if (!$user) {
    echo json_encode(["status" => "error", "message" => "Unauthorized"]);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    handle_get($pdo, $user['id']);
} elseif ($method === 'POST') {
    handle_post($pdo, $user['id']);
}

function handle_get($pdo, $userId) {
    try {
        // Fetch Markets
        $stmt = $pdo->query("SELECT * FROM lending_markets");
        $markets = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Fetch User Positions
        $stmt = $pdo->prepare("SELECT * FROM user_deposits WHERE user_id = ?");
        $stmt->execute([$userId]);
        $deposits = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $stmt = $pdo->prepare("SELECT * FROM user_borrows WHERE user_id = ?");
        $stmt->execute([$userId]);
        $borrows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode([
            "status" => "success",
            "data" => [
                "markets" => $markets,
                "deposits" => $deposits,
                "borrows" => $borrows
            ]
        ]);
    } catch (PDOException $e) {
        echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    }
}

function handle_post($pdo, $userId) {
    $data = json_decode(file_get_contents("php://input"), true);
    $action = $data['action'] ?? '';

    switch ($action) {
        case 'supply':
            process_supply($pdo, $userId, $data);
            break;
        case 'withdraw':
            process_withdraw($pdo, $userId, $data);
            break;
        case 'borrow':
            process_borrow($pdo, $userId, $data);
            break;
        case 'repay':
            process_repay($pdo, $userId, $data);
            break;
        default:
            echo json_encode(["status" => "error", "message" => "Invalid action"]);
    }
}

function process_supply($pdo, $userId, $data) {
    $symbol = strtoupper($data['symbol']);
    $amount = floatval($data['amount']);

    try {
        $pdo->beginTransaction();

        // Check wallet balance
        $stmt = $pdo->prepare("SELECT balance FROM user_assets WHERE user_id = ? AND symbol = ?");
        $stmt->execute([$userId, $symbol]);
        $walletBalance = $stmt->fetchColumn();

        if ($walletBalance === false || $walletBalance < $amount) {
            throw new Exception("Insufficient wallet balance to supply");
        }

        // Deduct from wallet
        $stmt = $pdo->prepare("UPDATE user_assets SET balance = balance - ? WHERE user_id = ? AND symbol = ?");
        $stmt->execute([$amount, $userId, $symbol]);

        // Update user_deposits
        $stmt = $pdo->prepare("SELECT id, amount FROM user_deposits WHERE user_id = ? AND symbol = ?");
        $stmt->execute([$userId, $symbol]);
        $existing = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($existing) {
            $stmt = $pdo->prepare("UPDATE user_deposits SET amount = amount + ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$amount, $existing['id']]);
        } else {
            $stmt = $pdo->prepare("INSERT INTO user_deposits (id, user_id, symbol, amount) VALUES (?, ?, ?, ?)");
            $stmt->execute([uniqid(), $userId, $symbol, $amount]);
        }

        $pdo->commit();
        echo json_encode(["status" => "success", "message" => "Supplied $amount $symbol successfully"]);
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    }
}

function process_withdraw($pdo, $userId, $data) {
    $symbol = strtoupper($data['symbol']);
    $amount = floatval($data['amount']);

    try {
        $pdo->beginTransaction();

        $stmt = $pdo->prepare("SELECT id, amount FROM user_deposits WHERE user_id = ? AND symbol = ?");
        $stmt->execute([$userId, $symbol]);
        $existing = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$existing || $existing['amount'] < $amount) {
            throw new Exception("Insufficient lending balance to withdraw");
        }

        // Deduct from deposits
        $stmt = $pdo->prepare("UPDATE user_deposits SET amount = amount - ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
        $stmt->execute([$amount, $existing['id']]);

        // Add back to wallet
        $stmt = $pdo->prepare("UPDATE user_assets SET balance = balance + ? WHERE user_id = ? AND symbol = ?");
        $stmt->execute([$amount, $userId, $symbol]);

        $pdo->commit();
        echo json_encode(["status" => "success", "message" => "Withdrawn $amount $symbol successfully"]);
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    }
}

function process_borrow($pdo, $userId, $data) {
    $symbol = strtoupper($data['symbol']);
    $amount = floatval($data['amount']);

    try {
        $pdo->beginTransaction();

        // Simple borrow limit check (Collateral Factor 75%)
        // Note: Real app would calculate total value in USD
        // For now, we allow borrowing if user has ANY deposits (simplified)
        $stmt = $pdo->prepare("SELECT SUM(amount) FROM user_deposits WHERE user_id = ?");
        $stmt->execute([$userId]);
        $totalDeposits = $stmt->fetchColumn();

        if (!$totalDeposits || $totalDeposits <= 0) {
             throw new Exception("You must supply collateral before borrowing");
        }
        
        // Add to user_borrows
        $stmt = $pdo->prepare("SELECT id, amount FROM user_borrows WHERE user_id = ? AND symbol = ?");
        $stmt->execute([$userId, $symbol]);
        $existing = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($existing) {
            $stmt = $pdo->prepare("UPDATE user_borrows SET amount = amount + ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$amount, $existing['id']]);
        } else {
            $stmt = $pdo->prepare("INSERT INTO user_borrows (id, user_id, symbol, amount) VALUES (?, ?, ?, ?)");
            $stmt->execute([uniqid(), $userId, $symbol, $amount]);
        }

        // Add to wallet
        $stmt = $pdo->prepare("UPDATE user_assets SET balance = balance + ? WHERE user_id = ? AND symbol = ?");
        $stmt->execute([$amount, $userId, $symbol]);

        $pdo->commit();
        echo json_encode(["status" => "success", "message" => "Borrowed $amount $symbol successfully"]);
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    }
}

function process_repay($pdo, $userId, $data) {
    $symbol = strtoupper($data['symbol']);
    $amount = floatval($data['amount']);

    try {
        $pdo->beginTransaction();

        // Check wallet balance
        $stmt = $pdo->prepare("SELECT balance FROM user_assets WHERE user_id = ? AND symbol = ?");
        $stmt->execute([$userId, $symbol]);
        $walletBalance = $stmt->fetchColumn();

        if ($walletBalance === false || $walletBalance < $amount) {
            throw new Exception("Insufficient wallet balance to repay");
        }

        $stmt = $pdo->prepare("SELECT id, amount FROM user_borrows WHERE user_id = ? AND symbol = ?");
        $stmt->execute([$userId, $symbol]);
        $existing = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$existing || $existing['amount'] <= 0) {
            throw new Exception("No active borrow to repay");
        }

        if ($existing['amount'] < $amount) {
            $amount = $existing['amount']; // Final repayment (don't overpay)
        }

        if ($amount > 0) {
            // Deduct from borrow
            $stmt = $pdo->prepare("UPDATE user_borrows SET amount = amount - ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$amount, $existing['id']]);

            // Deduct from wallet
            $stmt = $pdo->prepare("UPDATE user_assets SET balance = balance - ? WHERE user_id = ? AND symbol = ?");
            $stmt->execute([$amount, $userId, $symbol]);
        }

        $pdo->commit();
        echo json_encode(["status" => "success", "message" => "Repaid $amount $symbol successfully"]);
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    }
}
