<?php

namespace App\Http\Controllers\Courier;

use App\Http\Controllers\Controller;
use App\Models\Delivery;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;

class RecordsController extends Controller
{
    public function index(Request $request)
    {
        $courier = $request->user()->courier;

        $query = Delivery::query();

        if ($courier) {
            $query->where('courier_id', $courier->id);
        } else {
            $query->whereRaw('1 = 0');
        }

        $query->where('status', Delivery::STATUS_DELIVERED);
        $query->where('created_at', '>=', now()->subDays(90));

        $selectedDay = $request->string('day')->toString();
        if ($selectedDay !== '') {
            $query->whereDate('created_at', $selectedDay);
        }

        $deliveries = $query->latest()->paginate(20)->withQueryString();

        $days = $courier
            ? Delivery::query()
                ->where('courier_id', $courier->id)
                ->where('status', Delivery::STATUS_DELIVERED)
                ->where('created_at', '>=', now()->subDays(90))
                ->select(DB::raw('DATE(created_at) as day'), DB::raw('COUNT(*) as total'))
                ->groupBy(DB::raw('DATE(created_at)'))
                ->orderBy(DB::raw('DATE(created_at)'), 'desc')
                ->get()
            : collect();

        return view('courier.records', [
            'courier' => $courier,
            'deliveries' => $deliveries,
            'days' => $days,
            'selectedDay' => $selectedDay,
        ]);
    }
}
