<?php

namespace App\Controllers\Panel\Ujian;

use App\Controllers\Panel\BC;
use App\Models\Panel\Ujian\Jadwal;
use CodeIgniter\API\ResponseTrait;

class Overview extends BC
{
    use ResponseTrait;
    private $jadwalModel;
    public function __construct()
    {
        parent::__construct();
        $this->jadwalModel = new Jadwal();
    }
    public function index()
    {
        $data['page_title'] = "Overview";
        return view('Panel/Ujian/Overview/index', $data);
    }
    public function data()
    {
        $opt = [];
        if (!user()->hasRole('admin')) {
            $opt['user_id'] = user()->id;
            $opt['pengawas_id'] = user()->id;
        }
        $jadwalData = $this->jadwalModel->getAll($opt);
        $data['passcode_locked_app'] = options('passcode_locked_app');
        $data['ujian_today'] = 0;
        $data['ujian_active'] = 0;
        $data['jawaban'] = $this->jadwalModel->countJawaban();
        $data['ujiansiswa'] = $this->jadwalModel->countUjian();
        foreach ($jadwalData as $key => $value) {
            if (($value['startDateTime'] >= $this->request->getGet('startDate') && $value['startDateTime'] <= $this->request->getGet('endDate')) || ($value['endDateTime'] >= $this->request->getGet('startDate') && $value['endDateTime'] <= $this->request->getGet('endDate'))) {
                $data['ujian_today']++;
            }
            if ($value['status'] == 1) {
                $data['ujian_active']++;
            }
        }
        return $this->respond($data);
    }

    public function changePasscodeApp()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $newPass = random_int(100000, 999999);
        save_options($newPass, 'passcode_locked_app');
        return $this->respond(['passcode_locked_app' => $newPass]);
    }
}

