<?php

// Public, no-login order tracking page — customer scans the QR code on their receipt/label
class TrackController extends Controller
{
    public function show(): void
    {
        $orderNumber = trim($this->input('order', ''));
        $order = null;

        if ($orderNumber !== '') {
            $orderModel = new Order();
            $db = Database::getConnection();
            $stmt = $db->prepare("SELECT id FROM orders WHERE order_number = :num LIMIT 1");
            $stmt->execute(['num' => $orderNumber]);
            $row = $stmt->fetch();
            if ($row) {
                $order = $orderModel->findWithDetails((int) $row['id']);
            }
        }

        $this->view('track.show', [
            'pageTitle'   => 'Track Your Order',
            'orderNumber' => $orderNumber,
            'order'       => $order,
        ], null); // null layout = standalone page, no admin sidebar
    }

    // Polled via AJAX by the tracking page every few seconds for live updates without a full reload.
    public function status(): void
    {
        $orderNumber = trim($this->input('order', ''));
        if ($orderNumber === '') {
            $this->json(['success' => false], 404);
            return;
        }

        $orderModel = new Order();
        $db = Database::getConnection();
        $stmt = $db->prepare("SELECT id FROM orders WHERE order_number = :num LIMIT 1");
        $stmt->execute(['num' => $orderNumber]);
        $row = $stmt->fetch();
        if (!$row) {
            $this->json(['success' => false], 404);
            return;
        }

        $order = $orderModel->findWithDetails((int) $row['id']);
        $flow = ['PENDING', 'CONFIRMED', 'PREPARING', 'READY', 'OUT_FOR_DELIVERY', 'COMPLETED'];
        $currentIndex = array_search($order['status'], $flow, true);

        $history = [];
        foreach ($order['history'] as $h) {
            $history[$h['status']] = date('d M, h:i A', strtotime($h['changed_at']));
        }

        $this->json([
            'success'       => true,
            'status'        => $order['status'],
            'current_index' => $currentIndex,
            'history'       => $history,
            'rider_name'    => $order['delivery']['rider_name'] ?? null,
            'updated_at'    => date('h:i:s A'),
        ]);
    }
}
