<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Home extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('HasilTKA_model');
        $this->load->model('Token_model');
    }

    public function index()
    {
        $data['title'] = 'Cek Hasil TKA';

        $this->load->view('frontend/templates/header', $data);
        $this->load->view('frontend/home', $data);
        $this->load->view('frontend/templates/footer');
    }

    public function cek_hasil()
    {
        $this->load->library('form_validation');

        $this->form_validation->set_rules('nisn', 'NISN', 'required|trim|exact_length[10]');
        $this->form_validation->set_rules('token', 'Token', 'required|trim|exact_length[5]');

        if ($this->form_validation->run() == FALSE) {
            $data['title'] = 'Cek Hasil TKA';

            $this->load->view('frontend/templates/header', $data);
            $this->load->view('frontend/home', $data);
            $this->load->view('frontend/templates/footer');
        } else {
            $nisn = $this->input->post('nisn');
            $token = strtoupper($this->input->post('token'));

            // Check if token is valid
            if (!$this->Token_model->is_token_valid($token)) {
                $this->session->set_flashdata('error', 'Token tidak valid atau sudah expired!');
                redirect('home');
            }

            // Check if NISN exists
            $result = $this->HasilTKA_model->get_result_by_nisn($nisn);

            if (!$result) {
                $this->session->set_flashdata('error', 'NISN tidak ditemukan!');
                redirect('home');
            }

            // Data valid, show result
            $data['title'] = 'Hasil TKA - ' . $result->NAMA_PESERTA;
            $data['result'] = $result;

            $this->load->view('frontend/templates/header', $data);
            $this->load->view('frontend/hasil', $data);
            $this->load->view('frontend/templates/footer');
        }
    }
}
