<?php
// payment.php - Payment Page for Users
// File location: /bidwheels.net/user/payment.php

require_once '../includes/auth.php';
require_once '../includes/functions.php';
require_once '../includes/mailer.php';
require_once '../includes/header.php';

requireLogin();

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

// Get product details
$product = fetchOne("SELECT * FROM products WHERE id = $product_id");
if (!$product) {
    redirect('/user/dashboard.php');
}

// Get user's winning bid
$winning_bid = fetchOne("
    SELECT b.* FROM bids b
    WHERE b.product_id = $product_id 
    AND b.user_id = {$_SESSION['user_id']}
    AND b.amount = (SELECT MAX(amount) FROM bids WHERE product_id = $product_id)
    LIMIT 1
");

if (!$winning_bid) {
    redirect('/user/dashboard.php');
}

// Get active payment methods
$payment_methods = fetchAll("SELECT * FROM payment_methods WHERE is_active = 1");

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_payment'])) {
    $payment_method = sanitize($_POST['payment_method']);
    $phone = sanitize($_POST['phone']);
    $email = sanitize($_POST['email']);
    
    // Collect all payment fields
    $payment_data = [];
    foreach ($_POST as $key => $value) {
        if (strpos($key, 'field_') === 0) {
            $field_name = str_replace('field_', '', $key);
            $payment_data[$field_name] = sanitize($value);
        }
    }
    
    // Save payment
    $payment_id = insert('payments', [
        'user_id' => $_SESSION['user_id'],
        'product_id' => $product_id,
        'bid_id' => $winning_bid['id'],
        'payment_method' => $payment_method,
        'payment_data' => json_encode($payment_data),
        'phone' => $phone,
        'email' => $email
    ]);
    
    if ($payment_id) {
        // Send confirmation email
        sendPaymentConfirmationEmail(
            $_SESSION['user_email'],
            $_SESSION['user_name'],
            $product['name'],
            $winning_bid['amount']
        );
        
        $success = "Your payment information has been submitted. Our team will contact you within 24-48 hours.";
    } else {
        $error = "Failed to save payment information. Please try again.";
    }
}
?>

<div class="container">
    <div class="payment-container" style="max-width: 800px; margin: 50px auto;">
        <div class="payment-card" style="background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
            <h2 style="margin-bottom: 20px;">Complete Payment</h2>
            
            <div class="winning-info" style="background: #d4edda; padding: 15px; border-radius: 5px; margin-bottom: 25px;">
                <h3>You Won!</h3>
                <p>Product: <strong><?php echo htmlspecialchars($product['name']); ?></strong></p>
                <p>Winning Bid: <strong style="color: #e63946;"><?php echo formatPrice($winning_bid['amount']); ?></strong></p>
                <p>Please provide your payment information below. This is a manual payment process.</p>
            </div>
            
            <?php if ($success): ?>
                <div class="alert alert-success"><?php echo $success; ?></div>
                <a href="dashboard.php" class="btn btn-primary">Go to Dashboard</a>
            <?php else: ?>
                
                <?php if ($error): ?>
                    <div class="alert alert-danger"><?php echo $error; ?></div>
                <?php endif; ?>
                
                <form method="POST" action="">
                    <div class="form-group" style="margin-bottom: 20px;">
                        <label>Select Payment Method *</label>
                        <select name="payment_method" id="payment_method" class="form-control" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
                            <option value="">Select...</option>
                            <?php foreach ($payment_methods as $method): ?>
                                <option value="<?php echo htmlspecialchars($method['method_name']); ?>"><?php echo htmlspecialchars($method['method_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div id="payment_fields" class="payment-fields" style="margin-bottom: 20px;"></div>
                    
                    <div class="form-row" style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                        <div class="form-group">
                            <label>Phone Number *</label>
                            <input type="tel" name="phone" class="form-control" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
                        </div>
                        <div class="form-group">
                            <label>Email Address *</label>
                            <input type="email" name="email" class="form-control" value="<?php echo $_SESSION['user_email']; ?>" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
                        </div>
                    </div>
                    
                    <button type="submit" name="submit_payment" class="btn btn-primary" style="width: 100%; padding: 12px; background: #e63946; color: white; border: none; border-radius: 5px; font-size: 16px; cursor: pointer;">Submit Payment Information</button>
                </form>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
// Dynamic payment fields based on selection
document.getElementById('payment_method').addEventListener('change', function() {
    const method = this.value;
    const fieldsContainer = document.getElementById('payment_fields');
    
    // Predefined fields for credit card and bank transfer
    if (method === 'Credit Card') {
        fieldsContainer.innerHTML = `
            <h4 style="margin-bottom: 15px;">Credit Card Information</h4>
            <div class="form-group" style="margin-bottom: 15px;">
                <label>Name on Card</label>
                <input type="text" name="field_Name_on_Card" class="form-control" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
            </div>
            <div class="form-group" style="margin-bottom: 15px;">
                <label>Zip/Postal Code</label>
                <input type="text" name="field_Zip_Code" class="form-control" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
            </div>
            <div class="form-group" style="margin-bottom: 15px;">
                <label>Credit Card Number</label>
                <input type="text" name="field_Card_Number" class="form-control" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
            </div>
            <div class="form-row" style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div class="form-group">
                    <label>Expiration (MM/YY)</label>
                    <input type="text" name="field_Expiration" placeholder="MM/YY" class="form-control" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
                </div>
                <div class="form-group">
                    <label>CVC</label>
                    <input type="text" name="field_CVC" class="form-control" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
                </div>
            </div>
        `;
    } else if (method === 'Bank Transfer') {
        fieldsContainer.innerHTML = `
            <h4 style="margin-bottom: 15px;">Bank Transfer Information</h4>
            <div class="form-group" style="margin-bottom: 15px;">
                <label>Account Name</label>
                <input type="text" name="field_Account_Name" class="form-control" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
            </div>
            <div class="form-group" style="margin-bottom: 15px;">
                <label>Account Number</label>
                <input type="text" name="field_Account_Number" class="form-control" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
            </div>
            <div class="form-group" style="margin-bottom: 15px;">
                <label>Bank Name</label>
                <input type="text" name="field_Bank_Name" class="form-control" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
            </div>
            <div class="form-group" style="margin-bottom: 15px;">
                <label>Routing Number</label>
                <input type="text" name="field_Routing_Number" class="form-control" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
            </div>
        `;
    } else {
        fieldsContainer.innerHTML = '<p>Select a payment method to see required fields.</p>';
    }
});
</script>

<style>
@media (max-width: 768px) {
    .form-row {
        grid-template-columns: 1fr !important;
    }
}
</style>

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