<?php
namespace App\Controllers;

use Core\Controller;
use App\Models\Mahasiswa;
use App\Models\PPLK;
use App\Models\TokenPPLK;

class PPLKController extends Controller
{
    public function form()
    {
        $nim = $_SESSION['user']['nim'] ?? null;
        if (!$nim) {
            $_SESSION['error'] = 'NIM tidak ditemukan dalam sesi.';
            header('Location: /logout');
            exit;
        }

        $pplkModel      = new PPLK();
        $tokenModel     = new TokenPPLK();
        $mahasiswaModel = new Mahasiswa();

        $dataPplk = $pplkModel->findByNim($nim);

        /* ================= INSERT DATA (TOKEN) ================= */
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['token'])) {

            $token = trim($_POST['token']);

            if (!$tokenModel->isValid($token)) {
                $_SESSION['error'] = 'Token tidak valid.';
                header('Location: /dashboard/mahasiswa-daftarpplk');
                exit;
            }

            $dataMahasiswa = $mahasiswaModel->findByNim($nim);
            if (!$dataMahasiswa) {
                $_SESSION['error'] = 'Data mahasiswa tidak ditemukan.';
                header('Location: /dashboard/mahasiswa-daftarpplk');
                exit;
            }

            if ($dataPplk) {
                $_SESSION['error'] = 'Data PPLK sudah terdaftar.';
                header('Location: /dashboard/mahasiswa-daftarpplk');
                exit;
            }

            $insert = $pplkModel->insertFromMahasiswa($nim, $token);

            if ($insert) {
                $tokenModel->delete($token);
                $_SESSION['success'] = 'Pendaftaran PPLK berhasil.';
            } else {
                $_SESSION['error'] = 'Gagal menyimpan data PPLK.';
            }

            header('Location: /dashboard/mahasiswa-daftarpplk');
            exit;
        }

        /* ================= UPDATE DATA ================= */
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update'])) {

            $update = $pplkModel->updateByNim($nim, $_POST);

            if ($update) {
                $_SESSION['success'] = 'Data PPLK berhasil diperbarui.';
            } else {
                $_SESSION['error'] = 'Tidak ada perubahan data atau update gagal.';
            }

            header('Location: /dashboard/mahasiswa-daftarpplk');
            exit;
        }

        /* ================= LOAD VIEW ================= */
        return $this->view('pplk/daftar', [
            'data' => $dataPplk
        ]);
    }
}
