<?php
/**
 * Rig N Dig - Mobile API v1 / Order Tracking & Milestones
 */
header('Content-Type: application/json');
require_once '../../../config/config.php';
require_once '../../../includes/functions.php';
require_once '../api_helper.php';

$user = authenticateAPI();

try {
    // Get all active orders (invoices) for the customer
    $orders = Database::fetchAll("
        SELECT 
            id, invoice_number, total, amount_paid, status, 
            milestone, tracking_number, updated_at, created_at 
        FROM invoices 
        WHERE customer_id = ? 
        ORDER BY updated_at DESC
    ", [$user['id']]);

    $milestoneLabels = [
        'processed' => 'Order Processed',
        'sourcing' => 'Global Sourcing',
        'workshop' => 'In Workshop',
        'testing' => 'Technical Testing',
        'dispatched' => 'Dispatched',
        'delivered' => 'Delivered'
    ];

    foreach ($orders as &$order) {
        $order['milestone_label'] = $milestoneLabels[$order['milestone']] ?? 'Processing';
        
        // Progress percentage for a progress bar
        $progress = [
            'processed' => 15,
            'sourcing' => 35,
            'workshop' => 55,
            'testing' => 75,
            'dispatched' => 90,
            'delivered' => 100
        ];
        $order['progress_percent'] = $progress[$order['milestone']] ?? 10;
        
        // Fetch specific certificates linked to this order
        $certs = Database::fetchAll("SELECT id, title, cert_type, serial_number, file_path FROM certificates WHERE invoice_id = ?", [$order['id']]);
        foreach ($certs as &$c) {
            $c['file_url'] = SITE_URL . '/uploads/' . $c['file_path'];
        }
        $order['certificates'] = $certs;
    }

    apiResponse(true, 'Active orders loaded', $orders);
} catch (Exception $e) {
    apiResponse(false, 'Failed to load tracking data');
}
