<?php

namespace App\Http\Controllers;

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

class StockController extends Controller
{
    public function index(Request $request)
    {
        $query = Material::with('category');

        if ($request->filled('category')) {
            $query->where('category_id', $request->category);
        }

        if ($request->filled('search')) {
            $query->where('name', 'like', '%' . $request->search . '%');
        }

        if ($request->filled('status')) {
            if ($request->status === 'custom') {
                $query->where('is_custom', true);
            } elseif ($request->status === 'low') {
                $query->where('is_custom', false)
                    ->where('min_stock', '>', 0)
                    ->where('stock', '>', 0)
                    ->whereColumn('stock', '<=', 'min_stock');
            } elseif ($request->status === 'out') {
                $query->where('is_custom', false)
                    ->where('stock', '<=', 0);
            } elseif ($request->status === 'available') {
                $query->where(function ($q) {
                    $q->where(function ($qq) {
                        $qq->where('is_custom', false)
                            ->where('stock', '>', 0);
                    })->orWhere('is_custom', true);
                });
            }
        }

        $materials = $query->orderBy('name')->paginate(20)->withQueryString();

        $stats = [
            'total_materials' => Material::count(),
            'low_stock' => Material::where('is_custom', false)
                ->where('min_stock', '>', 0)
                ->where('stock', '>', 0)
                ->whereColumn('stock', '<=', 'min_stock')
                ->count(),
            'out_of_stock' => Material::where('is_custom', false)
                ->where('stock', '<=', 0)
                ->count(),
        ];

        return view('pages.stock.index', [
            'title' => 'Data Stok',
            'materials' => $materials,
            'stats' => $stats,
        ]);
    }

    public function movements(Request $request)
    {
        $query = StockMovement::with(['material', 'user']);

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

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

        if ($request->filled('date')) {
            $query->whereDate('created_at', $request->date);
        }

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

        return view('pages.stock.movements', [
            'title' => 'Riwayat Pergerakan Stok',
            'movements' => $movements,
            'materials' => $materials,
        ]);
    }
}
