<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\AcademicPeriodModel;
use App\Models\AcademicYearModel;

class AcademicPeriod extends BaseController
{
    protected $model;
    protected $yearModel;

    public function __construct()
    {
        $this->model     = new AcademicPeriodModel();
        $this->yearModel = new AcademicYearModel();
    }

    private function checkLogin()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }
        return null;
    }

    public function index()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $data = [
            'title'      => 'Tahun & Periode Akademik',
            'periods'    => $this->model->getAllWithYear(),
            'active'     => $this->model->getActive(),
            'years'      => $this->yearModel->orderBy('name', 'DESC')->findAll(),
            'activeYear' => $this->yearModel->getActive(),
        ];

        return view('academic_period/index', $data);
    }

    public function store()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $rules = [
            'academic_year_id' => 'required|integer',
            'semester'         => 'required|in_list[Ganjil,Genap]',
            'start_date'       => 'required|valid_date',
            'end_date'         => 'required|valid_date',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()
                ->with('errors', $this->validator->getErrors())
                ->withInput();
        }

        // Cek duplikasi
        $exists = $this->model
            ->where('academic_year_id', $this->request->getPost('academic_year_id'))
            ->where('semester', $this->request->getPost('semester'))
            ->where('deleted_at', null)
            ->first();

        if ($exists) {
            return redirect()->back()
                ->with('error', 'Periode ini sudah ada!')
                ->withInput();
        }

        $this->model->insert([
            'academic_year_id' => $this->request->getPost('academic_year_id'),
            'semester'         => $this->request->getPost('semester'),
            'start_date'       => $this->request->getPost('start_date'),
            'end_date'         => $this->request->getPost('end_date'),
            'is_active'        => 0,
        ]);

        return redirect()->to('/academic-period')
            ->with('success', 'Periode akademik berhasil ditambahkan!');
    }

    public function update($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $rules = [
            'start_date' => 'required|valid_date',
            'end_date'   => 'required|valid_date',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()
                ->with('errors', $this->validator->getErrors())
                ->withInput();
        }

        $this->model->update($id, [
            'start_date' => $this->request->getPost('start_date'),
            'end_date'   => $this->request->getPost('end_date'),
        ]);

        return redirect()->to('/academic-period')
            ->with('success', 'Periode akademik berhasil diupdate!');
    }

    public function setActive($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $this->model->setActive($id);

        return redirect()->to('/academic-period')
            ->with('success', 'Periode aktif berhasil diubah!');
    }

    public function delete($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $period = $this->model->find($id);

        if ($period['is_active'] == 1) {
            return redirect()->to('/academic-period')
                ->with('error', 'Periode aktif tidak bisa dihapus!');
        }

        $this->model->delete($id);

        return redirect()->to('/academic-period')
            ->with('success', 'Periode akademik berhasil dihapus!');
    }
}