<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\OrderStatusService;

class SearchController extends Controller
{
    public function __construct(private OrderStatusService $service)
    {
    }

    public function index(Request $request)
    {
        // Landing page with two forms
        return view('search.index');
    }

    public function showOrder(string $orderNo)
    {
        $orderNo = trim($orderNo);
        if ($orderNo === '') {
            return redirect()->route('home')->with('error', 'Please enter a valid Order No.');
        }

        $counts = $this->service->getOrderStageCounts($orderNo);
        $name = $this->service->getCustomerNameByOrder($orderNo);
        $balance = $this->service->getBalanceByOrder($orderNo); // Get the balance

        if (empty($counts)) {
            $notFound = is_null($name); // use customer name existence as proxy for order existence

            return view('search.order', [
                'orderNo' => $orderNo,
                'counts' => $counts,
                'notFound' => $notFound,
                'name' => $name,
                'balance' => $balance,
            ]);

        }

        return view('search.order', [
            'orderNo' => $orderNo,
            'counts' => $counts,
            'notFound' => false,
            'name' => $name,
            'balance' => $balance, // Pass balance to view
        ]);
    }


    public function searchPhone(Request $request)
    {
        $validated = $request->validate([
            'phone' => ['required', 'string', 'max:30'],
        ]);

        $orders = $this->service->getOrdersByPhone($validated['phone']);

        return view('search.phone', [
            'phone' => $validated['phone'],
            'orders' => $orders,
        ]);
    }
}
