<?php
include 'header.php';

// Process form submission if POST request
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['payment_screenshot'])) {
    // Get deposit details from session
    $deposit_details = $_SESSION['deposit_details'] ?? null;
    if (!$deposit_details) {
        echo "<script>alert('Deposit session expired. Please start again.'); window.location.href = 'manual.php';</script>";
        exit;
    }

    // Handle file upload
    if ($_FILES['payment_screenshot']['error'] !== UPLOAD_ERR_OK) {
        echo "<script>alert('Please upload a valid payment screenshot.'); window.location.href = 'manual.php';</script>";
        exit;
    }

    // File upload configuration
    $uploadDir = '../uploads/deposit_proofs/';
    $allowedTypes = ['image/jpeg', 'image/png', 'image/jpg'];
    $maxSize = 5 * 1024 * 1024; // 5MB
    
    // Create upload directory if it doesn't exist
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    
    $file = $_FILES['payment_screenshot'];
    $fileType = $file['type'];
    $fileSize = $file['size'];
    $fileName = uniqid('deposit_') . '_' . basename($file['name']);
    $targetPath = $uploadDir . $fileName;

    // Validate file
    if (!in_array($fileType, $allowedTypes)) {
        echo "<script>alert('Only JPG, JPEG, and PNG files are allowed.'); window.location.href = 'manual.php';</script>";
        exit;
    }

    if ($fileSize > $maxSize) {
        echo "<script>alert('File size must be less than 5MB.'); window.location.href = 'manual.php';</script>";
        exit;
    }

    // Move uploaded file
    if (move_uploaded_file($file['tmp_name'], $targetPath)) {
        // Prepare all data for database

        $coin = $deposit_details['coin'];
        $method = $deposit_details['method'];
        $receiving_amount = $deposit_details['receiving_amount'];
        $usd_amount = $deposit_details['amount'];
        $wallet_address = $crypto_addresses[strtoupper($coin)] ?? '';
        $status = 'pending';
        $charge = 0;
        $date = date('Y-m-d H:i:s');

        // Insert into database with all fields
        $stmt = $conn->prepare("INSERT INTO deposits 
            (user_id, amount, currency, usd_amount, wallet_address, payment_method, proof_image, status, charge, created_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("idssdsssds", 
            $user_id, 
            $receiving_amount, 
            $coin, 
            $usd_amount, 
            $wallet_address, 
            $method, 
            $fileName, 
            $status, 
            $charge, 
            $date);
        
        if ($stmt->execute()) {

            $userName = $full_name;
            
            $subject = "Deposit Submission Received - $sitename";
            $body = "
            <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/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;'>
                            Deposit Submission Received
                        </h1>
                        <p style='font-size: 18px; color: #4b5563; margin-bottom: 32px;'>
                            Dear <b>$userName</b>, we have received your deposit request.
                        </p>
                        
                        <div style='text-align: left; margin-bottom: 24px;'>
                            <h3 style='color: #1e293b;'>Deposit Details:</h3>
                            <p><strong>Amount:</strong> $usd_amount USD</p>
                            <p><strong>Cryptocurrency:</strong> $coin</p>
                            <p><strong>Payment Method:</strong> $method</p>
                            <p><strong>Status:</strong> Pending verification</p>
                        </div>
                        
                        <p style='font-size: 18px; color: #4b5563; margin-bottom: 32px;'>
                            Our team will review your payment and update your account balance shortly.
                            This process typically takes 1-3 business days.
                        </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 style='margin-top: 32px; font-size: 12px; color: #6b7280; text-align: left;'>
                            <p style='margin-bottom: 4px;'>Please consider all emails from us as confidential.</p>
                        </div>
                    </div>
                </div>
            </div>";

            // Send email to user
            $sendUser = sendMail($email, $subject, $body);

            // Optionally send notification to admin
            $adminSubject = "New Deposit Submission - $userName";
            $adminBody = "
            <div style='font-family: Arial, sans-serif;'>
                <h2>New Deposit Submission Received</h2>
                <p><strong>User:</strong> $userName</p>
                <p><strong>Email:</strong> $email</p>
                <p><strong>Amount:</strong> $usd_amount USD </p>
                <p><strong>Payment Method:</strong> $method</p>
                <p><strong>Wallet Address:</strong> $wallet_address</p>
                <p>Please review the submitted payment proof in the admin panel.</p>
            </div>";

            // Assuming you have an admin email in your config
            if (!empty($admin_email)) {
                $sendAdmin = sendMail($admin_email, $adminSubject, $adminBody);
            }

            // Clear the session deposit details
            unset($_SESSION['deposit_details']);
            echo "<script>alert('Deposit submitted successfully! We\\'ll review your payment shortly.'); window.location.href = 'manual.php';</script>";
            exit;
        } else {
            // Delete the uploaded file if database insert fails
            unlink($targetPath);
            echo "<script>alert('Error saving deposit. Please try again.'); window.location.href = 'manual.php';</script>";
            exit;
        }
    } else {
        echo "<script>alert('Error uploading file. Please try again.'); window.location.href = 'manual.php';</script>";
        exit;
    }
}

// Get deposit details from session for display
$deposit_details = $_SESSION['deposit_details'] ?? null;
if (!$deposit_details) {
    echo "<script>window.location.href = 'deposits.php';</script>";
    exit;
}

// User's deposit amount in USD
$usd_amount = $deposit_details['amount'];
$selected_coin = strtolower($deposit_details['coin']);

// Map user-selected coin to CoinGecko IDs
$coin_ids = [
    'btc' => 'bitcoin',
    'eth' => 'ethereum',
    'usdt' => 'tether',
    'bnb' => 'binancecoin',
    'xrp' => 'ripple',
    'sol' => 'solana',
    'ltc' => 'litecoin',
];

// Ensure valid coin
if (!isset($coin_ids[$selected_coin])) {
    echo "<script>alert('Invalid cryptocurrency selected.'); window.location.href = 'manual.php';</script>";
    exit;
}

$coin_id = $coin_ids[$selected_coin];

// Fetch real-time price from CoinGecko
$api_url = "https://api.coingecko.com/api/v3/simple/price?ids=$coin_id&vs_currencies=usd";
$response = file_get_contents($api_url);
$data = json_decode($response, true);

// Get conversion rate
$rate = $data[$coin_id]['usd'] ?? 0;

if ($rate <= 0) {
    echo "<script>alert('Could not fetch conversion rate. Please try again later'); window.location.href = 'manual.php';</script>";
    exit;
}

// Calculate crypto amount
$crypto_amount = $usd_amount / $rate;
$wallet_address = $crypto_addresses[strtoupper($selected_coin)] ?? 'Address not available';
?>



<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">
        
        <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="flex justify-between items-center">
                        <div>
                            <h2 class="bg-transparent text-[#ebedf2] font-medium capitalize">
                                Complete your payment
                            </h2>
                        </div>
                        <div>
                            <a href="deposits.php" class="flex justify-start items-center text-xs text-gray-400 hover:text-white">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M11 17l-5-5m0 0l5-5m-5 5h12" />
                                </svg>
                                <span>back</span>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div id="preloader" class="action-preloader">
            <div id="loading-bar-spinner" class="spinner">
                <div class="spinner-icon"></div>
            </div>
        </div>
        
        <div class="py-5">
            <div class="w-full flex justify-center">
                <div class="w-11/12 md:w-2/3 rounded-sm bg-[#0e1726] text-[#d3d6df] p-3 md:p-10">
                    
                    <div class="w-full my-6 md:my-10 flex justify-center">
                        <div class="space-y-2">
                            <div align="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 have selected to deposit <b>USD<?php echo number_format($deposit_details['amount'], 2); ?></b> via <b><?php echo $deposit_details['method']; ?></b>. A deposit charge of <b>USD<?php echo number_format($deposit_details['amount'] * ($deposits_charge / 100), 2); ?></b> has been applied to your deposit. Follow the payment instruction to complete your payment.</p>
                            </div>
                        </div>
                    </div>

                    <div class="w-full">
                        <div class="w-full grid grid-cols-2 gap-2 text-sm md:text-base break-all">
                            <div align="center" class="col-span-2 mb-3">
                                <div class="qrcode">
                                    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100" height="100" viewBox="0 0 100 100"><rect x="0" y="0" width="100" height="100" fill="#ffffff"/><g transform="scale(3.448)"><g transform="translate(0,0)"><path fill-rule="evenodd" d="M10 0L10 2L11 2L11 0ZM12 0L12 1L13 1L13 2L12 2L12 4L13 4L13 3L14 3L14 4L15 4L15 5L17 5L17 4L18 4L18 5L21 5L21 4L20 4L20 2L19 2L19 4L18 4L18 3L17 3L17 4L16 4L16 2L17 2L17 1L16 1L16 0ZM19 0L19 1L20 1L20 0ZM8 1L8 2L9 2L9 1ZM14 2L14 3L15 3L15 2ZM8 3L8 4L9 4L9 5L8 5L8 7L9 7L9 8L6 8L6 9L8 9L8 10L5 10L5 8L0 8L0 10L1 10L1 11L0 11L0 13L1 13L1 12L2 12L2 13L3 13L3 14L2 14L2 15L1 15L1 14L0 14L0 15L1 15L1 17L0 17L0 21L1 21L1 17L2 17L2 16L3 16L3 18L5 18L5 19L2 19L2 20L4 20L4 21L7 21L7 20L8 20L8 18L9 18L9 20L10 20L10 21L8 21L8 23L9 23L9 24L8 24L8 29L11 29L11 27L10 27L10 26L11 26L11 25L12 25L12 26L13 26L13 27L12 27L12 29L13 29L13 28L14 28L14 29L15 29L15 28L16 28L16 29L20 29L20 28L22 28L22 29L27 29L27 28L28 28L28 26L29 26L29 25L28 25L28 24L29 24L29 23L28 23L28 22L29 22L29 21L28 21L28 20L29 20L29 19L28 19L28 20L25 20L25 19L27 19L27 18L28 18L28 17L29 17L29 16L28 16L28 17L27 17L27 18L26 18L26 15L27 15L27 13L29 13L29 12L27 12L27 13L25 13L25 12L26 12L26 11L27 11L27 10L29 10L29 9L28 9L28 8L27 8L27 10L26 10L26 11L25 11L25 9L26 9L26 8L25 8L25 9L24 9L24 8L23 8L23 9L22 9L22 8L21 8L21 9L20 9L20 7L21 7L21 6L20 6L20 7L19 7L19 6L18 6L18 7L19 7L19 9L18 9L18 8L17 8L17 6L16 6L16 8L17 8L17 10L20 10L20 11L19 11L19 12L20 12L20 14L21 14L21 16L20 16L20 15L19 15L19 14L18 14L18 13L17 13L17 12L16 12L16 9L12 9L12 7L13 7L13 5L11 5L11 6L10 6L10 4L11 4L11 3ZM9 6L9 7L10 7L10 6ZM11 6L11 7L12 7L12 6ZM14 6L14 8L15 8L15 6ZM10 8L10 9L9 9L9 12L11 12L11 13L8 13L8 12L7 12L7 11L6 11L6 12L4 12L4 16L5 16L5 14L7 14L7 15L6 15L6 16L7 16L7 17L6 17L6 18L7 18L7 17L8 17L8 15L9 15L9 16L11 16L11 14L13 14L13 15L12 15L12 17L11 17L11 19L10 19L10 20L11 20L11 21L10 21L10 23L11 23L11 22L13 22L13 23L12 23L12 25L17 25L17 26L18 26L18 25L20 25L20 26L21 26L21 27L22 27L22 28L24 28L24 27L22 27L22 26L23 26L23 25L22 25L22 26L21 26L21 25L20 25L20 24L18 24L18 23L19 23L19 22L20 22L20 20L22 20L22 19L25 19L25 18L22 18L22 17L23 17L23 16L24 16L24 17L25 17L25 16L24 16L24 15L26 15L26 14L23 14L23 12L25 12L25 11L24 11L24 10L23 10L23 11L22 11L22 12L21 12L21 14L22 14L22 16L21 16L21 17L20 17L20 16L18 16L18 15L17 15L17 16L16 16L16 17L15 17L15 16L14 16L14 15L15 15L15 14L17 14L17 13L16 13L16 12L15 12L15 11L14 11L14 12L13 12L13 13L12 13L12 11L13 11L13 10L12 10L12 9L11 9L11 8ZM2 9L2 12L3 12L3 9ZM10 9L10 11L11 11L11 9ZM21 9L21 10L22 10L22 9ZM6 12L6 13L7 13L7 14L8 14L8 13L7 13L7 12ZM14 12L14 13L15 13L15 12ZM9 14L9 15L10 15L10 14ZM12 17L12 18L13 18L13 19L12 19L12 21L13 21L13 20L14 20L14 21L15 21L15 23L14 23L14 24L17 24L17 23L18 23L18 22L19 22L19 21L17 21L17 20L16 20L16 21L15 21L15 20L14 20L14 19L16 19L16 18L17 18L17 17L16 17L16 18L15 18L15 17ZM18 17L18 18L20 18L20 19L22 19L22 18L20 18L20 17ZM6 19L6 20L7 20L7 19ZM18 19L18 20L19 20L19 19ZM21 21L21 24L24 24L24 21ZM25 21L25 22L26 22L26 25L24 25L24 26L25 26L25 28L27 28L27 27L26 27L26 26L27 26L27 22L28 22L28 21L27 21L27 22L26 22L26 21ZM22 22L22 23L23 23L23 22ZM9 24L9 26L10 26L10 25L11 25L11 24ZM9 27L9 28L10 28L10 27ZM14 27L14 28L15 28L15 27ZM16 27L16 28L18 28L18 27ZM19 27L19 28L20 28L20 27ZM0 0L0 7L7 7L7 0ZM1 1L1 6L6 6L6 1ZM2 2L2 5L5 5L5 2ZM22 0L22 7L29 7L29 0ZM23 1L23 6L28 6L28 1ZM24 2L24 5L27 5L27 2ZM0 22L0 29L7 29L7 22ZM1 23L1 28L6 28L6 23ZM2 24L2 27L5 27L5 24Z" fill="#000000"/></g></g></svg>
                                </div>
                            </div>

                            <div class="font-medium">
                                <h3>Amount:</h3>
                            </div>
                            <div class="text-left"><?php echo number_format($crypto_amount, 8); ?> <?php echo $selected_coin; ?></div>

                            <div class="font-medium">
                                <h3>Network Type:</h3>
                            </div>
                            <div><?php echo $selected_coin; ?> Network</div>

                                                        <div class="font-medium py-3">
                                <h3>Wallet Address:</h3>
                            </div>
                            <div class="p-3 bg-gray-300 text-blue-500 rounded-md font-mono font-medium flex justify-between items-center">
                                <span id="wallet-address"><?php echo $wallet_address; ?></span>
                                <button onclick="copyWalletAddress()" class="ml-2 p-1 text-blue-500 hover:text-blue-700" title="Copy to clipboard">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
                                    </svg>
                                </button>
                            </div>
                            

                            <div class="font-medium">
                                <h3>Payment Instruction:</h3>
                            </div>
                            <div>
                                <p><strong>Payment instructions</strong></p>
                                <p><i><strong>1. Get a <?php echo $selected_coin; ?> wallet</strong></i></p>
                                <p><i><strong>2. Purchase <?php echo $selected_coin; ?> equivalent to your investment amount</strong></i></p>
                                <p><i><strong>3. Copy the <?php echo $selected_coin; ?> address provided above</strong></i></p>
                                <p><i><strong>4. Send <?php echo number_format($crypto_amount, 8); ?> <?php echo $selected_coin; ?> to the address</strong></i></p>
                                <p><i><strong>5. Take a screenshot of the transaction for confirmation</strong></i></p>
                            </div>
                        </div>
                        
                        <div class="w-full flex justify-start items-center space-x-5 mt-10">
                            <div>
                                <button type="button" class="save-deposit-btn text-xs md:text-sm text-[#d1d5db] text-center px-5 py-2 bg-[#1b2e4b] hover:bg-gray-700 rounded-md">
                                    Save Deposit
                                </button>
                            </div>
                            
                            <div>
                                <button type="button" class="text-xs md:text-sm text-[#d1d5db] text-center px-5 py-2 bg-red-600 hover:bg-red-400 rounded-md cancel-payment">
                                    Cancel
                                </button>
                            </div>
                        </div>
                    </div>

                    <form id="manual-cancel-form" action="deposits.php" method="POST">
                    </form>
                </div>
            </div>
        </div>

        <script>
            jQuery(function() {
                // on payment cancel
                $(".cancel-payment").click(function() {
                    Swal.fire({
                        title: 'Cancel payment?',
                        text: "Are you sure you want to cancel your payment?",
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#1b2e4b',
                        cancelButtonColor: '#d33',
                        confirmButtonText: 'Yes, cancel',
                        cancelButtonText: 'No',
                        background: "#0e1726",
                        color: "#d1d5db",
                    }).then((result) => {
                        if (result.isConfirmed) {
                            $("#manual-cancel-form").submit();
                        }
                    });
                });
        
                // save deposit
                $(".save-deposit-btn").click(function() {
                    Swal.fire({
                        html: `
                        <div class="p-2 md:p-4 text-[#bfc9d4]">
                            <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST" enctype="multipart/form-data">
                                <h3 class="text-sm lg:text-base font-medium mb-4">Save Deposit</h3>
                                <div class="space-y-5">
                                    <div>
                                        <label style="float:left !important;" for="screenshot" class="w-full text-xs lg:text-sm text-left">Upload payment screenshot:</label>
                                        <input class="cred-hyip-theme1-text-input pl-4" id="screenshot" type="file" accept="image/png, image/jpg, image/jpeg" placeholder="Upload screenshot" name="payment_screenshot" required>
                                    </div>
                                </div>
                                <div class="w-full my-5" align="left">
                                    <button type="submit" class="w-1/3 text-xs md:text-sm text-[#d1d5db] text-center px-5 py-2 bg-[#1b2e4b] hover:bg-gray-700 rounded-md">
                                        Save
                                    </button>
                                </div>
                            </form>
                        </div>
                        `,
                        showCancelButton: false,
                        showConfirmButton: false,
                        showCloseButton: true,
                        background: "#0e1726",
                        color: "#d1d5db",
                    });
                });
            });
            
                            // Copy wallet address function
                function copyWalletAddress() {
                    const walletAddress = document.getElementById('wallet-address').innerText;
                    navigator.clipboard.writeText(walletAddress).then(() => {
                        Swal.fire({
                            icon: 'success',
                            title: 'Copied!',
                            text: 'Wallet address copied to clipboard',
                            background: "#0e1726",
                            color: "#d1d5db",
                            timer: 2000,
                            showConfirmButton: false
                        });
                    }).catch(err => {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'Failed to copy address',
                            background: "#0e1726",
                            color: "#d1d5db"
                        });
                    });
                }
        </script>
    </div>

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