<?php
$page_title = "Complete Your Deposit";

require_once '../config/config.php';

require_once '../includes/user_auth.php';
require_once '../includes/functions.php';


$db = Database::getInstance()->connect();
if (!$auth->isLoggedIn()) {
    header("Location: ../login.php");
    exit();
}
$user_id = $auth->getCurrentUserId();

$transaction = null;

if (isset($_GET['ref'])) {
    $reference = $_GET['ref'];
    // Get transaction details
    $stmt = $db->prepare("SELECT * FROM transactions WHERE reference = ? AND user_id = ? AND type = 'deposit' AND status = 'pending'");
    $stmt->execute([$reference, $user_id]);
    $transaction = $stmt->fetch();

    if (!$transaction) {
        $_SESSION['error'] = "Invalid or completed deposit request.";
        header('Location: transactions.php');
        exit();
    }
} elseif (isset($_GET['amount']) && isset($_GET['method'])) {
    $transaction = [
        'amount' => floatval($_GET['amount']),
        'method' => $_GET['method'],
        'id' => 0 // Placeholder ID
    ];
} else {
    header('Location: deposit.php');
    exit();
}

$deposit_addresses = [
    'bitcoin' => 'bc1qdxvh25ruxz3u34czxnwdca6uese3zr7ndj2r5p',
   // 'ethereum' => '0x742d35Cc6634C0532925a3b844Bc9e0F7d5A5c7a',
   // 'usdt_erc20' => '0x742d35Cc6634C0532925a3b844Bc9e0F7d5A5c7a',
    'usdt_trc20' => 'TXvJhuvb19T7o4CuM93qU4hUe9enVgLCeE'
];

$payment_method_name = ucfirst(str_replace('_', ' ', $transaction['method']));
$wallet_address = $deposit_addresses[$transaction['method']] ?? 'Contact support for address';

// Handle payment proof upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_proof'])) {
    if (isset($_FILES['payment_proof']) && $_FILES['payment_proof']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['payment_proof'];
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
        $max_size = 5 * 1024 * 1024; // 5MB

        if (!in_array($file['type'], $allowed_types)) {
            $_SESSION['error'] = "Invalid file type. Only JPG, PNG, GIF, and PDF are allowed.";
        } elseif ($file['size'] > $max_size) {
            $_SESSION['error'] = "File size too large. Maximum size is 5MB.";
        } else {
            $upload_dir = '../uploads/proofs/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }

            $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
            $filename = 'proof_' . $user_id . '_' . time() . '.' . $extension;
            $filepath = $upload_dir . $filename;

            if (move_uploaded_file($file['tmp_name'], $filepath)) {
                if (isset($_GET['ref']) && $transaction['id'] > 0) {
                    // Update existing transaction
                    $update_stmt = $db->prepare("UPDATE transactions SET payment_proof = ? WHERE id = ?");
                    $update_stmt->execute([$filename, $transaction['id']]);
                } else {
                    // Create new transaction with proof
                    $functions->processDeposit($user_id, $transaction['amount'], $transaction['method'], $filename);
                }

                $_SESSION['success'] = "Payment proof uploaded successfully. Your deposit will be reviewed by an admin.";
                header('Location: transactions.php');
                exit();
            } else {
                $_SESSION['error'] = "Failed to upload payment proof.";
            }
        }
    } else {
        $_SESSION['error'] = "Please select a valid file to upload.";
    }
    
    // Redirect back with params to preserve state on error
    $query = $_SERVER['QUERY_STRING'];
    header('Location: deposit-payment.php?' . $query);
    exit();
}

?>

<?php require_once '../includes/header_user.php'; ?>
<div class="container-fluid">
    <div class="max-w-2xl mx-auto">
        <div class="bg-white rounded-xl shadow-lg p-8">
            <div class="text-center mb-8">
                <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fas fa-wallet text-2xl text-blue-600"></i>
                </div>
                <h1 class="text-2xl font-bold text-gray-800">Complete Your Deposit</h1>
                <p class="text-gray-600 mt-2">Please follow the instructions below to complete your deposit of <span class="font-bold">$<?php echo number_format($transaction['amount'], 2); ?></span>.</p>
            </div>

            <!-- Payment Instructions -->
            <div class="bg-gray-50 border border-gray-200 rounded-lg p-6 mb-6">
                <h3 class="font-bold text-lg mb-4">Step 1: Make Payment</h3>
                <p class="text-sm text-gray-600 mb-2">
                    Please send exactly <strong class="text-green-600"><?php echo number_format($transaction['amount'], 2); ?> USD</strong> worth of <strong><?php echo $payment_method_name; ?></strong> to the following address:
                </p>
                <div class="bg-gray-200 p-4 rounded-lg">
                    <div id="qrcode" class="flex justify-center mb-4"></div>
                    <code id="walletAddress" class="block text-center break-all font-mono text-gray-800"><?php echo $wallet_address; ?></code>
                    <button onclick="copyToClipboard('<?php echo $wallet_address; ?>')" class="mt-3 w-full bg-gray-800 text-white py-2 rounded-lg hover:bg-gray-700 text-sm">
                        <i class="fas fa-copy mr-2"></i>Copy Address
                    </button>
                </div>
                <div class="mt-4 text-center text-yellow-700 bg-yellow-50 p-3 rounded-lg text-sm">
                    <i class="fas fa-exclamation-triangle mr-2"></i>
                    Ensure you send the correct amount to the correct address. Incorrect payments may be lost.
                </div>
            </div>

            <!-- Upload Proof -->
            <div class="bg-gray-50 border border-gray-200 rounded-lg p-6">
                <h3 class="font-bold text-lg mb-4">Step 2: Upload Proof of Payment</h3>
                <p class="text-sm text-gray-600 mb-4">
                    After making the payment, please upload a screenshot or a document of the transaction confirmation.
                </p>
                <form method="POST" enctype="multipart/form-data">
                    <div class="mb-4">
                        <label for="payment_proof" class="block text-sm font-medium text-gray-700 mb-2">Payment Proof (Screenshot, PDF, etc.)</label>
                        <input type="file" id="payment_proof" name="payment_proof" required
                               class="w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-purple-50 file:text-purple-700 hover:file:bg-purple-100">
                    </div>
                    <button type="submit" name="upload_proof" class="w-full bg-gradient-to-r from-purple-600 to-blue-600 text-white font-bold py-3 px-4 rounded-lg hover:opacity-90 transition duration-300">
                        <i class="fas fa-check-circle mr-2"></i>Confirm & Upload Proof
                    </button>
                </form>
            </div>

            <div class="text-center mt-6">
                <a href="transactions.php" class="text-gray-600 hover:text-gray-800 text-sm">
                    <i class="fas fa-arrow-left mr-1"></i> I'll do this later
                </a>
            </div>
        </div>
    </div>
</div>

<!-- QR Code Library -->
<script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>
<script>
    function copyToClipboard(text) {
        navigator.clipboard.writeText(text).then(function() {
            showNotification('Address copied to clipboard!', 'success');
        }, function(err) {
            showNotification('Failed to copy address.', 'error');
        });
    }

    // Generate QR code
    const walletAddress = document.getElementById('walletAddress').textContent;
    if (walletAddress && walletAddress !== 'Contact support for address') {
        new QRCode(document.getElementById("qrcode"), {
            text: walletAddress,
            width: 180,
            height: 180,
            colorDark : "#000000",
            colorLight : "#ffffff",
            correctLevel : QRCode.CorrectLevel.H
        });
    }
</script>

<?php require_once '../includes/footer.php'; ?>

<script>
    // Override notification function to match deposit page style
    function showNotification(message, type = 'info') {
        const container = document.getElementById('notification-container');
        const notification = document.createElement('div');
        
        // Tailwind classes for styling
        const baseClasses = 'transform transition-all duration-300 ease-in-out translate-x-full bg-white rounded-lg shadow-lg p-4 flex items-center space-x-3 min-w-[300px] border-l-4';
        const typeClasses = type === 'success' ? 'border-green-500' : (type === 'error' ? 'border-red-500' : 'border-blue-500');
        const iconClass = type === 'success' ? 'fa-check-circle text-green-500' : (type === 'error' ? 'fa-exclamation-circle text-red-500' : 'fa-info-circle text-blue-500');
        
        notification.className = `${baseClasses} ${typeClasses}`;
        notification.innerHTML = `
            <i class="fas ${iconClass} text-xl"></i>
            <div class="flex-1">
                <p class="text-sm font-medium text-gray-900">${message}</p>
            </div>
            <button onclick="this.parentElement.remove()" class="text-gray-400 hover:text-gray-500">
                <i class="fas fa-times"></i>
            </button>
        `;

        container.appendChild(notification);

        // Animate in
        requestAnimationFrame(() => {
            notification.classList.remove('translate-x-full');
        });

        // Auto dismiss
        setTimeout(() => {
            notification.classList.add('translate-x-full');
            setTimeout(() => {
                notification.remove();
            }, 300);
        }, 3000);
    }
</script>