<?php

namespace App\Http\Controllers;

use App\Models\Material;
use App\Models\StockMovement;
use Illuminate\Http\Request;
use Carbon\Carbon;

class MaterialUsageController extends Controller
{
    public function index(Request $request)
    {
        if ($request->filled('date_range')) {
            $dateRange = trim((string) $request->date_range);

            if (str_contains($dateRange, ' to ')) {
                [$start, $end] = explode(' to ', $dateRange, 2);
                $startDate = Carbon::parse(trim($start))->startOfDay();
                $endDate = Carbon::parse(trim($end))->endOfDay();
            } else {
                $startDate = Carbon::parse($dateRange)->startOfDay();
                $endDate = Carbon::parse($dateRange)->endOfDay();
            }
        } else {
            $startDate = Carbon::now()->startOfMonth();
            $endDate = Carbon::now()->endOfDay();
        }

        $query = StockMovement::with(['material', 'user'])
            ->stockOut()
            ->whereBetween('created_at', [$startDate, $endDate]);

        if ($request->filled('material')) {
            $query->where('material_id', $request->material);
        }

        $movements = $query->latest()->paginate(20)->withQueryString();
        $materials = Material::orderBy('name')->get();

        $totalUsage = StockMovement::stockOut()
            ->whereBetween('created_at', [$startDate, $endDate])
            ->when($request->filled('material'), fn ($q) => $q->where('material_id', $request->material))
            ->sum('quantity');

        return view('pages.stock.usage.index', [
            'title' => 'Data Penggunaan Bahan',
            'movements' => $movements,
            'materials' => $materials,
            'totalUsage' => $totalUsage,
            'startDate' => $startDate->format('Y-m-d'),
            'endDate' => $endDate->format('Y-m-d'),
        ]);
    }
}