/home2/mshostin/public_html/saudiapost/smsa/js/tracking_ar.js
/* ============================================
   SMSA EXPRESS - نظام التتبع الكامل
   ============================================ */

// قاعدة بيانات الطرود التجريبية
const shipmentDatabase = {
    'XHSNF74652HBL': {
        source: 'الرياض',
        destination: 'جدة',
        serviceType: 'سريع',
        deliveryFee: 45.50,
        estimatedDate: '2026-02-10',
        status: 'قيد التسليم',
        timeline: [
            {
                status: 'تم استقبال الشحنة',
                location: 'مركز توزيع الرياض',
                coordinates: { lat: 24.7136, lng: 46.6753 },
                time: '2026-02-06 08:30'
            },
            {
                status: 'قيد المعالجة',
                location: 'مركز فرز الرياض',
                coordinates: { lat: 24.7200, lng: 46.6800 },
                time: '2026-02-06 10:15'
            },
            {
                status: 'قيد النقل',
                location: 'الطريق السريع إلى جدة',
                coordinates: { lat: 24.5000, lng: 46.5000 },
                time: '2026-02-07 14:00'
            },
            {
                status: 'قيد التسليم',
                location: 'مركز جدة المحلي',
                coordinates: { lat: 21.5433, lng: 39.1728 },
                time: 'مباشر'
            }
        ]
    },
    'DEMO123456789': {
        source: 'الدمام',
        destination: 'الرياض',
        serviceType: 'عادي',
        deliveryFee: 32.00,
        estimatedDate: '2026-02-12',
        status: 'قيد المعالجة',
        timeline: [
            {
                status: 'تم استقبال الشحنة',
                location: 'مركز توزيع الدمام',
                coordinates: { lat: 26.4124, lng: 50.1971 },
                time: '2026-02-05 09:00'
            },
            {
                status: 'قيد المعالجة',
                location: 'مركز فرز الدمام',
                coordinates: { lat: 26.4200, lng: 50.2000 },
                time: '2026-02-05 11:30'
            },
            {
                status: 'قيد النقل',
                location: 'الطريق السريع إلى الرياض',
                coordinates: { lat: 25.5000, lng: 48.5000 },
                time: 'مباشر'
            }
        ]
    }
};

let liveTimeInterval = null;

// تهيئة نظام التتبع
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();
            }
        });
    }
});

// الدالة الرئيسية للتتبع
function trackShipment() {
    const trackingInput = document.getElementById('tracking-input');
    const trackingNumber = trackingInput.value.trim().toUpperCase();

    if (!trackingNumber) {
        showAlert('يرجى إدخال رقم التتبع', 'error');
        return;
    }

    if (!shipmentDatabase[trackingNumber]) {
        showAlert('لم يتم العثور على رقم التتبع. جرب: XHSNF74652HBL أو DEMO123456789', 'error');
        return;
    }

    const shipment = shipmentDatabase[trackingNumber];
    displayShipmentInfo(trackingNumber, shipment);
    displayTrackingTimeline(shipment);
    showPaymentSection(trackingNumber, shipment.deliveryFee);
    
    // التمرير إلى النتائج
    setTimeout(() => {
        document.getElementById('tracking-results').scrollIntoView({ behavior: 'smooth' });
    }, 300);
}

// عرض معلومات الطرد
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 = `الحالة: ${shipment.status}`;

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

// عرض خط زمني للتتبع
function displayTrackingTimeline(shipment) {
    const timeline = document.getElementById('timeline');
    timeline.innerHTML = '';

    // إيقاف الفاصل الزمني السابق
    if (liveTimeInterval) {
        clearInterval(liveTimeInterval);
    }

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

    // تحديث عرض الوقت الفعلي
    updateLiveTimeDisplay();
}

// إنشاء عنصر خط زمني
function createTimelineItem(item, isLast) {
    const div = document.createElement('div');
    div.className = `timeline-item ${item.time === 'مباشر' ? 'live-item' : 'completed'}`;

    let timeDisplay = item.time;
    if (item.time === 'مباشر') {
        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">
            📍 خط العرض: ${item.coordinates.lat.toFixed(4)}, خط الطول: ${item.coordinates.lng.toFixed(4)}
        </div>
    `;

    return div;
}

// الحصول على التاريخ والوقت الحالي المنسق
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}`;
}

// تحديث عرض الوقت الفعلي
function updateLiveTimeDisplay() {
    const liveTimeElements = document.querySelectorAll('.live-time');
    
    if (liveTimeElements.length > 0) {
        // تحديث فوري
        liveTimeElements.forEach(element => {
            element.textContent = getCurrentDateTime();
        });

        // إيقاف الفاصل الزمني السابق
        if (liveTimeInterval) {
            clearInterval(liveTimeInterval);
        }

        // التحديث كل ثانية
        liveTimeInterval = setInterval(() => {
            const updatedElements = document.querySelectorAll('.live-time');
            updatedElements.forEach(element => {
                element.textContent = getCurrentDateTime();
            });
        }, 1000);
    }
}

// تنسيق التاريخ
function formatDate(dateString) {
    const date = new Date(dateString);
    const options = { year: 'numeric', month: 'long', day: 'numeric' };
    return date.toLocaleDateString('ar-SA', options);
}

// عرض قسم الدفع
function showPaymentSection(trackingNumber, deliveryFee) {
    document.getElementById('tracking-number-payment').value = trackingNumber;
    document.getElementById('delivery-fee').value = `ر.س ${deliveryFee.toFixed(2)}`;
    document.getElementById('payment-amount').textContent = `ر.س ${deliveryFee.toFixed(2)}`;

    // تخزين البيانات للدفع
    window.currentPayment = {
        trackingNumber: trackingNumber,
        deliveryFee: deliveryFee
    };

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

// عرض التنبيهات
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);
}

// تنسيق رقم البطاقة
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);
        });
    }
});