File "book_ride.php"

Full path: /home/itsevak/public_html/prepaiddev.itsevak.com/dashboard/book_ride.php
File size: 18.41 B (18.41 KB bytes)
MIME-type: text/x-php
Charset: utf-8

Download   Open   Edit   Advanced Editor   Back

<?php
require_once '../includes/functions.php';

// Require login and passenger access
requireLogin();
if ($_SESSION['user_type'] !== 'passenger') {
    redirect('/dashboard/');
}

$user = getCurrentUser();
$db = Database::getInstance();

$errors = [];
$success = '';
$booking = null;

// Check if user is proceeding to payment for an existing pending booking
if (isset($_GET['action']) && $_GET['action'] === 'proceed_payment' && isset($_GET['booking_id'])) {
    $bookingId = (int)$_GET['booking_id'];
    
    // Verify the booking belongs to the current user and is pending
    $existingBooking = $db->fetch(
        "SELECT b.*, tl.name as to_location_name 
         FROM bookings b 
         JOIN to_locations tl ON b.to_location_id = tl.id 
         WHERE b.id = ? AND b.passenger_id = ? AND b.status = 'pending'",
        [$bookingId, $user['id']]
    );
    
    if ($existingBooking) {
        $booking = $existingBooking;
        $success = 'Please complete the payment for your pending booking.';
    } else {
        $errors[] = 'Invalid booking or booking is not pending.';
    }
}

// Get available destinations
$destinations = $db->fetchAll("SELECT * FROM to_locations WHERE status = 'active' ORDER BY name");

// Handle booking submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCSRFToken($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid request. Please try again.';
    } else {
        $toLocationId = (int)($_POST['to_location_id'] ?? 0);
        $paymentMethod = $_POST['payment_method'] ?? '';
        
        // Validation
        if (empty($toLocationId)) {
            $errors[] = 'Please select a destination.';
        }
        
        if (empty($paymentMethod) || !in_array($paymentMethod, ['phonepe', 'googlepay'])) {
            $errors[] = 'Please select a payment method.';
        }
        
        if (empty($errors)) {
            try {
                // Get commission amount (fare will be calculated after operator assigns pickup location)
                // For now, we'll use a fixed commission amount or calculate based on destination
                $estimatedFare = 50.00; // Placeholder - will be updated by operator
                $commissionAmount = calculateCommission($estimatedFare); // Configurable commission
                $totalAmount = $commissionAmount; // Only commission for now, fare added later
                
                // Create booking record (from_location_id and fare will be set by operator when QR is scanned)
                $db->query(
                    "INSERT INTO bookings (passenger_id, from_location_id, to_location_id, booking_type, payment_method, commission_amount, fare_amount, total_amount, status, payment_status) VALUES (?, NULL, ?, 'qr_code', ?, ?, 0.00, ?, 'pending', 'pending')",
                    [$user['id'], $toLocationId, $paymentMethod, $commissionAmount, $totalAmount]
                );
                    
                $bookingId = $db->lastInsertId();
                    
                // Generate QR code data
                $qrData = json_encode([
                    'booking_id' => $bookingId,
                    'passenger_email' => $user['email'],
                    'to_location_id' => $toLocationId,
                    'payment_method' => $paymentMethod,
                    'total_amount' => $totalAmount
                ]);
                    
                // Update booking with QR data
                $db->query(
                    "UPDATE bookings SET qr_code_data = ? WHERE id = ?",
                    [$qrData, $bookingId]
                );
                    
                // Get the complete booking
                $booking = $db->fetch(
                    "SELECT b.*, tl.name as to_location_name FROM bookings b 
                     JOIN to_locations tl ON b.to_location_id = tl.id 
                     WHERE b.id = ?",
                    [$bookingId]
                );
                    
                $success = 'Booking created successfully! Please complete the payment to get your QR code.';
                    
                    // Add information about commission and fare
                    $success .= ' You are paying commission now. The actual fare will be calculated when you visit an operator counter.';
            } catch (Exception $e) {
                $errors[] = 'Error creating booking: ' . $e->getMessage();
            }
        }
    }
}

$pageTitle = 'Book a Ride';
require_once '../includes/header.php';
?>

<div class="container py-4">
    <div class="row">
        <div class="col-md-8 mx-auto">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title mb-0">Book a Ride</h3>
                </div>
                <div class="card-body">
                    <?php if (!empty($errors)): ?>
                        <div class="alert alert-danger">
                            <ul class="mb-0">
                                <?php foreach ($errors as $error): ?>
                                    <li><?php echo htmlspecialchars($error); ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($success): ?>
                        <div class="alert alert-success">
                            <?php echo htmlspecialchars($success); ?>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (!$booking): ?>
                        <div class="row">
                            <div class="col-md-4">
                                <!-- How it works card -->
                                <div class="card h-100">
                                    <div class="card-header bg-primary text-white">
                                        <h6 class="card-title mb-0">
                                            <i class="bi bi-info-circle"></i> How it works
                                        </h6>
                                    </div>
                                    <div class="card-body">
                                        <ol class="mb-0 small">
                                            <li>Select your destination and payment method</li>
                                            <li>Pay <strong>commission only</strong> to get your QR code</li>
                                            <li>Go to <strong>any operator counter</strong> at any pickup location</li>
                                            <li>Show your QR code to the operator</li>
                                            <li>Operator will calculate <strong>actual fare</strong> and assign auto rickshaw</li>
                                            <li>Pay the fare amount to the driver</li>
                                        </ol>
                                        <hr>
                                        <div class="alert alert-info mb-0 small">
                                            <i class="bi bi-lightbulb"></i> 
                                            <strong>Note:</strong> You don't need to select pickup location now. 
                                            The operator will set it based on which counter you visit.
                                        </div>
                                        <hr>
                                        <div class="alert alert-warning mb-0 small">
                                            <i class="bi bi-currency-exchange"></i> 
                                            <strong>Payment:</strong> Pay commission now (₹5.00), fare later. 
                                            Fare is calculated by operator based on actual pickup location.
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-8">
                                <form method="POST" action="">
                                    <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                                    
                                    <div class="mb-3">
                                        <label for="to_location_id" class="form-label">Select Destination</label>
                                        <select class="form-select" id="to_location_id" name="to_location_id" required>
                                            <option value="">Choose destination...</option>
                                            <?php foreach ($destinations as $destination): ?>
                                                <option value="<?php echo $destination['id']; ?>">
                                                    <?php echo htmlspecialchars($destination['name']); ?> - 
                                                    <?php echo htmlspecialchars($destination['city']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Payment Method</label>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="payment_method" id="phonepe" value="phonepe" required>
                                            <label class="form-check-label" for="phonepe">
                                                <i class="bi bi-phone"></i> PhonePe
                                            </label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="payment_method" id="googlepay" value="googlepay" required>
                                            <label class="form-check-label" for="googlepay">
                                                <i class="bi bi-google"></i> Google Pay
                                            </label>
                                        </div>
                                    </div>
                                    
                                    <div class="d-grid">
                                        <button type="submit" class="btn btn-primary btn-lg">
                                            <i class="bi bi-credit-card"></i> Proceed to Payment
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    <?php else: ?>
                        <!-- Payment Section -->
                        <div class="text-center mb-4">
                            <h4>Complete Your Payment</h4>
                            <p class="text-muted">Amount: ₹<?php echo number_format($booking['total_amount'], 2); ?></p>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-body text-center">
                                        <h5 class="card-title"><?php echo ucfirst($booking['payment_method']); ?> Payment</h5>
                                        <p class="card-text">Scan the QR code or use UPI ID to complete payment</p>
                                        <div class="mb-3">
                                            <div id="paymentQRCode" class="qr-code-generated">
                                                <div class="text-center">
                                                    <div class="spinner-border text-primary" role="status">
                                                        <span class="visually-hidden">Loading...</span>
                                                    </div>
                                                    <br><small class="text-muted">Generating QR Code...</small>
                                                </div>
                                            </div>
                                        </div>
                                        <button class="btn btn-success" onclick="simulatePayment()">
                                            <i class="bi bi-check-circle"></i> Complete Payment
                                        </button>
                                        <button class="btn btn-outline-secondary btn-sm mt-2" onclick="generatePaymentQRCode()">
                                            <i class="bi bi-arrow-clockwise"></i> Regenerate QR
                                        </button>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-body">
                                        <h5 class="card-title">Booking Details</h5>
                                        <ul class="list-unstyled">
                                            <li><strong>Destination:</strong> <?php echo htmlspecialchars($booking['to_location_name']); ?></li>
                                            <li><strong>Pickup Location:</strong> <span class="text-muted">Will be set by operator</span></li>
                                            <li><strong>Commission:</strong> ₹<?php echo number_format($booking['commission_amount'], 2); ?></li>
                                            <li><strong>Fare:</strong> <span class="text-muted">Will be calculated by operator</span></li>
                                            <li><strong>Total (Commission Only):</strong> ₹<?php echo number_format($booking['total_amount'], 2); ?></li>
                                            <li><strong>Status:</strong> <span class="badge bg-warning">Pending Payment</span></li>
                                        </ul>
                                        
                                        <div class="alert alert-info mt-3">
                                            <h6><i class="bi bi-info-circle"></i> Next Steps:</h6>
                                            <ol class="mb-0 small">
                                                <li>Complete the payment above</li>
                                                <li>Get your QR code</li>
                                                <li>Go to <strong>any operator counter</strong></li>
                                                <li>Show QR code to operator</li>
                                                <li>Operator will assign you an auto rickshaw</li>
                                            </ol>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Check if jQuery QR plugin is loaded
    if (typeof $.fn.qrcode === 'undefined') {
        $('#paymentQRCode').html('<div class="text-center text-danger"><i class="bi bi-exclamation-triangle"></i><br><small>QR Plugin Not Loaded</small><br><button class="btn btn-sm btn-outline-danger mt-2" onclick="location.reload()">Reload Page</button></div>');
        return;
    }
    
    // Generate QR code when page loads
    generatePaymentQRCode();
    
    // Regenerate QR code if needed
    setTimeout(function() {
        if ($('#paymentQRCode canvas').length === 0) {
            generatePaymentQRCode();
        }
    }, 1000);
});

function generatePaymentQRCode() {
    const bookingId = <?php echo $booking['id'] ?? 0; ?>;
    
    if (bookingId) {
        try {
            // Create QR code data
            const qrData = {
                booking_id: bookingId,
                passenger_email: '<?php echo addslashes($user['email'] ?? ''); ?>',
                destination: '<?php echo addslashes($booking['to_location_name'] ?? ''); ?>',
                amount: <?php echo $booking['total_amount'] ?? 0; ?>,
                payment_method: '<?php echo addslashes($booking['payment_method'] ?? ''); ?>',
                timestamp: Date.now(),
                service: 'Prepaid Auto Services'
            };
            

            
            // Clear previous content
            $('#paymentQRCode').empty();
            
            // Check if jQuery QR plugin is available
            if (typeof $.fn.qrcode === 'undefined') {
                $('#paymentQRCode').html('<div class="text-center text-danger"><i class="bi bi-exclamation-triangle"></i><br><small>QR Plugin Error</small></div>');
                return;
            }
            
            // Generate QR code using jQuery plugin
            $('#paymentQRCode').qrcode({
                text: JSON.stringify(qrData),
                width: 200,
                height: 200,
                colorDark: '#000000',
                colorLight: '#ffffff',
                correctLevel: 'H'
            });
            

        } catch (error) {
            // Fallback to placeholder
            $('#paymentQRCode').html('<div class="text-center"><i class="bi bi-qr-code display-4 text-muted"></i><br><small class="text-muted">QR Code</small></div>');
        }
    } else {
        // Show placeholder if no booking
        $('#paymentQRCode').html('<div class="text-center"><i class="bi bi-qr-code display-4 text-muted"></i><br><small class="text-muted">QR Code</small></div>');
    }
}

function simulatePayment() {
    // Simulate payment processing
    const button = event.target;
    button.disabled = true;
    button.innerHTML = '<i class="bi bi-hourglass-split"></i> Processing...';
    
    setTimeout(() => {
        // Redirect to payment success page
        const bookingId = <?php echo $booking['id'] ?? 0; ?>;
        if (bookingId) {
            window.location.href = 'payment_success.php?booking_id=' + bookingId;
        } else {
            // Fallback to dashboard if no booking ID
            window.location.href = 'index.php';
        }
    }, 2000);
}
</script>

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