<?php

namespace App\Http\Controllers;

use App\Models\Semester;
use Illuminate\Http\Request;
use App\Http\Requests\StoreSemesterRequest;
use App\Http\Requests\UpdateSemesterRequest;

class SemesterController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $semesters = Semester::all();
        return view('semesters.index', compact('semesters'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('semesters.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreSemesterRequest $request)
    {
        if ($request->is_active) {
            Semester::where('is_active', true)->update(['is_active' => false]);
        }
        Semester::create($request->validated());
        return redirect()->route('semesters.index')->with('success', 'Semester berhasil ditambahkan');
    }

    /**
     * Display the specified resource.
     */
    public function show(Semester $semester)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Semester $semester)
    {
        return view('semesters.edit', compact('semester'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateSemesterRequest $request, Semester $semester)
    {
        if ($request->is_active) {
            Semester::where('is_active', true)->update(['is_active' => false]);
        }
        $semester->update($request->validated());
        return redirect()->route('semesters.index')->with('success', 'Semester berhasil diupdate');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Semester $semester)
    {
        $semester->delete();
        return redirect()->route('semesters.index')->with('success', 'Semester berhasil dihapus');
    }

    // Tambahkan method untuk mengaktifkan semester
    public function activate(Semester $semester)
    {
        Semester::where('is_active', true)->update(['is_active' => false]);
        $semester->update(['is_active' => true]);
        return redirect()->route('semesters.index')->with('success', 'Semester diaktifkan');
    }
}
