<?php
include 'header.php';


// Check if withdrawal data exists in session
if (!isset($_SESSION['withdrawal_data'])) {
    header('Location: withdrawals.php');
    exit();
}


$withdrawal_data = $_SESSION['withdrawal_data'];
$amount = $withdrawal_data['amount'];
$fee = $amount * ($withdrawal_data['fee_percent'] / 100);
$total = $amount; 

// Initialize variables
$error = '';
$success = '';



// Process confirmation
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['confirm'])) {
        try {
            // Start transaction
            $conn->begin_transaction();
            
            // 1. Verify balance again (in case it changed)
            if ($balance < $total) {
                throw new Exception("Insufficient balance for withdrawal");
            }
            
            // 2. Deduct from user balance (only the withdrawal amount)
            $deductSql = "UPDATE users SET balance = balance - ? WHERE id = ?";
            $deductStmt = $conn->prepare($deductSql);
            $deductStmt->bind_param("di", $total, $user_id);
            $deductStmt->execute();
            
            if ($deductStmt->affected_rows === 0) {
                throw new Exception("Failed to deduct from balance");
            }
            
            // 3. Record withdrawal (store fee in database for tracking)
            $withdrawalSql = "INSERT INTO withdrawals 
                             (user_id, fullname, email, amount, fee, crypto_method, wallet_address, status, created_at) 
                             VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', NOW())";
            $withdrawalStmt = $conn->prepare($withdrawalSql);
            $fullname = $first_name . ' ' . $last_name;
            $withdrawalStmt->bind_param(
                "issddss", 
                $user_id,
                $fullname,
                $email,
                $amount,
                $fee,
                $withdrawal_data['crypto_method'],
                $withdrawal_data['wallet_address']
            );
            $withdrawalStmt->execute();
            
            // Get the withdrawal ID
            $withdrawal_id = $conn->insert_id;
            
            // Send confirmation email to user
            $userSubject = "Withdrawal Request Received - $sitename";
            $userBody = "
            <div style='background: #E4E9F0; padding: 20px; font-family: Arial, sans-serif;'>
                <div style='max-width: 600px; margin: 0 auto; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);'>
                    <div style='background-color: #1e293b; padding: 16px; display: flex; align-items: center;'>
                        <div style='display: flex; align-items: center;'>
                            <center><img src='$site_url/user/image/logo.png' width='100px' style='margin-right: 8px;'></center>
                        </div>
                    </div>
                    <div style='padding: 32px; text-align: center;'>
                        <h1 style='font-size: 28px; color: #1e293b; margin-bottom: 24px; line-height: 1.2;'>
                            Withdrawal Request Received
                        </h1>
                        <p style='font-size: 18px; color: #4b5563; margin-bottom: 32px;'>
                            Dear $first_name, your withdrawal request has been received and is being processed.
                        </p>
                        
                        <div style='text-align: left; margin-bottom: 24px;'>
                            <h3 style='color: #1e293b;'>Transaction Details:</h3>
                            <p><strong>Request ID:</strong> $withdrawal_id</p>
                            <p><strong>Amount:</strong> \$" . number_format($amount, 2) . "</p>
                            <p><strong>Fee (" . $withdrawal_data['fee_percent'] . "%):</strong> \$" . number_format($fee, 2) . "</p>
                            <p><strong>Amount to Receive:</strong> \$" . number_format(($amount - $fee), 2) . "</p>
                            <p><strong>Payment Method:</strong> {$withdrawal_data['crypto_method']}</p>
                            <p><strong>Wallet Address:</strong> {$withdrawal_data['wallet_address']}</p>
                            <p><strong>Status:</strong> Pending</p>
                            <p><strong>Date:</strong> " . date('Y-m-d H:i:s') . "</p>
                        </div>
                        
                        <p style='font-size: 18px; color: #4b5563; margin-bottom: 32px;'>
                            Our team will process your request within 24-48 hours. You will receive a confirmation once completed.
                        </p>
                        
                        <div style='margin-top: 32px; border-top: 1px solid #e5e7eb; padding-top: 24px; text-align: left;'>
                            <p style='color: #4b5563; margin-bottom: 8px;'>Thanks,</p>
                            <p style='color: #4b5563; font-weight: bold;'>Finance Team, $sitename</p>
                        </div>
                    </div>
                </div>
            </div>";
            
            sendMail($email, $userSubject, $userBody);
            
            // Send notification to admin
            $adminSubject = "New Withdrawal Request - $first_name";
            $adminBody = "
            <div style='font-family: Arial, sans-serif;'>
                <h2>New Withdrawal Request</h2>
                <p><strong>User:</strong> $fullname ($email)</p>
                <p><strong>Request ID:</strong> $withdrawal_id</p>
                <p><strong>Amount Requested:</strong> \$" . number_format($amount, 2) . "</p>
                <p><strong>Fee (" . $withdrawal_data['fee_percent'] . "%):</strong> \$" . number_format($fee, 2) . "</p>
                <p><strong>Amount to Send:</strong> \$" . number_format(($amount - $fee), 2) . "</p>
                <p><strong>Method:</strong> {$withdrawal_data['crypto_method']}</p>
                <p><strong>Wallet Address:</strong> {$withdrawal_data['wallet_address']}</p>
                <p><strong>Current Balance:</strong> \$" . number_format(($balance - $amount), 2) . "</p>
                <p>Please process this request in the admin panel.</p>
            </div>";
            
            if (!empty($admin_email)) {
                sendMail($admin_email, $adminSubject, $adminBody);
            }
            
            // Commit transaction
            $conn->commit();
            
            // Clear session data
            unset($_SESSION['withdrawal_data']);
            
            echo "<script>
                    alert('Withdrawal request submitted successfully!');
                    window.location.href = 'withdrawals.php';
                </script>";
            exit();
            
        } catch (Exception $e) {
            $conn->rollback();
            $error = "Withdrawal failed: " . $e->getMessage();
            echo "<script>alert('$error'); window.location.href = 'withdrawals.php';</script>";
            exit();
        }
    } elseif (isset($_POST['cancel'])) {
        // Cancel withdrawal
        unset($_SESSION['withdrawal_data']);
        header('Location: withdrawals.php');
        exit();
    }
}
?>

<!-- Display the confirmation form -->
<div class="pt-28 md:pt-0 mt-0 md:mt-36 w-full md:w-4/5" id="general-content">
    <div class="w-full md:w-10/12 md:ml-64 2xl:ml-1/5" id="general-content-section">
        
        <!-- Display success/error messages -->
        <?php if ($success): ?>
        <div class="w-full flex justify-center">
            <div class="w-11/12 bg-green-500 text-white p-3 rounded-md mb-4">
                <?php echo $success; ?>
            </div>
        </div>
        <?php endif; ?>
        
        <?php if ($error): ?>
        <div class="w-full flex justify-center">
            <div class="w-11/12 bg-red-500 text-white p-3 rounded-md mb-4">
                <?php echo $error; ?>
            </div>
        </div>
        <?php endif; ?>

        <div class="w-full py-5">
            <div class="w-full flex justify-center">
                <div class="w-11/12 rounded-md bg-[#0e1726] p-2 md:p-4">
                    <div class="w-full flex justify-start items-baseline space-x-2">
                        <h6 class="bg-transparent text-center text-[#ebedf2] text-xs md:text-sm capitalize">
                            Available Bal.
                        </h6>
                        <h2 class="bg-transparent text-center text-[#ebedf2] text-xl md:text-2xl font-semibold capitalize">
                            USD <?php echo number_format($balance, 2) ?>
                        </h2>
                    </div>

                    <hr class="w-full border-b border-dotted border-gray-600 border">

                    <div class="md:p-4">
                        <form action="confirm_withdrawals.php" method="POST">
                            <table class="w-full text-[#bfc9d4] text-xs md:text-sm table-fixed border-separate border-spacing-x-2 border-spacing-y-1 overflow-x-scroll">
                                <tbody class="md:p-4">
                                    <tr>
                                        <td><span class="font-medium">Amount:</span></td>
                                        <td>USD <?php echo number_format($amount, 2) ?></td>
                                    </tr>
                                    <tr>
                                        <td><span class="font-medium">Fee:</span></td>
                                        <td>USD <?php echo number_format($fee, 2) ?></td>
                                    </tr>
                                    <tr>
                                        <td><span class="font-medium">Total Deduction:</span></td>
                                        <td>USD <?php echo number_format($total, 2) ?></td>
                                    </tr>
                                    <tr>
                                        <td><span class="font-medium">Payment Method:</span></td>
                                        <td><?php echo htmlspecialchars($withdrawal_data['crypto_method']) ?></td>
                                    </tr>
                                    <tr>
                                        <td><span class="font-medium">Wallet Address:</span></td>
                                        <td><?php echo htmlspecialchars($withdrawal_data['wallet_address']) ?></td>
                                    </tr>
                                    
                                    <tr>
                                        <td colspan="2">
                                            <div class="w-full my-6 md:my-10 flex justify-center">
                                                <div class="space-y-2">
                                                    <div class="flex justify-center items-center">
                                                        <svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10 text-[#dfb05b]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                                            <path stroke-linecap="round" stroke-linejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                                        </svg>
                                                    </div>
                                                    <div class="text-xs md:text-sm font-medium text-center">
                                                        <p>You are about to withdraw <b>USD<?php echo number_format($amount, 2) ?></b> via <b><?php echo htmlspecialchars($withdrawal_data['crypto_method']) ?></b>. A withdrawal fee of <b>USD<?php echo number_format($fee, 2) ?></b> will be applied to this request.</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                    
                                    <tr>
                                        <td colspan="2">
                                            <div class="flex justify-between">
                                                <a href="withdrawals.php" class="text-xs md:text-sm text-[#d1d5db] text-center px-5 py-2 bg-gray-600 hover:bg-gray-700 rounded-md">
                                                    Cancel
                                                </a>
                                                <button type="submit" name="confirm" class="text-xs md:text-sm text-[#d1d5db] text-center px-5 py-2 bg-[#1b2e4b] hover:bg-gray-700 rounded-md">
                                                    Confirm Withdrawal
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>


<?php include 'footer.php'; ?>