/home2/mshostin/www/saudiapost/smsa/js/tracking.js
/* ============================================
   SMSA EXPRESS - TRACKING SYSTEM COMPLET
   ============================================ */

// Données de démonstration des colis
const shipmentDatabase = {
    'XHSNF74652HBL': {
        source: 'Riyadh',
        destination: 'Jeddah',
        serviceType: 'Express',
        deliveryFee: 45.50,
        estimatedDate: '2026-02-10',
        status: 'Out for Delivery',
        timeline: [
            {
                status: 'Shipment Received',
                location: 'Riyadh Distribution Center',
                coordinates: { lat: 24.7136, lng: 46.6753 },
                time: '2026-02-06 08:30'
            },
            {
                status: 'Processing',
                location: 'Riyadh Sorting Facility',
                coordinates: { lat: 24.7200, lng: 46.6800 },
                time: '2026-02-06 10:15'
            },
            {
                status: 'In Transit',
                location: 'Highway to Jeddah',
                coordinates: { lat: 24.5000, lng: 46.5000 },
                time: '2026-02-07 14:00'
            },
            {
                status: 'Out for Delivery',
                location: 'Jeddah Local Hub',
                coordinates: { lat: 21.5433, lng: 39.1728 },
                time: 'Live'
            }
        ]
    },
    'DEMO123456789': {
        source: 'Dammam',
        destination: 'Riyadh',
        serviceType: 'Standard',
        deliveryFee: 32.00,
        estimatedDate: '2026-02-12',
        status: 'Processing',
        timeline: [
            {
                status: 'Shipment Received',
                location: 'Dammam Distribution Center',
                coordinates: { lat: 26.4124, lng: 50.1971 },
                time: '2026-02-05 09:00'
            },
            {
                status: 'Processing',
                location: 'Dammam Sorting Facility',
                coordinates: { lat: 26.4200, lng: 50.2000 },
                time: '2026-02-05 11:30'
            },
            {
                status: 'In Transit',
                location: 'Highway to Riyadh',
                coordinates: { lat: 25.5000, lng: 48.5000 },
                time: 'Live'
            }
        ]
    }
};

let liveTimeInterval = null;

// Initialiser le système de tracking
document.addEventListener('DOMContentLoaded', function() {
    const trackButton = document.getElementById('btn-track');
    const trackingInput = document.getElementById('tracking-input');

    if (trackButton) {
        trackButton.addEventListener('click', trackShipment);
    }

    if (trackingInput) {
        trackingInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                trackShipment();
            }
        });
    }
});

// Fonction principale de suivi
function trackShipment() {
    const trackingInput = document.getElementById('tracking-input');
    const trackingNumber = trackingInput.value.trim().toUpperCase();

    if (!trackingNumber) {
        showAlert('Please enter a tracking number', 'error');
        return;
    }

    if (!shipmentDatabase[trackingNumber]) {
        showAlert('Tracking number not found. Try: XHSNF74652HBL or DEMO123456789', 'error');
        return;
    }

    const shipment = shipmentDatabase[trackingNumber];
    displayShipmentInfo(trackingNumber, shipment);
    displayTrackingTimeline(shipment);
    showPaymentSection(trackingNumber, shipment.deliveryFee);
    
    // Scroll vers les résultats
    setTimeout(() => {
        document.getElementById('tracking-results').scrollIntoView({ behavior: 'smooth' });
    }, 300);
}

// Afficher les informations du colis
function displayShipmentInfo(trackingNumber, shipment) {
    document.getElementById('source').textContent = shipment.source;
    document.getElementById('destination').textContent = shipment.destination;
    document.getElementById('tracking-number').textContent = trackingNumber;
    document.getElementById('service-type').textContent = shipment.serviceType;
    document.getElementById('estimated-date').textContent = formatDate(shipment.estimatedDate);
    document.getElementById('status-message').textContent = `Status: ${shipment.status}`;

    const resultsSection = document.getElementById('tracking-results');
    if (resultsSection) {
        resultsSection.classList.add('active');
    }
}

// Afficher la timeline de suivi
function displayTrackingTimeline(shipment) {
    const timeline = document.getElementById('timeline');
    timeline.innerHTML = '';

    // Arrêter l'intervalle précédent
    if (liveTimeInterval) {
        clearInterval(liveTimeInterval);
    }

    shipment.timeline.forEach((item, index) => {
        const timelineItem = createTimelineItem(item, index === shipment.timeline.length - 1);
        timeline.appendChild(timelineItem);
    });

    // Mettre à jour les heures en temps réel
    updateLiveTimeDisplay();
}

// Créer un élément de timeline
function createTimelineItem(item, isLast) {
    const div = document.createElement('div');
    div.className = `timeline-item ${item.time === 'Live' ? 'live-item' : 'completed'}`;

    let timeDisplay = item.time;
    if (item.time === 'Live') {
        timeDisplay = `<span class="live-time">${getCurrentDateTime()}</span>`;
    }

    div.innerHTML = `
        <div class="timeline-time">${timeDisplay}</div>
        <div class="timeline-status">${item.status}</div>
        <div class="timeline-location">${item.location}</div>
        <div class="timeline-coordinates">
            📍 Latitude: ${item.coordinates.lat.toFixed(4)}, Longitude: ${item.coordinates.lng.toFixed(4)}
        </div>
    `;

    return div;
}

// Obtenir la date/heure actuelle formatée
function getCurrentDateTime() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// Mettre à jour l'affichage de l'heure en temps réel
function updateLiveTimeDisplay() {
    const liveTimeElements = document.querySelectorAll('.live-time');
    
    if (liveTimeElements.length > 0) {
        // Mettre à jour immédiatement
        liveTimeElements.forEach(element => {
            element.textContent = getCurrentDateTime();
        });

        // Arrêter l'intervalle précédent
        if (liveTimeInterval) {
            clearInterval(liveTimeInterval);
        }

        // Mettre à jour toutes les secondes
        liveTimeInterval = setInterval(() => {
            const updatedElements = document.querySelectorAll('.live-time');
            updatedElements.forEach(element => {
                element.textContent = getCurrentDateTime();
            });
        }, 1000);
    }
}

// Formater la date
function formatDate(dateString) {
    const date = new Date(dateString);
    const options = { year: 'numeric', month: 'long', day: 'numeric' };
    return date.toLocaleDateString('en-US', options);
}

// Afficher la section de paiement
function showPaymentSection(trackingNumber, deliveryFee) {
    document.getElementById('tracking-number-payment').value = trackingNumber;
    document.getElementById('delivery-fee').value = `SAR ${deliveryFee.toFixed(2)}`;
    document.getElementById('payment-amount').textContent = `SAR ${deliveryFee.toFixed(2)}`;

    // Stocker les données pour le paiement
    window.currentPayment = {
        trackingNumber: trackingNumber,
        deliveryFee: deliveryFee
    };

    const paymentSection = document.getElementById('payment-section');
    if (paymentSection) {
        paymentSection.classList.add('active');
    }
}

// Afficher les alertes
function showAlert(message, type = 'info') {
    const alertBox = document.getElementById('alert-box');
    if (!alertBox) return;

    alertBox.textContent = message;
    alertBox.className = `alert active ${type}`;

    setTimeout(() => {
        alertBox.classList.remove('active');
    }, 5000);
}

// Formater le numéro de carte
document.addEventListener('DOMContentLoaded', function() {
    const cardNumberInput = document.getElementById('card-number');
    if (cardNumberInput) {
        cardNumberInput.addEventListener('input', function(e) {
            let value = e.target.value.replace(/\s/g, '');
            let formattedValue = value.replace(/(\d{4})/g, '$1 ').trim();
            e.target.value = formattedValue;
        });
    }

    const expiryInput = document.getElementById('expiry-date');
    if (expiryInput) {
        expiryInput.addEventListener('input', function(e) {
            let value = e.target.value.replace(/\D/g, '');
            if (value.length >= 2) {
                value = value.slice(0, 2) + '/' + value.slice(2, 4);
            }
            e.target.value = value;
        });
    }

    const cvvInput = document.getElementById('cvv');
    if (cvvInput) {
        cvvInput.addEventListener('input', function(e) {
            e.target.value = e.target.value.replace(/\D/g, '').slice(0, 4);
        });
    }
});