<?php
// includes/steadfast_tracking.php
// Full Steadfast Courier Integration

function callSteadfastAPI($endpoint, $method = 'GET', $data = null) {
    $curl = curl_init();
    $url = STEADFAST_BASE_URL . $endpoint;
    
    $headers = [
        'Api-Key: ' . STEADFAST_API_KEY,
        'Secret-Key: ' . STEADFAST_SECRET_KEY,
        'Content-Type: application/json'
    ];
    
    $options = [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => false
    ];
    
    if ($method == 'POST') {
        $options[CURLOPT_POST] = true;
        if ($data) {
            $options[CURLOPT_POSTFIELDS] = json_encode($data);
        }
    }
    
    curl_setopt_array($curl, $options);
    $response = curl_exec($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $error = curl_error($curl);
    curl_close($curl);
    
    return [
        'success' => ($http_code == 200 || $http_code == 201),
        'http_code' => $http_code,
        'data' => json_decode($response, true),
        'raw' => $response,
        'error' => $error
    ];
}

// Create shipment in Steadfast
function createSteadfastShipment($order_id) {
    global $conn;
    
    $stmt = $conn->prepare("SELECT * FROM orders WHERE id = ?");
    $stmt->bind_param("i", $order_id);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    
    if (!$order) {
        return ['success' => false, 'error' => 'Order not found'];
    }
    
    // Clean phone number (remove spaces, dashes, ensure 11 digits)
    $phone = preg_replace('/[^0-9]/', '', $order['customer_phone']);
    if (strlen($phone) == 10) $phone = '0' . $phone;
    if (strlen($phone) == 11 && substr($phone, 0, 2) == '01') {
        $phone = '88' . $phone;
    }
    
    $shipment_data = [
        'invoice' => $order['order_number'],
        'recipient_name' => $order['customer_name'],
        'recipient_phone' => $phone,
        'recipient_address' => $order['customer_address'] ?: 'Dhaka, Bangladesh',
        'cod_amount' => 0, // Free delivery
        'note' => 'Homeopathy Medicine - Order #' . $order['order_number'],
        'weight' => 0.5
    ];
    
    logCourierAction($order_id, $order['order_number'], 'create_shipment_request', json_encode($shipment_data));
    
    $result = callSteadfastAPI('/create_order', 'POST', $shipment_data);
    
    logCourierAction($order_id, $order['order_number'], 'create_shipment_response', json_encode($result));
    
    if ($result['success'] && isset($result['data']['data']['tracking_code'])) {
        $tracking_code = $result['data']['data']['tracking_code'];
        $tracking_link = "https://steadfast.com.bd/tl/" . $tracking_code;
        
        $update = $conn->prepare("UPDATE orders SET 
            tracking_id = ?,
            steadfast_tracking_code = ?,
            steadfast_tracking_link = ?,
            courier_status = 'pending',
            status = 'shipped',
            shipped_at = NOW(),
            courier = 'steadfast'
            WHERE id = ?");
        $update->bind_param("sssi", $tracking_code, $tracking_code, $tracking_link, $order_id);
        $update->execute();
        
        return [
            'success' => true,
            'tracking_code' => $tracking_code,
            'tracking_link' => $tracking_link,
            'message' => 'Shipment created successfully'
        ];
    }
    
    return [
        'success' => false,
        'error' => $result['data']['message'] ?? 'Failed to create shipment',
        'api_response' => $result
    ];
}

// Get real tracking status from Steadfast
function getSteadfastTrackingStatus($tracking_code) {
    if (empty($tracking_code)) {
        return ['success' => false, 'error' => 'No tracking code provided'];
    }
    
    // Remove STF- prefix if present (manual tracking)
    $tracking_code = str_replace('STF-', '', $tracking_code);
    
    $result = callSteadfastAPI('/tracking_by_code/' . urlencode($tracking_code), 'GET');
    
    if ($result['success'] && isset($result['data']['data'])) {
        $tracking_data = $result['data']['data'];
        
        $timeline = [];
        if (isset($tracking_data['tracking']) && is_array($tracking_data['tracking'])) {
            foreach ($tracking_data['tracking'] as $event) {
                $timeline[] = [
                    'date' => $event['date'] ?? '',
                    'time' => $event['time'] ?? '',
                    'description' => $event['description'] ?? ''
                ];
            }
        }
        
        // Map Steadfast status
        $current_status = $tracking_data['current_status'] ?? 'pending';
        $status_map = [
            'pending' => 'pending',
            'approved' => 'approved',
            'processing' => 'processing',
            'delivered' => 'delivered',
            'cancelled' => 'cancelled'
        ];
        
        return [
            'success' => true,
            'tracking_code' => $tracking_code,
            'status' => $status_map[$current_status] ?? 'pending',
            'current_status_text' => $current_status,
            'timeline' => $timeline,
            'recipient_name' => $tracking_data['recipient']['name'] ?? 'N/A',
            'recipient_address' => $tracking_data['recipient']['address'] ?? 'N/A',
            'assigned_rider' => $tracking_data['assigned_rider'] ?? null,
            'last_update' => $tracking_data['last_update'] ?? null,
            'raw' => $tracking_data
        ];
    }
    
    return [
        'success' => false,
        'error' => $result['data']['message'] ?? 'Unable to fetch tracking details',
        'raw_response' => $result['raw']
    ];
}

// Bulk sync all tracking statuses
function syncAllTrackingStatuses() {
    global $conn;
    
    $orders = $conn->query("SELECT id, tracking_id, status FROM orders WHERE tracking_id IS NOT NULL AND tracking_id != '' AND tracking_id NOT LIKE 'STF-%' AND status NOT IN ('delivered', 'cancelled')");
    
    $updated = 0;
    $failed = 0;
    
    while ($order = $orders->fetch_assoc()) {
        $tracking = getSteadfastTrackingStatus($order['tracking_id']);
        if ($tracking['success']) {
            $new_status = $tracking['status'];
            $update = $conn->prepare("UPDATE orders SET 
                courier_status = ?,
                tracking_last_sync = NOW()
                WHERE id = ?");
            $update->bind_param("si", $new_status, $order['id']);
            $update->execute();
            
            // Auto-update order status if delivered
            if ($new_status == 'delivered' && $order['status'] != 'delivered') {
                $conn->query("UPDATE orders SET status='delivered', delivered_at=NOW() WHERE id={$order['id']}");
            }
            $updated++;
        } else {
            $failed++;
        }
    }
    
    return ['success' => true, 'updated_count' => $updated, 'failed_count' => $failed];
}

// Log courier actions
function logCourierAction($order_id, $order_number, $action, $data) {
    global $conn;
    $stmt = $conn->prepare("INSERT INTO courier_logs (order_id, order_number, action, request_data, status, created_at) VALUES (?, ?, ?, ?, 'logged', NOW())");
    $stmt->bind_param("isss", $order_id, $order_number, $action, $data);
    $stmt->execute();
}

// Display tracking timeline HTML
function displayTrackingTimeline($order) {
    if (empty($order['tracking_id'])) {
        return '<div class="alert alert-info">📦 Tracking information will be available once your order is shipped.</div>';
    }
    
    // Check if it's a real Steadfast tracking or manual
    $is_real_tracking = !preg_match('/^STF-[A-F0-9]+$/', $order['tracking_id']);
    
    if (!$is_real_tracking && empty($order['steadfast_tracking_code'])) {
        return '<div class="alert alert-warning">
            <i class="fas fa-truck"></i> Your order has been shipped with tracking #' . htmlspecialchars($order['tracking_id']) . '.<br>
            <small>Real-time tracking will appear once the courier updates the status.</small>
        </div>';
    }
    
    $tracking_code = $order['steadfast_tracking_code'] ?: $order['tracking_id'];
    $tracking = getSteadfastTrackingStatus($tracking_code);
    
    if (!$tracking['success']) {
        return '<div class="alert alert-secondary">
            <i class="fas fa-clock"></i> Tracking status is being updated.
            <a href="https://steadfast.com.bd/tl/' . urlencode($tracking_code) . '" target="_blank" class="alert-link">
                Check on Steadfast website →
            </a>
        </div>';
    }
    
    $html = '<div class="tracking-card" style="background:#fff;border-radius:15px;padding:20px;margin:15px 0;box-shadow:0 2px 10px rgba(0,0,0,.05);">';
    $html .= '<div class="d-flex justify-content-between align-items-center mb-3">';
    $html .= '<h6><i class="fas fa-shipping-fast text-success"></i> Tracking #: ' . htmlspecialchars($tracking['tracking_code']) . '</h6>';
    
    // Status badge
    $badge_class = 'secondary';
    $badge_icon = '⏳';
    if ($tracking['status'] == 'delivered') {
        $badge_class = 'success';
        $badge_icon = '✅';
    } elseif ($tracking['status'] == 'shipped' || $tracking['status'] == 'processing') {
        $badge_class = 'primary';
        $badge_icon = '📦';
    } elseif ($tracking['status'] == 'cancelled') {
        $badge_class = 'danger';
        $badge_icon = '❌';
    }
    
    $html .= '<span class="badge bg-' . $badge_class . '">' . $badge_icon . ' ' . ucfirst($tracking['status']) . '</span>';
    $html .= '</div>';
    
    // Timeline
    if (!empty($tracking['timeline'])) {
        $html .= '<div class="timeline" style="position:relative;padding-left:30px;">';
        foreach (array_reverse($tracking['timeline']) as $event) {
            $html .= '<div style="position:relative;margin-bottom:20px;">';
            $html .= '<div style="position:absolute;left:-20px;top:5px;width:12px;height:12px;border-radius:50%;background:#2d6a4f;"></div>';
            $html .= '<div style="position:absolute;left:-14px;top:17px;width:2px;height:calc(100% + 3px);background:#dee2e6;"></div>';
            $html .= '<div class="text-muted small">' . date('d M Y, h:i A', strtotime($event['date'] . ' ' . $event['time'])) . '</div>';
            $html .= '<div>' . htmlspecialchars($event['description']) . '</div>';
            $html .= '</div>';
        }
        $html .= '</div>';
    }
    
    // Rider info
    if (!empty($tracking['assigned_rider'])) {
        $rider = $tracking['assigned_rider'];
        $html .= '<div class="alert alert-light mt-3">';
        $html .= '<i class="fas fa-motorcycle"></i> <strong>Rider:</strong> ' . htmlspecialchars($rider['name'] ?? 'N/A');
        if (!empty($rider['phone'])) {
            $html .= ' | 📞 <a href="tel:' . $rider['phone'] . '">' . $rider['phone'] . '</a>';
        }
        $html .= '</div>';
    }
    
    $html .= '<div class="text-center mt-3">';
    $html .= '<button onclick="refreshTracking()" class="btn btn-sm btn-outline-primary">';
    $html .= '<i class="fas fa-sync-alt"></i> Refresh Status</button>';
    $html .= '</div>';
    $html .= '</div>';
    
    return $html;
}

// Get Steadfast balance
function getSteadfastBalance() {
    $result = callSteadfastAPI('/balance', 'GET');
    if ($result['success'] && isset($result['data']['data']['balance'])) {
        return $result['data']['data']['balance'];
    }
    return false;
}
?>