<?php
session_start();
require_once "../include/db.php";

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SESSION['user_id'])) {
    $userId = intval($_SESSION['user_id']);
    $amount = floatval($_POST['amount']);
    $method = mysqli_real_escape_string($conn, $_POST['payment_method']);
    
    // 1. Validation
    if ($amount < 10) {
        $_SESSION['error'] = "Minimum deposit is $10.00";
        header("Location: ../deposit.php");
        exit;
    }

    // 2. Generate Unique Transaction Reference
    $txnRef = "DEP-" . strtoupper(bin2hex(random_bytes(4)));

    // 3. Insert Pending Transaction
    $stmt = mysqli_prepare($conn, "INSERT INTO transactions (user_id, type, amount, method, ref, status, created_at) VALUES (?, 'deposit', ?, ?, ?, 'pending', NOW())");
    mysqli_stmt_bind_param($stmt, "idss", $userId, $amount, $method, $txnRef);

    if (mysqli_stmt_execute($stmt)) {
        // Redirect to a Payment Details page (where you show your crypto address)
        header("Location: ../pay.php?ref=$txnRef");
    } else {
        $_SESSION['error'] = "Something went wrong. Please try again.";
        header("Location: ../deposit.php");
    }
}