<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Carbon\Carbon;

class TrackingController extends Controller
{
    /**
     * Show order tracking search form.
     */
    public function index()
    {
        return view('pages.tracking.index', [
            'title' => 'Lacak Pesanan - Posgraf',
        ]);
    }

    /**
     * Search for order(s).
     */
    public function search(Request $request)
    {
        $searchType = $request->input('search_type', 'invoice');
        
        if ($searchType === 'invoice') {
            $request->validate([
                'invoice_numbers' => ['required', 'string'],
            ], [
                'invoice_numbers.required' => 'Nomor invoice harus diisi',
            ]);

            // Parse multiple invoices (one per line)
            $invoiceNumbers = array_filter(
                array_map('trim', explode("\n", $request->invoice_numbers))
            );

            if (empty($invoiceNumbers)) {
                return back()
                    ->withInput()
                    ->with('error', 'Nomor invoice harus diisi');
            }

            // Single invoice - redirect to show
            if (count($invoiceNumbers) === 1) {
                $order = Order::where('invoice_number', $invoiceNumbers[0])->first();
                
                if (!$order) {
                    return back()
                        ->withInput()
                        ->with('error', 'Order dengan nomor invoice tersebut tidak ditemukan.');
                }

                return redirect()->route('tracking.show', $order->invoice_number);
            }

            // Multiple invoices - get all orders and show result list
            $orders = Order::with(['items', 'customer'])
                ->whereIn('invoice_number', $invoiceNumbers)
                ->get();

            if ($orders->isEmpty()) {
                return back()
                    ->withInput()
                    ->with('error', 'Tidak ada order yang ditemukan dengan nomor invoice tersebut.');
            }

            // Store not found invoices
            $foundInvoices = $orders->pluck('invoice_number')->toArray();
            $notFoundInvoices = array_diff($invoiceNumbers, $foundInvoices);

            return view('pages.tracking.results', [
                'title' => 'Status Pesanan - Posgraf',
                'orders' => $orders,
                'notFoundInvoices' => $notFoundInvoices,
            ]);
        } else {
            $request->validate([
                'phone' => ['required', 'string'],
                'order_date' => ['required', 'date'],
            ], [
                'phone.required' => 'Nomor HP harus diisi',
                'order_date.required' => 'Tanggal order harus diisi',
            ]);

            $orderDate = Carbon::parse($request->order_date);

            $orders = Order::with(['items', 'customer'])
                ->where('customer_phone', $request->phone)
                ->whereDate('created_at', $orderDate)
                ->get();

            if ($orders->isEmpty()) {
                return back()
                    ->withInput()
                    ->with('error', 'Order tidak ditemukan. Pastikan nomor HP dan tanggal order sudah benar.');
            }

            // Single order
            if ($orders->count() === 1) {
                return redirect()->route('tracking.show', $orders->first()->invoice_number);
            }

            // Multiple orders
            return view('pages.tracking.results', [
                'title' => 'Status Pesanan - Posgraf',
                'orders' => $orders,
                'notFoundInvoices' => [],
            ]);
        }
    }

    /**
     * Show single order tracking result.
     */
    public function show(string $invoiceNumber)
    {
        $order = Order::with(['items', 'customer', 'designer', 'operator'])
            ->where('invoice_number', $invoiceNumber)
            ->firstOrFail();

        $timeline = $this->getTimeline($order);

        return view('pages.tracking.result', [
            'title' => 'Status Pesanan - ' . $order->invoice_number,
            'order' => $order,
            'timeline' => $timeline,
        ]);
    }

    /**
     * Get production timeline for order.
     */
    private function getTimeline(Order $order): array
    {
        $steps = [
            [
                'status' => 'pending',
                'label' => 'Order Diterima',
                'description' => 'Pesanan Anda telah diterima',
                'completed' => true,
                'date' => $order->created_at,
            ],
            [
                'status' => 'proses_cetak',
                'label' => 'Proses Cetak',
                'description' => 'Sedang dalam proses cetak',
                'completed' => in_array($order->production_status, ['proses_cetak', 'finishing', 'selesai']),
                'date' => $order->started_at,
            ],
            [
                'status' => 'finishing',
                'label' => 'Finishing',
                'description' => 'Tahap finishing',
                'completed' => in_array($order->production_status, ['finishing', 'selesai']),
                'date' => null,
            ],
            [
                'status' => 'selesai',
                'label' => 'Selesai',
                'description' => 'Siap diambil',
                'completed' => $order->production_status === 'selesai',
                'date' => $order->finished_at,
            ],
            [
                'status' => 'picked_up',
                'label' => 'Diambil',
                'description' => 'Pesanan sudah diambil',
                'completed' => $order->pickup_status === 'picked_up',
                'date' => $order->picked_up_at,
            ],
        ];

        $currentIndex = 0;
        foreach ($steps as $index => $step) {
            if ($step['completed']) {
                $currentIndex = $index;
            }
        }
        $steps[$currentIndex]['current'] = true;

        return $steps;
    }
}
