<?php

namespace App\Http\Controllers\Transaction;

use App\Http\Controllers\Controller;
use App\Models\StockMovement;
use App\Models\Product;
use App\Models\Branch;
use Illuminate\Http\Request;

class StockMovementController extends Controller
{
    public function __construct()
    {
        $this->middleware(['permission:stock-movements.index'])->only('index');
    }

    /**
     * Display a listing of stock movements
     */
    public function index(Request $request)
    {
        $title = "stock_movement";
        $products = Product::orderBy('name')->get();
        $branches = Branch::where('is_active', true)->get();

        $query = StockMovement::with(['product', 'branch', 'user', 'reference']);

        // Filter by product
        if ($request->filled('product_id')) {
            $query->where('product_id', $request->product_id);
        }

        // Filter by branch
        if ($request->filled('branch_id')) {
            $query->where('branch_id', $request->branch_id);
        }

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

        // Filter by date range
        if ($request->filled('start_date')) {
            $query->whereDate('created_at', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->whereDate('created_at', '<=', $request->end_date);
        }

        $stockMovements = $query->orderBy('id', 'desc')->paginate(50);

        return view('transaction.stock-movement.index', compact('title', 'stockMovements', 'products', 'branches'));
    }
}
