<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Database connection
    $conn = new mysqli('localhost', 'betadat3_vtu1', 'betadat3_vtu1', 'betadat3_vtu1');
    if ($conn->connect_error) {
        die('Connection failed: ' . $conn->connect_error);
    }

    // Sanitize inputs
    $amountSell = $conn->real_escape_string($_POST['amountSell']);
    $totalAmount = $conn->real_escape_string($_POST['totalAmount']);
    $bankAccount = $conn->real_escape_string($_POST['bankAccount']);
    $bankName = $conn->real_escape_string($_POST['bankName']);
    $receiverName = $conn->real_escape_string($_POST['receiverName']);
    $whatsAppNumber = $conn->real_escape_string($_POST['whatsAppNumber']);
    
    // Handle file upload
    $targetDir = "uploads/";
    $transactionReceipt = $targetDir . basename($_FILES["transactionReceipt"]["name"]);
    if (move_uploaded_file($_FILES["transactionReceipt"]["tmp_name"], $transactionReceipt)) {
        // Insert data into database
        $sql = "INSERT INTO sell_pi_requests (amount_sell, total_amount, bank_account, bank_name, receiver_name, 
                wallet_address, transaction_receipt, whatsapp) 
                VALUES ('$amountSell', '$totalAmount', '$bankAccount', '$bankName', '$receiverName', 
                        'hkbgomvfjevjsncsjss', '$transactionReceipt', '$whatsAppNumber')";

        if ($conn->query($sql) === TRUE) {
            echo "<script>alert('Congratulations! Wait for admin to approve your transaction.');</script>";
        } else {
            echo "Error: " . $conn->error;
        }
    } else {
        echo "<script>alert('Failed to upload receipt.');</script>";
    }

    $conn->close();
}
?>
// Retrieve Pi price from configuration or hardcoded for simplicity
$piPrice = 1250;
?>

<div class="page-content header-clear-medium">
    <div class="card card-style">
        <div class="content">
            <div class="text-center mb-3"><img src="/images/pi_network_logo.png" width="100" alt="Pi Network Logo" /></div>
            <p class="text-center mb-0 font-600 color-highlight">Sell Your Pi Now</p>
            <h1 class="text-center mb-3">Pi Selling Service</h1>
            
            <div class="mt-5">
                <form method="post" enctype="multipart/form-data" class="contactForm" id="sellPiForm">
                    <fieldset>
                        <!-- Display Pi Price -->
                        <div class="input-style input-style-always-active has-borders validate-field">
                            <label for="piPrice" class="color-highlight">Pi Price (₦)</label>
                            <input type="number" id="piPrice" value="<?php echo $piPrice; ?>" readonly />
                        </div>
                        
                        <!-- Amount to sell -->
                        <div class="input-style input-style-always-active has-borders validate-field">
                            <label for="amountSell" class="color-highlight">Amount of Pi to Sell</label>
                            <input type="number" id="amountSell" name="amountSell" required />
                        </div>
                        
                        <!-- Total sell amount -->
                        <div class="input-style input-style-always-active has-borders validate-field">
                            <label for="totalAmount" class="color-highlight">Total Amount (₦)</label>
                            <input type="number" id="totalAmount" readonly />
                        </div>

                        <!-- Bank Details -->
                        <div class="input-style input-style-always-active has-borders validate-field">
                            <label for="bankAccount" class="color-highlight">Your Bank Account Number</label>
                            <input type="text" id="bankAccount" name="bankAccount" required />
                        </div>

                        <div class="input-style input-style-always-active has-borders validate-field">
                            <label for="bankName" class="color-highlight">Bank Name</label>
                            <input type="text" id="bankName" name="bankName" list="bankOptions" required />
                            <datalist id="bankOptions">
                                <option value="First Bank">
                                <option value="GT Bank">
                                <option value="Access Bank">
                            </datalist>
                        </div>
                        
                        <div class="input-style input-style-always-active has-borders validate-field">
                            <label for="receiverName" class="color-highlight">Receiver Name</label>
                            <input type="text" id="receiverName" name="receiverName" required />
                        </div>

                        <!-- Wallet Address -->
                        <div class="input-style input-style-always-active has-borders validate-field">
                            <label class="color-highlight">Wallet Address</label>
                            <div class="d-flex align-items-center">
                                <input type="text" id="walletAddress" value="hkbgomvfjevjsncsjss" readonly />
                                <button type="button" onclick="copyWalletAddress()">Copy</button>
                            </div>
                        </div>

                        <!-- Transaction Receipt -->
                        <div class="input-style input-style-always-active has-borders validate-field">
                            <label for="transactionReceipt" class="color-highlight">Upload Transaction Receipt</label>
                            <input type="file" id="transactionReceipt" name="transactionReceipt" accept="image/*" required />
                        </div>

                        <!-- WhatsApp Number -->
                        <div class="input-style input-style-always-active has-borders validate-field">
                            <label for="whatsAppNumber" class="color-highlight">Your WhatsApp Number</label>
                            <input type="text" id="whatsAppNumber" name="whatsAppNumber" required />
                        </div>

                        <!-- Submit Button -->
                        <div class="form-button-group">
                            <button type="submit" class="btn btn-full btn-m gradient-highlight">Submit</button>
                        </div>
                    </fieldset>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
// Copy wallet address to clipboard
function copyWalletAddress() {
    const walletAddress = document.getElementById("walletAddress");
    walletAddress.select();
    document.execCommand("copy");
    alert("Wallet address copied!");
}

// Calculate total amount based on Pi amount
document.getElementById("amountSell").addEventListener("input", function() {
    const piPrice = <?php echo $piPrice; ?>;
    const amount = this.value;
    const total = amount * piPrice;
    document.getElementById("totalAmount").value = total.toFixed(2);
});
</script>