<?php
// includes/tracking_fallback.php
// Manual tracking display for when API is unavailable

function displayTrackingFallback($order) {
    if (empty($order['tracking_id'])) {
        return '<div class="alert alert-info">📦 Tracking will be available once your order is shipped.</div>';
    }
    
    $tracking_id = $order['tracking_id'];
    $tracking_link = "https://steadfast.com.bd/tl/" . urlencode($tracking_id);
    
    // Check if it's a manual tracking ID (starts with STF-)
    if (preg_match('/^STF-[A-F0-9]+$/', $tracking_id)) {
        return '
        <div class="alert alert-warning">
            <i class="fas fa-truck"></i> 
            <strong>Order Shipped!</strong><br>
            Tracking Number: <code>' . htmlspecialchars($tracking_id) . '</code><br>
            <small>Real-time tracking will appear once the courier partner updates the status.</small>
            <hr>
            <a href="' . $tracking_link . '" target="_blank" class="btn btn-sm btn-outline-primary">
                <i class="fas fa-external-link-alt"></i> Check on Steadfast Website
            </a>
        </div>';
    }
    
    // For numeric tracking IDs (like 252487159)
    if (is_numeric($tracking_id)) {
        return '
        <div class="alert alert-info">
            <i class="fas fa-shipping-fast"></i>
            <strong>Tracking Information</strong><br>
            Consignment ID: <code>' . htmlspecialchars($tracking_id) . '</code><br>
            <a href="https://steadfast.com.bd/tracking/' . $tracking_id . '" target="_blank">
                Click here to track your shipment →
            </a>
        </div>';
    }
    
    // Default tracking display
    return '
    <div class="alert alert-secondary">
        <i class="fas fa-box"></i>
        <strong>Shipment Information</strong><br>
        Tracking ID: <code>' . htmlspecialchars($tracking_id) . '</code><br>
        <a href="' . $tracking_link . '" target="_blank" class="btn btn-sm btn-link">
            Track your order
        </a>
    </div>';
}

// Function to update order status manually
function updateOrderStatusManually($order_id, $new_status) {
    global $conn;
    $stmt = $conn->prepare("UPDATE orders SET status = ? WHERE id = ?");
    $stmt->bind_param("si", $new_status, $order_id);
    return $stmt->execute();
}

// Function to add real tracking to an order
function addRealTrackingToOrder($order_id, $steadfast_tracking_code) {
    global $conn;
    $tracking_link = "https://steadfast.com.bd/tl/" . $steadfast_tracking_code;
    $stmt = $conn->prepare("UPDATE orders SET 
        tracking_id = ?,
        steadfast_tracking_code = ?,
        steadfast_tracking_link = ?,
        courier = 'steadfast',
        status = 'shipped',
        shipped_at = NOW()
        WHERE id = ?");
    $stmt->bind_param("sssi", $steadfast_tracking_code, $steadfast_tracking_code, $tracking_link, $order_id);
    return $stmt->execute();
}
?>