<?php

namespace App\Http\Controllers;

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

class TraceOrderController extends Controller
{
    public function index(Request $request)
    {
        $orders = collect();

        if ($request->filled('search') || $request->filled('date')) {

            $query = Order::with('items');

            if ($request->filled('search')) {

                $search = $request->search;

                $query->where(function ($q) use ($search) {

                    $q->where('invoice_number', 'like', "%{$search}%")
                      ->orWhere('customer_name', 'like', "%{$search}%");

                });

            }

            if ($request->filled('date')) {

                $query->whereDate('created_at', $request->date);

            }

            $orders = $query->latest()->get();

        }

        return view('trace-order.index', compact('orders'));
    }
}
