<?php
$pageTitle = 'Payment';
require_once 'includes/header.php';

if (!isLoggedIn()) {
    redirect(BASE_URL . 'login.php');
}

$bookingDbId = intval($_GET['booking'] ?? 0);
$db = getDBConnection();

$stmt = $db->prepare("
    SELECT b.*, p.title as package_title, p.slug as package_slug
    FROM bookings b 
    JOIN packages p ON b.package_id = p.id 
    WHERE b.id = ? AND b.user_id = ? AND b.payment_status = 'pending'
");
$stmt->execute([$bookingDbId, $_SESSION['user_id']]);
$booking = $stmt->fetch();

if (!$booking) {
    setFlash('danger', 'Booking not found or already paid.');
    redirect(USER_URL . 'bookings.php');
}

$settings = getAllSettings();

// Handle payment submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $paymentMethod = sanitize($_POST['payment_method'] ?? 'cash');
    
    // For demo purposes, simulate payment success
    $transactionId = generateTransactionId();
    
    try {
        $db->beginTransaction();
        
        // Update booking
        $stmt = $db->prepare("UPDATE bookings SET status = 'confirmed', payment_status = 'paid', payment_method = ? WHERE id = ?");
        $stmt->execute([$paymentMethod, $booking['id']]);
        
        // Create transaction
        $stmt = $db->prepare("
            INSERT INTO transactions (transaction_id, booking_id, user_id, amount, payment_method, payment_gateway_id, status)
            VALUES (?, ?, ?, ?, ?, ?, 'success')
        ");
        $stmt->execute([
            $transactionId,
            $booking['id'],
            $_SESSION['user_id'],
            $booking['final_amount'],
            $paymentMethod,
            'DEMO_' . strtoupper($paymentMethod) . '_' . time()
        ]);
        
        $db->commit();
        
        logActivity($_SESSION['user_id'], 'payment_success', "Payment $transactionId for booking " . $booking['booking_id']);
        setFlash('success', 'Payment successful! Your booking is confirmed. Booking ID: ' . $booking['booking_id']);
        redirect(USER_URL . 'bookings.php');
        
    } catch (Exception $e) {
        $db->rollBack();
        setFlash('danger', 'Payment failed. Please try again.');
    }
}
?>

<div style="margin-top:75px;padding:60px 0;min-height:80vh;">
    <div class="container">
        <div style="max-width:700px;margin:0 auto;">
            <h1 style="margin-bottom:30px;"><i class="fas fa-credit-card text-primary"></i> Complete Payment</h1>
            
            <!-- Booking Summary -->
            <div class="admin-card">
                <div class="card-header">
                    <h3>Booking Summary</h3>
                    <span class="status-badge status-pending">Pending Payment</span>
                </div>
                <div class="card-body">
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:15px;">
                        <div>
                            <p style="color:var(--gray);font-size:0.85rem;">Booking ID</p>
                            <p style="font-weight:600;"><?= $booking['booking_id'] ?></p>
                        </div>
                        <div>
                            <p style="color:var(--gray);font-size:0.85rem;">Package</p>
                            <p style="font-weight:600;"><?= sanitize($booking['package_title']) ?></p>
                        </div>
                        <div>
                            <p style="color:var(--gray);font-size:0.85rem;">Travel Date</p>
                            <p style="font-weight:600;"><?= formatDate($booking['travel_date']) ?></p>
                        </div>
                        <div>
                            <p style="color:var(--gray);font-size:0.85rem;">People</p>
                            <p style="font-weight:600;"><?= $booking['num_people'] ?> Person(s)</p>
                        </div>
                    </div>
                    
                    <div style="margin-top:20px;padding-top:15px;border-top:1px solid var(--gray-lighter);">
                        <div style="display:flex;justify-content:space-between;margin-bottom:8px;">
                            <span style="color:var(--gray);">Total Amount</span>
                            <span><?= formatCurrency($booking['total_amount']) ?></span>
                        </div>
                        <?php if ($booking['discount_amount'] > 0): ?>
                        <div style="display:flex;justify-content:space-between;margin-bottom:8px;">
                            <span style="color:var(--success);">Discount</span>
                            <span style="color:var(--success);">-<?= formatCurrency($booking['discount_amount']) ?></span>
                        </div>
                        <?php endif; ?>
                        <div style="display:flex;justify-content:space-between;font-size:1.2rem;font-weight:700;color:var(--primary);padding-top:10px;border-top:1px dashed var(--gray-lighter);">
                            <span>Amount to Pay</span>
                            <span><?= formatCurrency($booking['final_amount']) ?></span>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Payment Methods -->
            <div class="admin-card">
                <div class="card-header">
                    <h3>Select Payment Method</h3>
                </div>
                <div class="card-body">
                    <form method="POST">
                        <div style="display:grid;gap:12px;margin-bottom:25px;">
                            <?php if ($settings['razorpay_enabled'] ?? '0'): ?>
                            <label style="display:flex;align-items:center;gap:15px;padding:15px;border:2px solid var(--gray-lighter);border-radius:var(--radius);cursor:pointer;transition:all 0.2s ease;" class="payment-option">
                                <input type="radio" name="payment_method" value="razorpay" checked style="accent-color:var(--primary);width:18px;height:18px;">
                                <div>
                                    <strong style="display:block;">Razorpay</strong>
                                    <small style="color:var(--gray);">Pay securely with UPI, Cards, Net Banking</small>
                                </div>
                                <i class="fas fa-credit-card" style="margin-left:auto;font-size:1.5rem;color:var(--secondary);"></i>
                            </label>
                            <?php endif; ?>
                            
                            <?php if ($settings['phonepe_enabled'] ?? '0'): ?>
                            <label style="display:flex;align-items:center;gap:15px;padding:15px;border:2px solid var(--gray-lighter);border-radius:var(--radius);cursor:pointer;transition:all 0.2s ease;" class="payment-option">
                                <input type="radio" name="payment_method" value="phonepe" style="accent-color:var(--primary);width:18px;height:18px;">
                                <div>
                                    <strong style="display:block;">PhonePe</strong>
                                    <small style="color:var(--gray);">Pay with PhonePe UPI</small>
                                </div>
                                <i class="fas fa-mobile-alt" style="margin-left:auto;font-size:1.5rem;color:#5F259F;"></i>
                            </label>
                            <?php endif; ?>
                            
                            <?php if ($settings['cash_enabled'] ?? '1'): ?>
                            <label style="display:flex;align-items:center;gap:15px;padding:15px;border:2px solid var(--gray-lighter);border-radius:var(--radius);cursor:pointer;transition:all 0.2s ease;" class="payment-option">
                                <input type="radio" name="payment_method" value="cash" <?= !($settings['razorpay_enabled'] ?? '0') ? 'checked' : '' ?> style="accent-color:var(--primary);width:18px;height:18px;">
                                <div>
                                    <strong style="display:block;">Cash Payment</strong>
                                    <small style="color:var(--gray);">Pay at our office or to the tour guide</small>
                                </div>
                                <i class="fas fa-money-bill-wave" style="margin-left:auto;font-size:1.5rem;color:var(--success);"></i>
                            </label>
                            <?php endif; ?>
                        </div>
                        
                        <button type="submit" class="btn btn-primary btn-block btn-lg">
                            <i class="fas fa-lock"></i> Pay <?= formatCurrency($booking['final_amount']) ?>
                        </button>
                        
                        <p style="text-align:center;margin-top:15px;font-size:0.82rem;color:var(--gray);">
                            <i class="fas fa-shield-alt"></i> Your payment is secured with 256-bit SSL encryption
                        </p>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.payment-option:has(input:checked) {
    border-color: var(--primary) !important;
    background: rgba(255, 107, 53, 0.03);
}
</style>

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