<?php 
include "include/header.php";

$sql = "SELECT btc, eth, trx, ltc, bnb, doge, usdterc20, usdttrc20 FROM wallets LIMIT 1";
$result = mysqli_query($myConn, $sql);

if (!$result) {
    die("Query failed: " . mysqli_error($myConn));
}

$wallets = mysqli_fetch_assoc($result);


?>

<?php

$username = $_SESSION['user_name']; 
$email = $_SESSION['user_email'];


$query_userdetails = "SELECT * FROM users WHERE user_email = '$email'";
$result = mysqli_query($myConn, $query_userdetails);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
$user_id  =$row["user_id"];



// Defaults (placeholders)
$cardType = "XXXXX Card";
$maskedCardNumber = "XXXX XXXX XXXX XXXX";
$cardholderName = "XXXXXXXXXXXXX";
$validThru = "XX/XX";
$cvv = "***";

// Fetch ONE card (latest)
$sql = "SELECT cardholder_name, card_type, card_number, expiry_date, cvv
        FROM cards 
        WHERE user_id = $user_id AND status = 'active'
        ORDER BY id DESC 
        LIMIT 1";

$result = mysqli_query($conn, $sql);

if ($result && mysqli_num_rows($result) > 0) {
    $row = mysqli_fetch_assoc($result);

    $cardType = htmlspecialchars($row['card_type']);
    $cardholderName = htmlspecialchars($row['cardholder_name']);
    $maskedCardNumber = "XXXX XXXX XXXX " . substr($row['card_number'], -4);
    $validThru = htmlspecialchars($row['expiry_date']);
    $cvv = htmlspecialchars($row['cvv']);
}



if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // Sanitize input
    $cardholder = mysqli_real_escape_string($conn, trim($_POST['cardholdersname']));
    $cardType = mysqli_real_escape_string($conn, trim($_POST['card_typ']));
    $email = filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL);
    $phone = mysqli_real_escape_string($conn, trim($_POST['phone']));
    $address = mysqli_real_escape_string($conn, trim($_POST['address']));
    $wallet = mysqli_real_escape_string($conn, trim($_POST['wallet_address']));
    $transactionID = mysqli_real_escape_string($conn, trim($_POST['TransactionID']));
    $currency = mysqli_real_escape_string($conn, trim($_POST['currency']));
    $amount = $_POST['amount'] ; 
    $crypto_amount = $_POST['crypto_amount'] ;

    // Validation
    $errors = [];
    if (!$cardholder) $errors[] = "Cardholder name is required.";
    if (!$cardType) $errors[] = "Card type is required.";
    if (!$email) $errors[] = "Valid email is required.";
    if (!$phone) $errors[] = "Phone number is required.";
    if (!$address) $errors[] = "Address is required.";
    if (!$wallet) $errors[] = "Wallet address is required.";

    if (!empty($errors)) {
        $errorMsg = implode("\\n", $errors);
        echo "<script>alert('$errorMsg'); window.location.href='".$_SERVER['PHP_SELF']."';</script>";
        exit;
    }

    // Handle file upload
    $proofFilePath = '';
    if (isset($_FILES['Poof_of_address']) && $_FILES['Poof_of_address']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = 'uploads/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

        $fileTmpPath = $_FILES['Poof_of_address']['tmp_name'];
        $fileName = basename($_FILES['Poof_of_address']['name']);
        $proofFilePath = $uploadDir . time() . "_" . $fileName;

        move_uploaded_file($fileTmpPath, $proofFilePath);
    }

    // Generate card details
    $cardNumber = '';
    for ($i=0; $i<16; $i++) $cardNumber .= mt_rand(0,9);
    $expiryMonth = str_pad(mt_rand(1,12), 2, '0', STR_PAD_LEFT);
    $expiryYear = date('y', strtotime('+3 years'));
    $expiryDate = $expiryMonth . '/' . $expiryYear;
    $cvv = str_pad(mt_rand(100,999), 3, '0', STR_PAD_LEFT);

    // --- Save to cards table ---
    $sql_cards = "
        INSERT INTO cards 
        (user_id, cardholder_name, card_type, email, phone, address, transaction_id, proof_file, card_number, expiry_date, cvv)
        VALUES ($user_id, '$cardholder', '$cardType', '$email', '$phone', '$address', '$transactionID', '$proofFilePath', '$cardNumber', '$expiryDate', '$cvv')
    ";
    $res = mysqli_query($conn, $sql_cards);
    if (!$res) die("Failed to save card request. MySQL error: " . mysqli_error($conn));
    $card_id = mysqli_insert_id($conn);

    // --- Save to transactions table ---
    $details = "Card request ID: $card_id";
    $status = 'pending';
    $date = date('Y-m-d H:i:s');
    $type = 'Receive';

    $sql_trans = "
        INSERT INTO transactions 
        (transaction_id, username, amount, crypto_amount, currency, type, wallet_address, proof, details, date, status)
        VALUES ('$transactionID', '$username', $amount, $crypto_amount, '$currency', '$type', '$wallet', '$proofFilePath', '$details', '$date', '$status')
    ";
    $res2 = mysqli_query($conn, $sql_trans);
    if (!$res2) die("Failed to save transaction. MySQL error: " . mysqli_error($conn));

    // --- Send confirmation email ---
    $subject = "Card Request Confirmation";
    $message = "
    <h3>Dear $cardholder,</h3>
    <p>Your card request has been successfully submitted.</p>
    <p><strong>Card Type:</strong> $cardType<br>
    Transaction ID: $transactionID</p>
    ";

    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8\r\n";
    $headers .= "From: $adminemail\r\n";

    mail($email, $subject, $message, $headers);

    echo "<script>alert('Card request submitted successfully. Card details sent to your email.'); window.location.href='".$_SERVER['PHP_SELF']."';</script>";

    mysqli_close($conn);
    exit;
}
?>



<!-- Page Content - Only Page Elements Here-->
        <div class="page-content footer-clear">

            <!-- Page Title-->
            <div class="pt-3">
                <div class="page-title d-flex">
                    <div class="align-self-center">
                        <a href="#"
                            data-back-button
                            class="me-3 ms-0 icon icon-xxs bg-theme rounded-s shadow-m">
                            <i class="bi bi-chevron-left color-theme font-14"></i>
                        </a>
                    </div>
                    <div class="align-self-center me-auto">
                        <!-- <p class="color-highlight">Hello Enabled</p> -->
                        <h1 class="color-theme">Card Request</h1>
                    </div>
                    <div class="align-self-center ms-auto">

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

            <svg id="header-deco" viewBox="0 0 1440 600" xmlns="http://www.w3.org/2000/svg" class="transition duration-300 ease-in-out delay-150">
                <path id="header-deco-1" d="M 0,600 C 0,600 0,120 0,120 C 92.36363636363635,133.79904306220095 184.7272727272727,147.59808612440193 287,148 C 389.2727272727273,148.40191387559807 501.4545454545455,135.40669856459328 592,129 C 682.5454545454545,122.5933014354067 751.4545454545455,122.77511961722489 848,115 C 944.5454545454545,107.22488038277511 1068.7272727272727,91.49282296650718 1172,91 C 1275.2727272727273,90.50717703349282 1357.6363636363635,105.25358851674642 1440,120 C 1440,120 1440,600 1440,600 Z"></path>
                <path id="header-deco-2" d="M 0,600 C 0,600 0,240 0,240 C 98.97607655502392,258.2105263157895 197.95215311004785,276.4210526315789 278,282 C 358.04784688995215,287.5789473684211 419.16746411483257,280.5263157894737 524,265 C 628.8325358851674,249.4736842105263 777.377990430622,225.47368421052633 888,211 C 998.622009569378,196.52631578947367 1071.3205741626793,191.57894736842107 1157,198 C 1242.6794258373207,204.42105263157893 1341.3397129186603,222.21052631578948 1440,240 C 1440,240 1440,600 1440,600 Z"></path>
                <path id="header-deco-3" d="M 0,600 C 0,600 0,360 0,360 C 65.43540669856458,339.55023923444975 130.87081339712915,319.1004784688995 245,321 C 359.12918660287085,322.8995215311005 521.9521531100479,347.1483253588517 616,352 C 710.0478468899521,356.8516746411483 735.3205741626795,342.3062200956938 822,333 C 908.6794258373205,323.6937799043062 1056.7655502392345,319.62679425837325 1170,325 C 1283.2344497607655,330.37320574162675 1361.6172248803828,345.1866028708134 1440,360 C 1440,360 1440,600 1440,600 Z"></path>
                <path id="header-deco-4" d="M 0,600 C 0,600 0,480 0,480 C 70.90909090909093,494.91866028708137 141.81818181818187,509.8373205741627 239,499 C 336.18181818181813,488.1626794258373 459.6363636363636,451.5693779904306 567,446 C 674.3636363636364,440.4306220095694 765.6363636363636,465.88516746411483 862,465 C 958.3636363636364,464.11483253588517 1059.8181818181818,436.8899521531101 1157,435 C 1254.1818181818182,433.1100478468899 1347.090909090909,456.555023923445 1440,480 C 1440,480 1440,600 1440,600 Z"></path>
            </svg>




            <link rel="stylesheet" href="card/style.css">
            <script src="card/costom.js"></script>

            <div class="flip-card">
                <div class="flip-card__front-side">
                    <div class="card-con container">
                        <header class="card-header">
                            <span class="card-logo">
                                <h5 class="card-h5 card-typ"><?php echo $cardType ?> Card</h5>
                            </span>
                            <img src="card/images/chip.png" alt="" class="card-chip" />
                        </header>

                        <div class="card-details">
                            <div class="logo" style="margin-left: auto; margin-right: 1%;">
                                <img src="../../img/loginlogo.png" alt="" width="60px" />
                            </div>
                        </div>

                        <div class="card-details">
                            <div class="name-number">
                                <h6 class="card-h6">Card Number</h6>
                                <h5 class="card-h5 card-number card123"><?= $maskedCardNumber ?></h5>
                                <h5 class="card-h5 card-name"><?= $cardholderName ?></h5>
                            </div>
                            <div class="valid-date">
                                <h6 class="card-h6">Valid Thru</h6>
                                <h5 class="card-h5"><?= $validThru ?></h5>
                            </div>
                        </div>
                    </div>
                </div>


                <div class="flip-card__back-side">
                    <div class="card-con container">

                        <div class="card-details">
                            <div class="logo" style="margin-bottom: 30px;">
                                <img src="../../img/loginlogo.png" alt="" width="60px" />
                            </div>
                        </div>

                        <div class="card-details" style="background-color:rgb(0, 0, 0); margin-bottom: 22px;">
                            <div class="name-number" style="margin-top: 20px; margin-bottom: 20px; margin-left: 200px;">
                                <h5 class="card-h5 card-number">ccv <?= $cvv ?></h5>
                            </div>
                        </div>
                    </div>
                </div>
            </div>




            <div class="card card-style">
                <form id="rcard_form" method="post" enctype="multipart/form-data">
                    <div class="content">

                        <h4>Shipping Details</h4>
                        <div class="form-custom form-label form-icon mb-3 mt-5">
                            <i class="bi bi-person-circle font-14"></i>
                            <input type="text" name="cardholdersname" class="form-control rounded-xs" id="cardholdersname" placeholder="John Doe" />
                            <label for="cardholdersname" class="color-highlight form-label-always-active">Cardholder Name</label>
                        </div>

                        <div class="form-custom form-label form-icon mb-3">
                            <i class="bi bi-credit-card-2-back-fill font-13"></i>
                            <select name="card_typ" class="form-select rounded-xs" id="card_typ" aria-label="Floating label select example">
                                <option selected value="">Select Card</option>
                                <option value="Visa">Visa Card</option>
                                <option value="Master">Master Card</option>
                                <option value="Platinum">Platinum Card</option>
                            </select>
                            <label for="card_typ" class="color-highlight form-label-always-active">Select Card Type</label>
                        </div>

                        <div class="row">
                            <div class="col-12">
                                <div class="form-custom form-label mb-3 form-icon">
                                    <i class="bi bi-envelope-open-fill font-14"></i>
                                    <input name="email" type="email" class="form-control rounded-xs" id="email" placeholder="1234 5678 9012 3456" />
                                    <label for="email" class="color-highlight form-label-always-active">Email</label>
                                </div>
                            </div>

                            <div class="col-12">
                                <div class="form-custom form-label mb-3 form-icon">
                                    <i class="bi bi-telephone-fill font-14"></i>
                                    <input name="phone" type="tel" class="form-control rounded-xs" id="phone" value="" />
                                    <label for="phone" class="color-highlight form-label-always-active">Phone Number</label>
                                    <!-- <span>(required)</span> -->
                                </div>
                            </div>


                            <div class="col-12">
                                <div class="form-custom form-label mb-3 form-icon">
                                    <i class="bi bi-geo-alt-fill font-12"></i>
                                    <textarea name="address" class="form-control rounded-xs" placeholder="Detail your address" id="address"></textarea>
                                    <label for="address" class="form-label-always-active color-highlight font-11">Address</label>
                                </div>
                            </div>


                            <div class="file-data">
                                <div class="form-custom form-label mb-3 form-icon">
                                    <!-- Dropify File Input -->
                                    <input type="file" id="Poof_of_address" name="Poof_of_address" class="dropify" data-height="50" data-default-file="" />
                                    <label for="Poof_of_address" class="color-highlight form-label-always-active">Upload Prove of Address</label>
                                </div>
                            </div>



                        </div>
                        <div class="divider mt-2 mb-4"></div>
                        <h4 style="margin-bottom: 17px;">Payment Details</h4>

                        <div class="divider mt-2 mb-4"></div>


                        <div id="barscan" style="display: none;">
                            <div class="col-12 text-center">
                                <div id="accordion6-3" class="text-center accordion-collapse collapse show" data-bs-parent="#accordion-group-6">
                                    <div class="row text-center">
                                        <div class="col-12 text-center"><img id="qrCodeImage" style="max-width: 50% !important;" src="https://api.qrserver.com/v1/create-qr-code/?data=Ask Admin" class="imghere img-fluid rounded-xxs"></div>
                                    </div>
                                    <h2 class="mb-2">Scan the QR Code above to get Address</h2>
                                </div>
                            </div>
                            <div class="input-group mb-2" style="display: none;" id="copyaddress">
                                <input value="Contact Admin for Wallet Address" readonly="" style="cursor: pointer;" type="text" class="form-control" id="inlineFormInputGroup" placeholder="Address" fdprocessedid="yqq2pg">
                                <div class="input-group-prepend">
                                    <div id="copyaddress" class="input-group-text" style="margin-left: 5px;"><i class="bi bi-copy"></i></div>
                                </div>


                            </div>

                            <div class="input-wrapper text-center">
                                <label class="label" for="amount3">
                                    <h4 class="m-0">Transaction ID:</h4>
                                </label>
                                <p style="color:green">
                                    QFS43818485                                </p>
                            </div>
                            <input type="hidden" value="QFS43818485" name="TransactionID">
                        </div>

                        <br>
                        <input type="hidden" name="currency" id="currency">
                        <div class="form-custom form-label form-icon mb-3">
                            <i class="bi bi-currency-bitcoin font-13"></i>
                            <select name="wallet_address" required class="form-control" id="wallet_address">
                                <option value="" disabled selected>Select a wallet address</option>

                                        <?php if (!empty($wallets['btc'])) { ?>
                                            <option value="<?= htmlspecialchars($wallets['btc']) ?>" data-wallet-name="bitcoin">
                                                Bitcoin (<?= htmlspecialchars($wallets['btc']) ?>)
                                            </option>
                                        <?php } ?>
                                    
                                        <?php if (!empty($wallets['eth'])) { ?>
                                            <option value="<?= htmlspecialchars($wallets['eth']) ?>" data-wallet-name="ethereum">
                                                Ethereum (<?= htmlspecialchars($wallets['eth']) ?>)
                                            </option>
                                        <?php } ?>
                                    
                                        <?php if (!empty($wallets['trx'])) { ?>
                                            <option value="<?= htmlspecialchars($wallets['trx']) ?>" data-wallet-name="tron">
                                                Tron (<?= htmlspecialchars($wallets['trx']) ?>)
                                            </option>
                                        <?php } ?>
                                    
                                        <?php if (!empty($wallets['ltc'])) { ?>
                                            <option value="<?= htmlspecialchars($wallets['ltc']) ?>" data-wallet-name="litecoin">
                                                Litecoin (<?= htmlspecialchars($wallets['ltc']) ?>)
                                            </option>
                                        <?php } ?>
                                    
                                        <?php if (!empty($wallets['bnb'])) { ?>
                                            <option value="<?= htmlspecialchars($wallets['bnb']) ?>" data-wallet-name="bnb">
                                                BNB (<?= htmlspecialchars($wallets['bnb']) ?>)
                                            </option>
                                        <?php } ?>
                                    
                                        <?php if (!empty($wallets['doge'])) { ?>
                                            <option value="<?= htmlspecialchars($wallets['doge']) ?>" data-wallet-name="dogecoin">
                                                Dogecoin (<?= htmlspecialchars($wallets['doge']) ?>)
                                            </option>
                                        <?php } ?>
                                    
                                        <?php if (!empty($wallets['usdterc20'])) { ?>
                                            <option value="<?= htmlspecialchars($wallets['usdterc20']) ?>" data-wallet-name="usdt-erc20">
                                                USDT ERC20 (<?= htmlspecialchars($wallets['usdterc20']) ?>)
                                            </option>
                                        <?php } ?>
                                    
                                        <?php if (!empty($wallets['usdttrc20'])) { ?>
                                            <option value="<?= htmlspecialchars($wallets['usdttrc20']) ?>" data-wallet-name="usdt-trc20">
                                                USDT TRC20 (<?= htmlspecialchars($wallets['usdttrc20']) ?>)
                                            </option>
                                        <?php } ?>
                                    
                                        <?php if (!empty($wallets['paypal'])) { ?>
                                            <option value="<?= htmlspecialchars($wallets['paypal']) ?>" data-wallet-name="paypal">
                                                PayPal (<?= htmlspecialchars($wallets['paypal']) ?>)
                                            </option>
                                        <?php } ?>
                                    </select>



                            <script>
                                $('#wallet_address').on('change', function() {
                                    var walletAddress = $(this).val();
                                    var selectedWallet = $(this).find('option:selected').text();

                                    // Update QR Code
                                    $('#qrCodeImage').attr('src', 'https://api.qrserver.com/v1/create-qr-code/?data=' + encodeURIComponent(walletAddress));
                                    $('#barscan').css('display', 'block');
                                    $('#copyaddress').css('display', 'flex');

                                    // Update Input Field
                                    $('#inlineFormInputGroup').val(walletAddress);

                                    $('.notes').css('display', 'block');

                                    $('.texzt').text(selectedWallet);
                                });
                            </script>



                            <label for="wallet_address" class="color-highlight form-label-always-active">Select Wallet</label>
                        </div>
                        <div style="margin-top: 15px; display: none;" class="notes">
                            <h4 style="color: red;">Note:</h4>
                            <div class="col-12">
                                <ul class="mb-0 ps-3">
                                    <li>Send only <b class="texzt"></b> to this wallet address. Sending any other coins may result in permanent loss.</li>
                                    <li>Minimum deposit: 10,000 USD worth of <b class="texzt"></b>.</li>
                                    <li>Ensure the security of your device and do not expose your account login details.</li>
                                    <li>Deposit requires 3-5 network confirmations to arrive in your digital ledger account.</li>
                                </ul>
                            </div>
                        </div>

                        <button type="submit" name="" class="btn btn-full gradient-highlight">
                                        Pre-Order
                                    </button>
                        </br>

                    </div>
                </form>
            </div>
            <!-- End of Page Content-->
            
            <script>
                        document.getElementById('wallet_address').addEventListener('change', function () {
                            var selected = this.options[this.selectedIndex];
                            var currency = selected.getAttribute('data-wallet-name');
                        
                            document.getElementById('currency').value = currency;
                        });
                        </script>
        

<script src="scripts/bootstrap.min.js"></script>
<script src="scripts/custom.js"></script>
</body>