<?php

namespace App\Http\Controllers;

use App\Models\Material;
use App\Models\StockMovement;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;

class StockUsageController extends Controller
{
    public function index(Request $request)
    {
        $dateRange = (string) $request->input('date_range', '');
        $perPage = (int) $request->input('per_page', 15);
        $perPage = in_array($perPage, [10, 15, 25, 50, 100], true) ? $perPage : 15;

        if ($dateRange && str_contains($dateRange, ' to ')) {
            [$startDate, $endDate] = explode(' to ', $dateRange);
        } else {
            $startDate = now()->startOfMonth()->format('Y-m-d');
            $endDate = now()->format('Y-m-d');
        }

        $materials = Material::active()->orderBy('name')->get();

        $movement = new StockMovement();
        $table = $movement->getTable();
        $qtyColumn = Schema::hasColumn($table, 'quantity') ? 'quantity' : (Schema::hasColumn($table, 'qty') ? 'qty' : 'quantity');
        $typeColumn = Schema::hasColumn($table, 'type') ? 'type' : (Schema::hasColumn($table, 'movement_type') ? 'movement_type' : null);

        $baseQuery = StockMovement::query()
            ->with([
                'material:id,name,unit',
                'user:id,name',
            ])
            ->when($request->filled('material'), function ($query) use ($request) {
                $query->where('material_id', $request->material);
            })
            ->whereBetween($table . '.created_at', [
                $startDate . ' 00:00:00',
                $endDate . ' 23:59:59',
            ]);

        if ($typeColumn) {
            $baseQuery->whereIn($typeColumn, [
                'usage',
                'consume',
                'out',
                'production',
                'order',
                'order_usage',
            ]);
        }

        $totalUsage = (clone $baseQuery)->sum($qtyColumn);

        $movements = $baseQuery
            ->orderByDesc($table . '.created_at')
            ->paginate($perPage)
            ->withQueryString();

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