<?php
// ajax/add-money-request.php
require_once '../common/config.php';
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Please login first.']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userId = $_SESSION['user_id'];
    $amount = (float)($_POST['amount'] ?? 0);
    $paymentMethod = sanitize($_POST['payment_method'] ?? '');
    $txnId = sanitize($_POST['txn_id'] ?? '');

    $methodStmt = $pdo->prepare("SELECT id FROM payment_methods WHERE name=? AND status='active'");
    $methodStmt->execute([$paymentMethod]);
    if ($amount < 10 || !is_finite($amount) || empty($paymentMethod) || empty($txnId) || !$methodStmt->fetch()) {
        echo json_encode(['status' => 'error', 'message' => 'Please provide valid payment details.']);
        exit;
    }

    $stmt = $pdo->prepare("INSERT INTO wallet_requests (user_id, amount, payment_method, txn_id) VALUES (?, ?, ?, ?)");
    
    if ($stmt->execute([$userId, $amount, $paymentMethod, $txnId])) {
        echo json_encode(['status' => 'success', 'message' => 'Money request submitted for review.', 'redirect' => '../profile.php']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Failed to submit request.']);
    }
}
?>
