MIF_E31230680/app/Http/Controllers/PeriodeController.php

83 lines
2.6 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\Periode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class PeriodeController extends Controller
{
public function index()
{
$periodes = Periode::latest()->get();
return view('periode.index', compact('periodes'));
}
public function store(Request $request)
{
$request->validate([
'nama_periode' => 'required|string|max:255',
'kuota' => 'required|integer|min:1',
]);
Periode::create([
'nama_periode' => $request->nama_periode,
'kuota' => $request->kuota,
'is_aktif' => false, // Default tidak aktif saat baru dibuat
]);
return redirect()->back()->with('success', 'Periode berhasil ditambahkan!');
}
public function update(Request $request, $id)
{
$request->validate([
'nama_periode' => 'required|string|max:255',
'kuota' => 'required|integer|min:1',
]);
$periode = Periode::findOrFail($id);
$periode->update($request->only('nama_periode', 'kuota'));
return redirect()->back()->with('success', 'Periode berhasil diperbarui!');
}
/**
* Logika Inti: Mengaktifkan satu periode dan mematikan yang lain
*/
public function aktifkan($id)
{
DB::transaction(function () use ($id) {
// Set semua periode jadi tidak aktif
Periode::query()->update(['is_aktif' => false]);
// Set periode terpilih jadi aktif
$periode = Periode::findOrFail($id);
$periode->update(['is_aktif' => true]);
});
return redirect()->back()->with('success', 'Periode ' . Periode::find($id)->nama_periode . ' kini aktif!');
}
public function destroy($id)
{
$periode = Periode::findOrFail($id);
if ($periode->is_aktif) {
return redirect()->back()->with('error', 'Tidak bisa menghapus periode yang sedang aktif!');
}
// ===================================================================
// 2. PAGAR PELINDUNG ARSIP HISTORI
// Cek apakah periode ini sudah punya data riwayat seleksi warga
// ===================================================================
if ($periode->hasilSeleksis()->count() > 0) {
return redirect()->back()->with('error', 'Gagal! Periode ini tidak bisa dihapus karena sudah menyimpan arsip riwayat Hasil Seleksi Bansos. Biarkan saja sebagai histori laporan Desa.');
}
$periode->delete();
return redirect()->back()->with('success', 'Periode berhasil dihapus!');
}
}