<?php

namespace App\Http\Controllers;

use App\Models\ItemRequest;
use App\Models\RequestItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
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);
        $stockItems = RequestItem::where('is_active', true)
            ->orderBy('display_name')
            ->get();

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

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

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

    public function showItem(RequestItem $requestItem)
    {
        abort_unless($requestItem->is_active, 404);

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'items' => 'required|array|min:1',
            'items.*.request_item_id' => 'required|distinct|exists:request_items,id',
            'items.*.quantity' => 'required|numeric|min:0.01',
            'letter_file' => 'required|file|mimes:pdf|max:2048',
            'realization_date' => 'required|date|after_or_equal:today',
            'purpose' => 'required|string|max:1000',
        ], [
            'items.required' => 'Tambahkan minimal satu barang ke daftar permintaan.',
            'items.min' => 'Tambahkan minimal satu barang ke daftar permintaan.',
            'items.*.request_item_id.distinct' => 'Setiap barang hanya boleh ditambahkan satu kali dalam satu permintaan.',
            'letter_file.required' => 'Surat pengajuan wajib diupload.',
            'letter_file.mimes' => 'Surat pengajuan harus berformat PDF.',
            'letter_file.max' => 'Ukuran surat pengajuan tidak boleh lebih dari 2MB.',
        ]);

        $requestDate = now()->toDateString();
        $itemMap = RequestItem::whereIn('id', collect($validated['items'])->pluck('request_item_id'))
            ->get()
            ->keyBy('id');
        $preparedItems = [];

        foreach ($validated['items'] as $index => $row) {
            $item = $itemMap->get((int) $row['request_item_id']);

            if (!$item) {
                throw ValidationException::withMessages([
                    "items.$index.request_item_id" => 'Barang permintaan tidak ditemukan.',
                ]);
            }

            $quantity = (float) $row['quantity'];
            $stock = (float) $item->stock;

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

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

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

            $preparedItems[] = [
                'request_item_id' => $item->id,
                'quantity' => $row['quantity'],
                'unit_snapshot' => $item->unit,
                'item_name_snapshot' => $item->display_name,
                'image_url_snapshot' => $item->getRawOriginal('image_url'),
            ];
        }

        $letterPath = $request->file('letter_file')->store('item-request-letters', 'public');

        try {
            DB::transaction(function () use ($preparedItems, $validated, $requestDate, $letterPath) {
                foreach ($preparedItems as $itemData) {
                    ItemRequest::create([
                        'user_id' => Auth::id(),
                        'request_item_id' => $itemData['request_item_id'],
                        'quantity' => $itemData['quantity'],
                        'unit_snapshot' => $itemData['unit_snapshot'],
                        'item_name_snapshot' => $itemData['item_name_snapshot'],
                        'image_url_snapshot' => $itemData['image_url_snapshot'],
                        'letter_file_path' => $letterPath,
                        'request_date' => $requestDate,
                        'realization_date' => $validated['realization_date'],
                        'purpose' => $validated['purpose'],
                        'status' => 'pending',
                    ]);
                }
            });
        } catch (\Throwable $e) {
            Storage::disk('public')->delete($letterPath);
            throw $e;
        }

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