File "view_rickshaw.php"

Full path: /home/itsevak/public_html/prepaiddev.itsevak.com/dashboard/view_rickshaw.php
File size: 23.34 B (23.34 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 auto owner access
requireUserType('auto_owner');

// Get rickshaw ID from URL
$rickshawId = (int)($_GET['id'] ?? 0);

if (!$rickshawId) {
    $_SESSION['flash_message'] = 'Invalid rickshaw ID.';
    $_SESSION['flash_type'] = 'danger';
    redirect('/dashboard/manage_rickshaws.php');
}

$db = Database::getInstance();

// Get rickshaw details
$rickshaw = $db->fetch(
    "SELECT * FROM auto_rickshaws WHERE id = ? AND owner_id = ?", 
    [$rickshawId, $_SESSION['user_id']]
);

if (!$rickshaw) {
    $_SESSION['flash_message'] = 'Rickshaw not found or you do not have permission to view it.';
    $_SESSION['flash_type'] = 'danger';
    redirect('/dashboard/manage_rickshaws.php');
}

$pageTitle = 'Rickshaw Details - ' . $rickshaw['number_plate'];
require_once '../includes/header.php';
?>

<div class="container py-4">
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h2 class="mb-1">
                        <i class="bi bi-truck me-2"></i><?php echo htmlspecialchars($rickshaw['number_plate']); ?>
                    </h2>
                    <p class="text-muted mb-0">Auto Rickshaw Details</p>
                </div>
                <div>
                    <a href="<?php echo url_for('dashboard/manage_rickshaws.php'); ?>" class="btn btn-outline-secondary">
                        <i class="bi bi-arrow-left me-2"></i>Back to List
                    </a>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row">
        <!-- Basic Information -->
        <div class="col-lg-8">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="bi bi-info-circle me-2"></i>Basic Information
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label fw-bold">Number Plate</label>
                                <p class="mb-0"><?php echo htmlspecialchars($rickshaw['number_plate']); ?></p>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label fw-bold">Unique Local ID</label>
                                <p class="mb-0"><?php echo htmlspecialchars($rickshaw['unique_local_id']); ?></p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label fw-bold">Status</label>
                                <p class="mb-0"><?php echo getStatusBadge($rickshaw['status']); ?></p>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label fw-bold">Added On</label>
                                <p class="mb-0"><?php echo formatDate($rickshaw['created_at']); ?></p>
                            </div>
                        </div>
                    </div>
                    
                    <?php if ($rickshaw['updated_at'] !== $rickshaw['created_at']): ?>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Last Updated</label>
                                    <p class="mb-0"><?php echo formatDate($rickshaw['updated_at']); ?></p>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Document Photos -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="bi bi-images me-2"></i>Document Photos
                    </h5>
                </div>
                <div class="card-body">
                    <?php 
                    $hasDocuments = false;
                    $documents = [];
                    for ($i = 1; $i <= 3; $i++) {
                        $photoKey = 'document_photo_' . $i;
                        if ($rickshaw[$photoKey]) {
                            $hasDocuments = true;
                            $documents[] = $rickshaw[$photoKey];
                        }
                    }
                    ?>
                    
                    <?php if ($hasDocuments): ?>
                        <div class="row">
                            <?php for ($i = 1; $i <= 3; $i++): ?>
                                <?php $photoKey = 'document_photo_' . $i; ?>
                                <div class="col-md-4 mb-3">
                                    <?php if ($rickshaw[$photoKey]): ?>
                                        <div class="text-center">
                                            <img src="<?php echo url_for('uploads/' . $rickshaw[$photoKey]); ?>" 
                                                 class="img-fluid rounded border" 
                                                 alt="Document <?php echo $i; ?>"
                                                 style="max-height: 200px; width: 100%; object-fit: cover; cursor: pointer;"
                                                 onclick="viewRickshawDocuments(<?php echo $rickshaw['id']; ?>, <?php echo htmlspecialchars(json_encode($documents)) ?>)">
                                            <p class="mt-2 mb-0">
                                                <small class="text-muted">Click to view full size</small>
                                            </p>
                                        </div>
                                    <?php else: ?>
                                        <div class="text-center text-muted">
                                            <i class="bi bi-image display-4"></i>
                                            <p class="mt-2 mb-0">
                                                <small>No document uploaded</small>
                                            </p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            <?php endfor; ?>
                        </div>
                        
                        <div class="text-center mt-3">
                            <button type="button" class="btn btn-primary" 
                                    onclick="viewRickshawDocuments(<?php echo $rickshaw['id']; ?>, <?php echo htmlspecialchars(json_encode($documents)) ?>)">
                                <i class="bi bi-images me-2"></i>View All Documents
                            </button>
                        </div>
                    <?php else: ?>
                        <div class="text-center text-muted py-4">
                            <i class="bi bi-images display-4 mb-3"></i>
                            <p>No documents uploaded for this rickshaw.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- QR Code and Actions -->
        <div class="col-lg-4">
            <!-- QR Code -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="bi bi-qr-code me-2"></i>QR Code
                    </h5>
                </div>
                <div class="card-body text-center">
                    <div class="qr-code-container">
                        <!-- QR Code Generation Area -->
                        <div id="qrCodeDisplay" class="mb-3" style="display: none;">
                            <div id="qrcode" class="qr-code-generated"></div>
                        </div>
                        
                        <p class="mb-3">
                            <small class="text-muted">
                                Generate a QR code for this rickshaw
                            </small>
                        </p>
                        
                        <div class="d-grid gap-2">
                            <button type="button" class="btn btn-primary mb-2" onclick="generateRealQRCode()">
                                <i class="bi bi-qr-code me-2"></i>Generate Real QR Code
                            </button>
                            <button type="button" class="btn btn-success" onclick="downloadQRCode()" id="downloadQRBtn" style="display: none;">
                                <i class="bi bi-download me-2"></i>Download QR Code Image
                            </button>
                            <button type="button" class="btn btn-outline-primary" onclick="printQRCode()" id="printQRBtn" style="display: none;">
                                <i class="bi bi-printer me-2"></i>Print QR Code
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Status Information -->
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="bi bi-info-circle me-2"></i>Status Information
                    </h5>
                </div>
                <div class="card-body">
                    <?php if ($rickshaw['status'] === 'pending_approval'): ?>
                        <div class="alert alert-warning">
                            <i class="bi bi-clock me-2"></i>
                            <strong>Pending Approval</strong><br>
                            <small>Your rickshaw is currently under review. You'll be notified once it's approved.</small>
                        </div>
                    <?php elseif ($rickshaw['status'] === 'active'): ?>
                        <div class="alert alert-success">
                            <i class="bi bi-check-circle me-2"></i>
                            <strong>Active</strong><br>
                            <small>Your rickshaw is approved and ready for service.</small>
                        </div>
                    <?php elseif ($rickshaw['status'] === 'inactive'): ?>
                        <div class="alert alert-danger">
                            <i class="bi bi-x-circle me-2"></i>
                            <strong>Inactive</strong><br>
                            <small>Your rickshaw is currently inactive. Contact support for assistance.</small>
                        </div>
                    <?php endif; ?>
                    
                    <div class="mt-3">
                        <h6>Next Steps:</h6>
                        <ul class="list-unstyled">
                            <?php if ($rickshaw['status'] === 'pending_approval'): ?>
                                <li><i class="bi bi-clock text-warning me-2"></i>Wait for approval</li>
                                <li><i class="bi bi-bell text-info me-2"></i>You'll receive notification</li>
                            <?php elseif ($rickshaw['status'] === 'active'): ?>
                                <li><i class="bi bi-qr-code text-success me-2"></i>
                                    <a href="#" onclick="generateRealQRCode(); return false;" class="text-decoration-none">
                                        Generate QR code for this rickshaw
                                    </a>
                                </li>
                                <li><i class="bi bi-phone text-info me-2"></i>
                                    <a href="<?php echo url_for('dashboard/'); ?>" class="text-decoration-none">Start accepting rides</a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add JavaScript for printing and regenerating functionality -->
<script>
function printQRCode() {
    const rickshawPlate = '<?php echo htmlspecialchars($rickshaw['number_plate']); ?>';
    const qrcodeDiv = document.getElementById('qrcode');
    
    // Check if we have a generated QR code or a file path
    let imageSource = '';
    let isGeneratedQR = false;
    
    if (qrcodeDiv && qrcodeDiv.querySelector('canvas')) {
        // Use generated QR code from canvas
        const canvas = qrcodeDiv.querySelector('canvas');
        imageSource = canvas.toDataURL('image/png');
        isGeneratedQR = true;
    } else {
        // Try to use existing QR code file
        const qrCodeImage = '<?php echo url_for('uploads/' . $rickshaw['qr_code_path']); ?>';
        imageSource = qrCodeImage;
    }
    
    if (!imageSource) {
        alert('No QR code available to print. Please generate a QR code first.');
        return;
    }
    
    // Create a new window for printing
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Print QR Code - ${rickshawPlate}</title>
            <style>
                body { 
                    font-family: Arial, sans-serif; 
                    text-align: center; 
                    padding: 20px;
                    margin: 0;
                }
                .qr-container { 
                    max-width: 400px; 
                    margin: 0 auto; 
                }
                .qr-code { 
                    width: 100%; 
                    height: auto; 
                    border: 2px solid #333;
                }
                .rickshaw-info { 
                    margin-top: 20px; 
                    font-size: 18px; 
                    font-weight: bold;
                }
                .instructions { 
                    margin-top: 15px; 
                    font-size: 14px; 
                    color: #666;
                }
                .error-message {
                    color: #dc3545;
                    font-weight: bold;
                    padding: 20px;
                    border: 2px dashed #dc3545;
                    border-radius: 8px;
                }
                @media print {
                    body { margin: 0; }
                    .no-print { display: none; }
                }
            </style>
        </head>
        <body>
            <div class="qr-container">
                <h2>Auto Rickshaw QR Code</h2>
                <div class="rickshaw-info">${rickshawPlate}</div>
                <img src="${imageSource}" alt="QR Code" class="qr-code" 
                     onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">
                <div class="error-message" style="display: none;">
                    <i class="bi bi-exclamation-triangle"></i><br>
                    QR Code image could not be loaded<br>
                    <small>Please check if the file exists at: ${imageSource}</small>
                </div>
                <div class="instructions">
                    <p>Scan this QR code to verify rickshaw details</p>
                    <p>Display this code prominently on your rickshaw</p>
                </div>
                <div class="no-print">
                    <br><br>
                    <button onclick="window.print()">Print</button>
                    <button onclick="window.close()">Close</button>
                </div>
            </div>
        </body>
        </html>
    `);
    printWindow.document.close();
    
    // Check if image loads successfully
    setTimeout(() => {
        const img = printWindow.document.querySelector('.qr-code');
        if (img && img.naturalWidth === 0) {
            img.style.display = 'none';
            printWindow.document.querySelector('.error-message').style.display = 'block';
        }
    }, 1000);
}

// Enhanced Document Viewer Function
function viewRickshawDocuments(rickshawId, documents) {
    // Filter out empty documents
    documents = documents.filter(doc => doc && doc.trim() !== '');
    
    if (documents.length === 0) {
        alert('No documents available for this rickshaw.');
        return;
    }
    
    // Initialize the enhanced document viewer
    if (typeof DocumentViewer !== 'undefined') {
        DocumentViewer.init(rickshawId, documents);
    } else {
        // Fallback to simple modal if DocumentViewer is not available
        showSimpleDocumentModal(documents);
    }
}

function showSimpleDocumentModal(documents) {
    const modalHTML = `
        <div class="modal fade" id="simpleDocModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Documents</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            ${documents.map((doc, index) => `
                                <div class="col-md-6 mb-3">
                                    <div class="text-center">
                                        <img src="uploads/${doc}" class="img-fluid rounded border" alt="Document ${index + 1}">
                                        <p class="mt-2 mb-0">
                                            <small class="text-muted">Document ${index + 1}</small>
                                        </p>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Remove existing modal if any
    const existingModal = document.getElementById('simpleDocModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    // Add modal to body
    document.body.insertAdjacentHTML('beforeend', modalHTML);
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('simpleDocModal'));
    modal.show();
}

function regenerateQRCode() {
    if (confirm('Are you sure you want to regenerate the QR code for this rickshaw?')) {
        // Show loading state
        const button = event.target;
        const originalText = button.innerHTML;
        button.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>Generating...';
        button.disabled = true;
        
        // Make AJAX request to regenerate QR code
        fetch('regenerate_qr.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'rickshaw_id=<?php echo $rickshawId; ?>&csrf_token=<?php echo $_SESSION['csrf_token']; ?>'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('QR Code regenerated successfully!');
                location.reload();
            } else {
                alert('Error: ' + (data.message || 'Failed to regenerate QR code'));
                button.innerHTML = originalText;
                button.disabled = false;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error: Failed to regenerate QR code');
            button.innerHTML = originalText;
            button.disabled = false;
        });
    }
}

function generateRealQRCode() {
    const rickshawPlate = '<?php echo htmlspecialchars($rickshaw['number_plate']); ?>';
    const uniqueLocalId = '<?php echo htmlspecialchars($rickshaw['unique_local_id']); ?>';
    const qrCodeContainer = document.getElementById('qrCodeDisplay');
    const qrcodeDiv = document.getElementById('qrcode');
    const downloadBtn = document.getElementById('downloadQRBtn');
    const printBtn = document.getElementById('printQRBtn');

    if (!rickshawPlate || !uniqueLocalId) {
        alert('Rickshaw information not available to generate a QR code.');
        return;
    }

    // Create QR data dynamically (no sensitive information)
    const qrCodeData = {
        type: 'auto_rickshaw',
        number_plate: rickshawPlate,
        unique_local_id: uniqueLocalId,
        generated_at: new Date().toISOString()
    };

    // Clear previous QR code
    qrcodeDiv.innerHTML = '';
    qrCodeContainer.style.display = 'block'; // Show the container

    try {
        // Use jquery.qrcode.js to generate the QR code
        $(qrcodeDiv).qrcode({
            text: JSON.stringify(qrCodeData),
            width: 200,
            height: 200,
            ecLevel: 'H', // Error correction level
            render: 'canvas' // Use canvas for better performance
        });
        
        // Show download button after successful generation
        if (downloadBtn) {
            downloadBtn.style.display = 'block';
        }

        // Show print button after successful generation
        if (printBtn) {
            printBtn.style.display = 'block';
        }
        
        // Scroll to the generated QR code
        qrCodeContainer.scrollIntoView({ behavior: 'smooth', block: 'center' });
        
    } catch (error) {
        console.error('Error generating QR code:', error);
        alert('Error generating QR code. Please try again.');
    }
}

function downloadQRCode() {
    const qrcodeDiv = document.getElementById('qrcode');
    const rickshawPlate = '<?php echo htmlspecialchars($rickshaw['number_plate']); ?>';
    const fileName = `${rickshawPlate}_qr_code.png`;

    if (!qrcodeDiv || !qrcodeDiv.querySelector('canvas')) {
        alert('QR code not generated yet. Please generate a QR code first.');
        return;
    }

    try {
        const canvas = qrcodeDiv.querySelector('canvas');
        
        // Create a download link
        const link = document.createElement('a');
        link.download = fileName;
        
        // Convert canvas to blob and create URL
        canvas.toBlob(function(blob) {
            const url = URL.createObjectURL(blob);
            link.href = url;
            
            // Trigger download
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            // Clean up the URL
            URL.revokeObjectURL(url);
        }, 'image/png');
        
    } catch (error) {
        console.error('Error downloading QR code:', error);
        alert('Error downloading QR code. Please try again.');
    }
}

</script>

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