<?php

namespace App\Http\Controllers\Inventory;

use App\Http\Controllers\Controller;
use App\Models\InventoryItems;
use App\Models\StockMovements;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class StockMovementController extends Controller
{
    public function index(Request $request)
    {
        $user = Auth::user();

        $items = InventoryItems::where('clinic_id', $user->clinic_id)
            ->orderBy('name')
            ->get(['id', 'name']);

        $query = StockMovements::with('inventoryItem')
            ->whereHas('inventoryItem', function ($q) use ($user) {
                $q->where('clinic_id', $user->clinic_id);
            })
            ->orderByDesc('created_at');

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

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

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

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

        $movements = $query->paginate(30);

        return view('admin.inventory.movements.index', compact(
            'items',
            'movements'
        ));
    }
}
