<?php
// 1. Capture the form data securely
$phone = isset($_POST['phone']) ? htmlspecialchars($_POST['phone']) : '';
$amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
$frequency = isset($_POST['frequency']) ? $_POST['frequency'] : 'daily';
$method = isset($_POST['method']) ? $_POST['method'] : 'momo'; 

// --- BASE STYLING FOR ALL UI STATES ---
$ui_style = "<style>
    @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap');
    body { font-family: 'Plus Jakarta Sans', sans-serif; background: radial-gradient(130% 100% at top left, #121824 0%, #080b11 100%); min-height: 100vh; display: flex; justify-content: center; align-items: center; margin: 0; padding: 20px; color: #ffffff; }
    .box { width: 100%; max-width: 400px; background: linear-gradient(145deg, rgba(26, 34, 50, 0.8) 0%, rgba(15, 22, 36, 0.95) 100%); padding: 32px; border-radius: 24px; box-shadow: 0 20px 40px rgba(0, 0, 0, 0.5); border: 1px solid rgba(255, 255, 255, 0.1); text-align: center; }
    h3 { font-size: 22px; font-weight: 800; margin-bottom: 16px; }
    .success { color: #10b981; }
    .error { color: #ef4444; }
    input { width: 90%; padding: 12px; margin-top: 10px; border-radius: 8px; border: 1px solid #374151; background: #1f2937; color: white; text-align: center; font-size: 12px; }
    .btn-return, .btn-copy { display: inline-block; padding: 10px 24px; margin-top: 20px; border-radius: 12px; font-size: 13px; font-weight: 700; background: rgba(255, 255, 255, 0.05); color: #9ca3af; text-decoration: none; border: 1px solid rgba(255, 255, 255, 0.1); cursor: pointer; }
    .btn-copy { background: #10b981; color: white; border: none; margin-top: 10px; }
</style>";

// --- ROUTING LOGIC ---
$payment_successful = false;

if ($method === 'momo') {
    $db_settings = new PDO('sqlite:app_feed.db');
    $secret_key = $db_settings->query("SELECT setting_value FROM app_feed_settings WHERE setting_key = 'flutterwave_key'")->fetchColumn();

    $payment_data = ["amount" => $amount, "currency" => "USD", "phone_number" => $phone, "tx_ref" => "tx-" . uniqid(), "email" => "user@example.com"];
    $ch = curl_init("https://api.flutterwave.com/v3/charges?type=mobile_money_ghana");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payment_data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer " . $secret_key, "Content-Type: application/json"]);
    $response = curl_exec($ch);
    curl_close($ch);
    $result = json_decode($response, true);
    $payment_successful = (is_array($result) && isset($result['status']) && $result['status'] === 'success');

} elseif ($method === 'card') {
    echo "<script>window.location.href = 'https://your-payment-gateway-link.com/pay';</script>";
    exit();
} elseif ($method === 'crypto') {
    $wallet_address = "YOUR_WALLET_ADDRESS_HERE"; // Update with your actual wallet address
    $qr_url = "https://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=" . urlencode($wallet_address);
    
    echo $ui_style;
    echo "<div class='box'>
            <h3>Scan Crypto Address</h3>
            <p>Send <b>$$amount</b> to this address:</p>
            <img src='$qr_url' style='background:white; padding:10px; border-radius:10px;'>
            <input type='text' id='wallet' value='$wallet_address' readonly>
            <button class='btn-copy' onclick='navigator.clipboard.writeText(document.getElementById(\"wallet\").value); alert(\"Address Copied!\");'>Copy Address</button>
            <p style='font-size:11px; margin-top:15px; color:#6b7280;'>Once sent, our system will verify your deposit.</p>
          </div>";
    exit();
}

// --- DATABASE UPDATE LOGIC ---
if ($payment_successful) { 
    try {
        $admin_db = new PDO('sqlite:app_feed.db');
        $admin_stmt = $admin_db->prepare("INSERT INTO momo_transactions (phone, amount, frequency, status, payment_method) VALUES (?, ?, ?, 'Completed', ?)");
        $admin_stmt->execute([$phone, $amount, $frequency, $method]);

        $pdo = new PDO("mysql:host=localhost;dbname=imperial_credit_bank;charset=utf8", "root", "");
        $stmt = $pdo->prepare("SELECT balance_usd FROM users WHERE phone_number = ? LIMIT 1");
        $stmt->execute([$phone]);
        $user_row = $stmt->fetch();

        $new_balance = ($user_row ? floatval($user_row['balance_usd']) : 0) + $amount;
        $level = ($new_balance > 500) ? 4 : (($new_balance > 150) ? 3 : (($new_balance > 25) ? 2 : 1));

        if ($user_row) {
            $pdo->prepare("UPDATE users SET balance_usd = ?, current_level = ? WHERE phone_number = ?")->execute([$new_balance, $level, $phone]);
        } else {
            $pdo->prepare("INSERT INTO users (phone_number, balance_usd, current_level) VALUES (?, ?, ?)")->execute([$phone, $new_balance, $level]);
        }

        echo $ui_style;
        echo "<div class='box'><h3 class='success'>Payment Received via " . strtoupper($method) . "!</h3><p>New Balance: $".number_format($new_balance, 2)." USD</p></div>";
    } catch (PDOException $e) {
        die("System Error: Could not update ledger.");
    }
} else {
    echo $ui_style;
    echo "<div class='box'><h3 class='error'>Payment Verification Failed</h3><p>The gateway rejected the transaction.</p><a href='index.php' class='btn-return'>Return to Dashboard</a></div>";
}
?>