<?php
require("../config.php");
require("header.php"); // this already has session_start()

// Get session user ID
$userId = $_SESSION['SESS_USERID'] ?? 0;
if (!$userId) {
    die("Not logged in");
}

// Get user info
$stmt = $pdo->prepare("SELECT * FROM logins WHERE id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    die("User not found");
}

// If coming from deposit.php
$amount    = isset($_GET['amount']) ? floatval($_GET['amount']) : 0;
$method_id = isset($_GET['method_id']) ? intval($_GET['method_id']) : 0;

// Fetch method
$stmt = $pdo->prepare("SELECT * FROM payment_methods WHERE id = ?");
$stmt->execute([$method_id]);
$method = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$method) {
    die("Invalid method selected.");
}

  // Convert USER currency → USD
$user_rate = $user['cur_rate'] > 0 ? $user['cur_rate'] : 1;
$converted = $user_rate > 0 ? $amount / $user_rate : 0;
        

// Handle confirm payment
if (isset($_POST['deposit_action'])) {
    try {
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $date = date("Y-m-d H:i:s");
        $wallet = $method['wallet_address'] ?? '';
        $cur = $user['cur_symbol'] ?? 'USD';
        $note = "Deposit via " . $method['name'];
        $Pay_location = $method['logo']; // logo stored as proof location

        // File upload for payment proof
        if (!empty($_FILES['imgPay']['name'])) {
            $target_dir = "accounts/upload/payment/";
            if (!is_dir($target_dir)) {
                mkdir($target_dir, 0777, true);
            }
            $file_name = time() . "_" . basename($_FILES["imgPay"]["name"]);
            $target_file = $target_dir . $file_name;
            if (move_uploaded_file($_FILES["imgPay"]["tmp_name"], $target_file)) {
                $Pay_location = $target_file;
            }
        }
        
      

        // Calculate converted deposit based on rate
        // $user_rate = $method['rate_in_usd'] > 0 ? $method['rate_in_usd'] : 1;
        // $converted = $user_rate > 0 ? $amount / $user_rate : 0;

        // Insert deposit
        $stmt = $pdo->prepare("
            INSERT INTO deposit (
                log_id, email, amount,amt, cur, date, note, user, user_cur, user_rate, user_bal,
                name, phone, method, signa, Pay_location, wallet, app_id, status, trans_id
            ) VALUES (
                ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?
            )
        ");
        $stmt->execute([
            $userId,
            $user['email'],
            
            $amount,
            $converted,
            $cur,
            $date,
            $note,
            $user['username'],
            $cur,
            $user_rate,
            $user['balance'] ?? 0,
            $user['fullname'] ?? '',
            $user['phone'] ?? '',
            $method['name'],
            'signature',
            $Pay_location,
            $wallet,
            uniqid("APP"),
            uniqid("TX")
        ]);

        // Update logins table
        $pdo->prepare("UPDATE logins SET confirm = 1, pmethod = ? WHERE id = ?")->execute([$method['name'], $userId]);
        $pdo->prepare("UPDATE logins SET deposit = ? WHERE id = ?")->execute([$converted, $userId]);



$pdo->prepare("UPDATE logins SET deposit = ? WHERE id = ?")->execute([$converted, $userId]);


        echo "<script>
            alert('Your deposit request was successful. Your trading account will be credited once confirmed.');
            window.location.href = 'transactions.php';
        </script>";
        exit;

    } catch (PDOException $e) {
        die("DB error: " . $e->getMessage());
    }
}
?>


<main class="flex-1 px-2 py-2 md:p-4 pb-20 md:pb-6 overflow-hidden">
    <div class="space-y-3 sm:space-y-6 mt-1 sm:mt-2">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-3 sm:gap-6">
            
            <!-- Left Section -->
            <div class="lg:col-span-2">
                <div class="bg-[#0F0A1F] rounded-lg sm:rounded-xl overflow-hidden">
                    
                    <!-- Header -->
                    <div class="p-3 sm:p-6 border-b border-gray-800/50">
                        <div class="flex items-center justify-between">
                            <h3 class="text-base sm:text-lg font-medium">Deposit Details</h3>
                            <a href="deposit.php" class="inline-flex items-center gap-1 sm:gap-1.5 text-xs sm:text-sm text-red-500 hover:text-red-400">
                                <i class="fas fa-times w-3 h-3 sm:w-4 sm:h-4"></i>
                                Cancel
                            </a>
                        </div>
                    </div>

                    <!-- Amount & Timer -->
                    <div class="p-3 sm:p-6 bg-gradient-to-r from-[#2FE6DE]/10 to-transparent">
                        <div class="flex items-center justify-between mb-3 sm:mb-4">
                            <div>
                                <span class="text-xs sm:text-sm text-gray-400">Amount to Pay</span>
                                <div class="flex flex-col mt-1">
                                    <span class="text-xl sm:text-2xl font-medium text-[#2FE6DE]">
                                        <?= $user['cur_symbol'] ?><?= number_format($amount, 2) ?> <?= $user['currency'] ?>
                                    </span>
                                </div>
                            </div>
                            
                             <div>
                                <span class="text-xs sm:text-sm text-gray-400">Equivalent in USD</span>
                                <div class="mt-1">
                                    <span class="text-xl sm:text-2xl font-medium text-[#2FE6DE]">
                                        $<?= number_format($converted, 2) ?> USD
                                    </span>
                                </div>
                            </div>
                            <!-- Countdown -->
                            <div class="text-right flex-shrink-0 ml-2"
                                 x-data="{timeLeft:1800,timer:null,formatTime(s){let m=Math.floor(s/60),sec=s%60;return m.toString().padStart(2,'0')+':'+sec.toString().padStart(2,'0')}}"
                                 x-init="timer=setInterval(()=>{if(timeLeft>0){timeLeft--}},1000)">
                                <div class="flex items-center gap-2 text-yellow-500">
                                    <i class="fas fa-clock"></i>
                                    <span class="font-medium text-sm sm:text-base" x-text="formatTime(timeLeft)">30:00</span>
                                </div>
                                <span class="text-xs text-gray-400">Time Remaining</span>
                            </div>
                        </div>
                    </div>










 <!-- Payment Method -->

<form method="POST" enctype="multipart/form-data" class="mt-6 space-y-4">
       
                   
                    <div class="p-3 sm:p-6 border-t border-gray-800/50">
                        <div class="flex items-center gap-4 mb-6">
                            <div class="w-12 h-12 flex items-center justify-center bg-gray-800/50 rounded-lg">
                                <img src="../<?= htmlspecialchars($method['logo']) ?>" alt="<?= htmlspecialchars($method['name']) ?>" class="w-8 h-8">
                            </div>
                            <div>
                                <h4 class="font-medium text-base"><?= htmlspecialchars($method['name']) ?></h4>
                                <p class="text-sm text-gray-400">Network: <?= strtoupper($method['name']) ?></p>
                            </div>
                        </div>

                        <!-- QR + Wallet -->
                        <div class="flex flex-col items-center p-6 bg-gray-800/30 rounded-xl">
                            <div class="bg-white p-4 rounded-lg mb-4">
                                <img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=<?= urlencode($method['wallet_address']) ?>" 
                                     alt="QR Code" class="w-48 h-48 object-contain">
                            </div>
                            <p class="text-sm text-gray-400 mb-3">Scan QR code to make payment</p>

                            <div class="flex w-full">
                                <input type="text" value="<?= htmlspecialchars($method['wallet_address']) ?>" readonly
                                    class="flex-1 bg-gray-800/50 border border-r-0 border-gray-700 rounded-l-lg px-4 py-3 text-gray-300 font-mono text-sm">
                                <button onclick="navigator.clipboard.writeText('<?= $method['wallet_address'] ?>')" 
                                    class="px-4 border border-gray-700 rounded-r-lg text-gray-400 hover:text-[#2FE6DE] hover:border-[#2FE6DE]">
                                    <i class="fas fa-copy"></i>
                                </button>
                            </div>
                        </div>
                        
                        
                        

                        
        <input type="hidden" name="amount" value="<?=  $amount  ?>">
        
        <!--<input type="" name="converted" value="<?= $converted ?>">-->
        
        <input type="hidden" name="method" value="<?= htmlspecialchars($method['name']) ?>">
        <input type="hidden" name="wallet" value="<?= htmlspecialchars($method['wallet_address']) ?>">
        <input type="hidden" name="cur" value="<?= htmlspecialchars($user['cur_symbol']) ?>">

        <!-- Proof of payment -->
        <label class="block text-sm text-gray-300">Upload Payment Proof (optional)</label>
        <input type="file" name="imgPay" accept="image/*" class="w-full p-2 bg-[#1A1428] rounded">

        <button type="submit" name="deposit_action" 
            class="w-full bg-gradient-to-r from-[#2FE6DE] to-[#2FE6DE]/80 text-black font-medium py-3 rounded-lg hover:brightness-110">
            Confirm Payment
        </button>
    </form>
                        
                        
                        
                        
                    </div>
                </div>
            </div>

            <!-- Right Sidebar -->
            <div class="lg:col-span-1">
                <div class="bg-[#0F0A1F] rounded-xl p-6">
                    <h3 class="text-lg font-medium mb-4">Important Notes</h3>
                    <div class="space-y-4">
                        <div class="flex items-start gap-3">
                            <div class="w-6 h-6 flex items-center justify-center rounded-full bg-yellow-500/10">
                                <i class="fas fa-exclamation-triangle text-yellow-500"></i>
                            </div>
                            <p class="text-sm text-gray-400">Ensure your deposit meets the minimum requirement.</p>
                        </div>
                        <div class="flex items-start gap-3">
                            <div class="w-6 h-6 flex items-center justify-center rounded-full bg-blue-500/10">
                                <i class="fas fa-info-circle text-blue-500"></i>
                            </div>
                            <p class="text-sm text-gray-400">Double-check the network before making deposit.</p>
                        </div>
                        <div class="flex items-start gap-3">
                            <div class="w-6 h-6 flex items-center justify-center rounded-full bg-green-500/10">
                                <i class="fas fa-clock text-green-500"></i>
                            </div>
                            <p class="text-sm text-gray-400">Deposits are processed within 24 hours.</p>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</main>

<?php require("footer.php"); ?>
