<?php

namespace App\Http\Controllers;

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

class StockInController extends Controller
{
    public function __construct()
    {
        $this->middleware(\App\Http\Middleware\PermissionMiddleware::class . ':manage materials,manage stock')
            ->only(['create', 'store', 'destroy']);
    }
    public function index(Request $request)
    {
        $query = StockMovement::with(['material', 'user'])
            ->stockIn();

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

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

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

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

    public function create()
    {
        $materials = Material::active()->orderBy('name')->get();

        return view('pages.stock.incoming.create', [
            'title' => 'Tambah Stok Masuk',
            'materials' => $materials,
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'material_id' => ['required', 'exists:materials,id'],
            'quantity' => ['required', 'numeric', 'min:0.01'],
            'unit_price' => ['nullable', 'numeric', 'min:0'],
            'notes' => ['nullable', 'string', 'max:500'],
        ]);

        $material = Material::findOrFail($validated['material_id']);
        $unitPrice = $validated['unit_price'] ?? 0;
        
        $material->addStock(
            $validated['quantity'],
            $unitPrice,
            $validated['notes'] ?? null
        );

        return redirect()->route('stock.incoming.index')
            ->with('success', 'Stok masuk berhasil dicatat.');
    }

    public function destroy(StockMovement $incoming)
    {
        // Hanya bisa hapus stok masuk manual (tanpa reference ke Purchase)
        if ($incoming->reference_type !== null) {
            return back()->with('error', 'Stok masuk dari pembelian hanya bisa dibatalkan via menu Pembelian.');
        }

        if ($incoming->type !== StockMovement::TYPE_IN) {
            return back()->with('error', 'Data ini bukan stok masuk.');
        }

        // Kembalikan stok
        $incoming->material->decrement('stock', $incoming->quantity);
        
        // Hapus record
        $incoming->delete();

        return redirect()->route('stock.incoming.index')
            ->with('success', 'Stok masuk berhasil dibatalkan dan stok dikembalikan.');
    }
}
