<?php

namespace App\Http\Controllers;

use App\Models\Jatah;
use Illuminate\Http\Request;

class JatahController extends Controller
{
    public function index(Request $request)
    {
        $search = $request->input('search');
        $status = $request->input('status');

        $query = Jatah::query();

        if ($search) {
            $query->where('tujuan', 'like', "%{$search}%");
        }

        if ($status) {
            $query->where('status', $status);
        }

        $jatahs = $query->orderBy('tujuan', 'asc')->paginate(15)->withQueryString();

        return view('jatah.index', compact('jatahs'));
    }

    public function updateStatus(Request $request, $id)
    {
        $jatah = Jatah::findOrFail($id);

        $request->validate([
            'status' => 'required|in:belum_diambil,diambil',
        ]);

        $status = $request->input('status');
        $jatah->update([
            'status' => $status,
        ]);

        $statusLabel = $status === 'diambil' ? 'SUDAH DIAMBIL' : 'BELUM DIAMBIL';
        return redirect()->back()->with('success', "Jatah untuk {$jatah->tujuan} berhasil diubah ke {$statusLabel}.");
    }
}
