<?php

namespace App\Http\Controllers;

use App\Models\ItemRequest;
use App\Models\RequestItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class ItemRequestController extends Controller
{
    public function index()
    {
        $user = Auth::user();

        $query = ItemRequest::with(['user', 'item', 'approver']);

        if ($user->role !== 'sekretariat') {
            $query->where('user_id', $user->id);
        }

        $requests = $query->latest()->paginate(10);

        return view('item-requests.index', compact('requests'));
    }

    public function create()
    {
        $items = RequestItem::where('is_active', true)
            ->orderBy('display_name')
            ->get();

        return view('item-requests.create', compact('items'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'request_item_id' => 'required|exists:request_items,id',
            'quantity' => 'required|numeric|min:0.01',
            'realization_date' => 'required|date|after_or_equal:today',
            'purpose' => 'required|string|max:1000',
        ]);

        $item = RequestItem::findOrFail($validated['request_item_id']);
        $quantity = (float) $validated['quantity'];
        $stock = (float) $item->stock;

        if ($stock <= 0) {
            throw ValidationException::withMessages([
                'request_item_id' => 'Barang yang dipilih sedang habis dan belum bisa diajukan.',
            ]);
        }

        if ($item->unit !== 'meter' && floor($quantity) != $quantity) {
            throw ValidationException::withMessages([
                'quantity' => 'Untuk barang dengan satuan pcs atau unit, jumlah harus angka bulat.',
            ]);
        }

        if ($quantity > $stock) {
            throw ValidationException::withMessages([
                'quantity' => 'Jumlah permintaan melebihi stok tersedia. Maksimal: ' . rtrim(rtrim(number_format($stock, 2, '.', ''), '0'), '.') . ' ' . $item->unit . '.',
            ]);
        }

        ItemRequest::create([
            'user_id' => Auth::id(),
            'request_item_id' => $item->id,
            'quantity' => $validated['quantity'],
            'unit_snapshot' => $item->unit,
            'item_name_snapshot' => $item->display_name,
            'image_url_snapshot' => $item->getRawOriginal('image_url'),
            'request_date' => now()->toDateString(),
            'realization_date' => $validated['realization_date'],
            'purpose' => $validated['purpose'],
            'status' => 'pending',
        ]);

        return redirect()
            ->route('item-requests.index')
            ->with('success', 'Permintaan berhasil dikirim dan telah diteruskan ke pihak sekretariat untuk diproses.');
    }
}
