<?php

namespace App\Http\Controllers;

use App\Models\Order;

class TrackingController extends Controller
{
    /**
     * Display the customer tracking main page.
     */
    public function index()
    {
        return view('customer.tracking');
    }

    /**
     * Display the public "Tentang OKE Laundry" page.
     */
    public function about()
    {
        $mitra = \App\Models\Setting::mitra();
        return view('customer.about', compact('mitra'));
    }

    /**
     * Track an order by receipt number and return JSON data.
     */
    public function track($receipt_number)
    {
        // Sanitize input
        $receipt_number = trim($receipt_number);

        if (empty($receipt_number) || strlen($receipt_number) > 255) {
            return response()->json(['error' => 'Nomor resi tidak valid'], 400);
        }

        $order = Order::with(['customer', 'status', 'courier', 'statusHistories'])
            ->where('receipt_number', $receipt_number)
            ->first();

        if (!$order) {
            return response()->json(['error' => 'Pesanan tidak ditemukan'], 404);
        }

        return response()->json([
            'id' => $order->id,
            'nomor' => $order->receipt_number,
            'nama' => $order->customer ? $order->customer->name : 'Unknown',
            'customer_id' => $order->customer_id,
            'status' => $order->status ? $order->status->status_name : 'jemput',
            'status_id' => $order->status_id,
            'note' => $order->note,
            'jarak' => $order->distance,
            'cost' => $order->shipping_cost,
            'date' => $order->order_date
                ? $order->order_date->format('d/m/Y, H.i.s')
                : $order->created_at->format('d/m/Y, H.i.s'),
            'processStage' => $order->process_stage,
            'history' => $order->statusHistories->map(function ($h) {
                return [
                    'status' => $h->status_name,
                    'stage' => $h->process_stage,
                    'time' => $h->created_at->format('d/m/Y, H.i'),
                ];
            }),
            'courier_name' => $order->courier ? $order->courier->name : null,
            'courier_phone' => $order->courier ? $order->courier->phone : null,
            'customer' => $order->customer ? [
                'name' => $order->customer->name,
                'pos' => ($order->customer->latitude && $order->customer->longitude) ? [
                    'lat' => $order->customer->latitude,
                    'lng' => $order->customer->longitude,
                ] : null,
            ] : null,
        ]);
    }
}
