<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Period;
use Illuminate\Http\Request;

class PeriodController extends Controller
{
    public function index() {
        $items = Period::latest()->paginate(10);
        return view('admin.periods.index', compact('items'));
    }

    public function create() {
        return view('admin.periods.create');
    }

    public function store(Request $req) {
        $data = $req->validate([
            'name' => 'required',
            'voting_start' => 'nullable|date',
            'voting_end' => 'nullable|date|after:voting_start',
            'is_active' => 'nullable|boolean'
        ]);
        $data['is_active'] = $req->boolean('is_active');
        Period::create($data);
        return redirect()->route('admin.periods.index')->with('status','Periode dibuat.');
    }

    public function edit(Period $period) {
        return view('admin.periods.edit', compact('period'));
    }

    public function update(Request $req, Period $period) {
        $data = $req->validate([
            'name' => 'required',
            'voting_start' => 'nullable|date',
            'voting_end' => 'nullable|date|after:voting_start',
            'is_active' => 'nullable|boolean'
        ]);
        $data['is_active'] = $req->boolean('is_active');
        $period->update($data);
        return back()->with('status','Periode diupdate.');
    }

    public function destroy(Period $period) {
        $period->delete();
        return back()->with('status','Periode dihapus.');
    }
}
