<?php
/**
 * Bitcoin Payment Handler
 * Digital Product Store - Manual Bitcoin Support
 */

require_once __DIR__ . '/../config/database.php';
require_login();

$order_id = isset($_GET['order_id']) ? (int)$_GET['order_id'] : 0;

if (!$order_id) {
    set_flash_message('Invalid order.', 'error');
    header('Location: ' . BASE_URL . '/cart.php');
    exit;
}

$order = get_order_by_id($order_id);

if (!$order || $order['user_id'] != get_current_user_id()) {
    set_flash_message('Order not found.', 'error');
    header('Location: ' . BASE_URL . '/cart.php');
    exit;
}

// Get Bitcoin settings
$bitcoin = get_payment_gateway('bitcoin');

if (!$bitcoin) {
    set_flash_message('Bitcoin payment is not configured.', 'error');
    header('Location: ' . BASE_URL . '/checkout.php');
    exit;
}

$config = $bitcoin['config'];
$wallet_address = $config['wallet_address'] ?? '';

if (empty($wallet_address)) {
    set_flash_message('Bitcoin wallet is not configured.', 'error');
    header('Location: ' . BASE_URL . '/checkout.php');
    exit;
}

// Get current BTC price (you can use a real API here)
// For demo, using a fixed rate - in production, use a real exchange rate API
$btc_rate = 0.000015; // Example: $1 = 0.000015 BTC (approx $66,666 per BTC)
$btc_amount = round($order['total'] * $btc_rate, 8);

// Update order status to pending (awaiting payment)
$stmt = $pdo->prepare("UPDATE orders SET payment_status = 'pending' WHERE id = ?");
$stmt->execute([$order_id]);

// Record transaction
record_payment_transaction($order_id, 'bitcoin', 'PENDING_' . time(), $order['total'], get_setting('currency_code', 'USD'), 'pending');

$page_title = 'Bitcoin Payment';
include __DIR__ . '/../header.php';
?>

<section class="py-5">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-8">
                <div class="card">
                    <div class="card-header bg-warning text-dark">
                        <i class="fab fa-bitcoin me-2"></i>Bitcoin Payment
                    </div>
                    <div class="card-body text-center">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            Send the exact amount of Bitcoin to the address below. Your order will be processed once payment is confirmed on the blockchain.
                        </div>
                        
                        <h5 class="mb-3">Order Details</h5>
                        <p><strong>Order Number:</strong> <?php echo $order['order_number']; ?></p>
                        <p><strong>Amount in <?php echo get_setting('currency_code', 'USD'); ?>:</strong> <?php echo format_price($order['total']); ?></p>
                        
                        <div class="my-4">
                            <h4 class="text-primary"><?php echo $btc_amount; ?> BTC</h4>
                            <p class="text-muted">Send exactly this amount</p>
                        </div>
                        
                        <div class="bg-light p-4 rounded mb-4">
                            <h6 class="mb-3">Bitcoin Address</h6>
                            <div class="input-group mb-3">
                                <input type="text" class="form-control text-center" value="<?php echo htmlspecialchars($wallet_address); ?>" readonly id="btc-address">
                                <button class="btn btn-outline-secondary" type="button" onclick="copyAddress()">
                                    <i class="fas fa-copy"></i>
                                </button>
                            </div>
                            <p class="text-muted small">Or scan the QR code:</p>
                            <div class="bg-white p-3 d-inline-block rounded">
                                <!-- QR Code would be generated here -->
                                <img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=bitcoin:<?php echo urlencode($wallet_address); ?>?amount=<?php echo $btc_amount; ?>" 
                                     alt="Bitcoin QR Code" class="img-fluid">
                            </div>
                        </div>
                        
                        <div class="alert alert-warning">
                            <h6><i class="fas fa-exclamation-triangle me-2"></i>Important</h6>
                            <ul class="text-start mb-0">
                                <li>Send <strong>exactly <?php echo $btc_amount; ?> BTC</strong></li>
                                <li>Use your Order Number (<strong><?php echo $order['order_number']; ?></strong>) as the payment reference/message</li>
                                <li>Payment must be made within 24 hours</li>
                                <li>Send transaction ID to <?php echo get_setting('site_email', 'support@digitalstore.com'); ?></li>
                                <li>Your order will be processed after 3 blockchain confirmations</li>
                            </ul>
                        </div>
                        
                        <div class="d-grid gap-2 mt-4">
                            <a href="<?php echo BASE_URL; ?>/order-confirmation.php?order_id=<?php echo $order_id; ?>" class="btn btn-warning">
                                <i class="fas fa-check me-2"></i>I've Sent the Payment
                            </a>
                            <a href="<?php echo BASE_URL; ?>/contact.php" class="btn btn-outline-secondary">
                                <i class="fas fa-envelope me-2"></i>Contact Support
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
function copyAddress() {
    var copyText = document.getElementById('btc-address');
    copyText.select();
    copyText.setSelectionRange(0, 99999);
    document.execCommand('copy');
    alert('Bitcoin address copied to clipboard!');
}
</script>

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