<?php

namespace App\Http\Controllers\Restaurant;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class OrdersController extends Controller
{
    public function index(Request $request)
    {
        $restaurant = $request->user()->restaurant;
        $query = $restaurant ? $restaurant->deliveries()->latest() : null;

        if (!$query) {
            return view('restaurant.orders.index', [
                'deliveries' => collect(),
                'filters' => $request->all(),
                'counts' => [
                    'total' => 0,
                    'pending' => 0,
                    'confirmed' => 0,
                    'at_restaurant' => 0,
                    'en_route' => 0,
                    'delivered' => 0,
                ],
            ]);
        }

        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('phone')) {
            $query->where('customer_phone', 'like', '%' . $request->phone . '%');
        }
        if ($request->filled('customer')) {
            $query->where('customer_name', 'like', '%' . $request->customer . '%');
        }

        $counts = [
            'total' => $restaurant->deliveries()->count(),
            'pending' => $restaurant->deliveries()->where('status', 'pending')->count(),
            'confirmed' => $restaurant->deliveries()->where('status', 'confirmed')->count(),
            'at_restaurant' => $restaurant->deliveries()->where('status', 'at_restaurant')->count(),
            'en_route' => $restaurant->deliveries()->where('status', 'en_route')->count(),
            'delivered' => $restaurant->deliveries()->where('status', 'delivered')->count(),
        ];

        return view('restaurant.orders.index', [
            'deliveries' => $query->get(),
            'filters' => $request->all(),
            'counts' => $counts,
        ]);
    }
}
