<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\UjianModel;
use Ramsey\Uuid\Uuid;

class UjianController extends BaseController
{
    protected $ujianModel;
    protected $validation;

    public function __construct()
    {
        $this->ujianModel = new UjianModel();
        $this->validation = \Config\Services::validation();
        $this->db = \Config\Database::connect(); // ✅ Tambahkan baris ini
    }

    public function index()
    {
        helper('auth'); // jika pakai helper session

        $setting        = $this->appSetting();
        $userId         = user_id();
        $role           = user_role();

        $tingkatModel   = new \App\Models\TingkatModel();
        $kelasModel     = new \App\Models\KelasModel();
        $jurusanModel   = new \App\Models\JurusanModel();
        $agamaModel     = new \App\Models\AgamaModel();
        $guruModel      = new \App\Models\UserModel();
        $bankSoalModel  = new \App\Models\BankSoalModel();

        // Ambil data guru dan bank soal berdasarkan role
        if ($role === 'admin') {
            $guruList = $guruModel->where('roles', 'guru')->findAll();
            $bankList = $bankSoalModel->findAll();
        } else {
            $guruList = $guruModel->where(['id' => $userId, 'roles' => 'guru'])->findAll();
            $bankList = $bankSoalModel->where('created_by', $userId)->findAll();
        }

        $data = [
            'title'     => 'Manajemen Ujian',
            'setting'   => $setting,
            'gurus'     => $guruList,
            'banks'     => $bankList,
            'tingkat'   => $tingkatModel->where('is_active', 1)->findAll(),
            'kelas'     => $kelasModel->where('is_active', 1)->findAll(),
            'jurusan'   => $jurusanModel->where('is_active', 1)->findAll(),
            'agama'     => $agamaModel->where('is_active', 1)->findAll(),
        ];

        return view('Panel/Ujian/ujian_view', $data);
    }



    public function list()
    {

        if (!$this->request->isAJAX()) {
            return $this->response->setStatusCode(403)->setJSON([
                'status'  => false,
                'message' => 'Hanya bisa diakses via AJAX.'
            ]);
        }

        if (!is_logged_in()) {
            return $this->response->setStatusCode(401)->setJSON([
                'status'  => false,
                'message' => 'Silakan login terlebih dahulu.'
            ]);
        }

        $data = has_role('admin')
            ? $this->ujianModel->getAllUjian()
            : $this->ujianModel->getAllUjian(user_id());

        return $this->response->setJSON([
            'status' => true,
            'data'   => $data
        ]);
    }


    public function create()
    {
        if ($this->request->isAJAX()) {
            $rules = [
                'bank_soal_id'   => 'required',
                'nama_ujian'     => 'required|min_length[3]',
                'kode_ujian'     => 'required',
                'waktu_mulai'    => 'required|valid_date',
                'waktu_selesai'  => 'required|valid_date',
            ];

            if (!$this->validate($rules)) {
                return $this->response->setJSON([
                    'status' => false,
                    'message' => $this->validation->getErrors()
                ]);
            }

            $data = [
                'id'                  => Uuid::uuid4()->toString(),
                'bank_soal_id'        => $this->request->getPost('bank_soal_id'),
                'nama_ujian'          => $this->request->getPost('nama_ujian'),
                'deskripsi'           => $this->request->getPost('deskripsi'),
                'kode_ujian'          => $this->request->getPost('kode_ujian'),
                'token'               => $this->request->getPost('token'),
                'acak_soal'           => (int)$this->request->getPost('acak_soal'),
                'acak_opsi'           => (int)$this->request->getPost('acak_opsi'),
                'pakai_token'         => (int)$this->request->getPost('pakai_token'),
                'durasi_ujian'        => (int)$this->request->getPost('durasi_ujian'),
                'minimal_durasi'      => (int)$this->request->getPost('minimal_durasi'),
                'tampil_nilai'        => (int)$this->request->getPost('tampil_nilai'),
                'tampil_pembahasan'   => (int)$this->request->getPost('tampil_pembahasan'),
                'pakai_webcam'        => (int)$this->request->getPost('pakai_webcam'),
                'perangkat_terkunci'  => (int)$this->request->getPost('perangkat_terkunci'),
                'single_login'        => (int)$this->request->getPost('single_login'),
                'created_by'          => $this->request->getPost('created_by'),
                'waktu_mulai'         => $this->request->getPost('waktu_mulai'),
                'waktu_selesai'       => $this->request->getPost('waktu_selesai'),
                'created_at'          => date('Y-m-d H:i:s')
            ];

            $this->ujianModel->insert($data);

            return $this->response->setJSON([
                'status' => true,
                'message' => 'Ujian berhasil ditambahkan.'
            ]);
        }
        return $this->fail('Hanya bisa diakses via AJAX.');
    }

    public function update($id = null)
    {
        if ($this->request->isAJAX()) {
            $rules = [
                'bank_soal_id'   => 'required',
                'nama_ujian'     => 'required|min_length[3]',
                'kode_ujian'     => 'required',
                'waktu_mulai'    => 'required|valid_date',
                'waktu_selesai'  => 'required|valid_date',
            ];

            if (!$this->validate($rules)) {
                return $this->response->setJSON([
                    'status' => false,
                    'message' => $this->validation->getErrors()
                ]);
            }

            $data = [
                'bank_soal_id'        => $this->request->getPost('bank_soal_id'),
                'nama_ujian'          => $this->request->getPost('nama_ujian'),
                'deskripsi'           => $this->request->getPost('deskripsi'),
                'kode_ujian'          => $this->request->getPost('kode_ujian'),
                'token'               => $this->request->getPost('token'),
                'acak_soal'           => (int)$this->request->getPost('acak_soal'),
                'acak_opsi'           => (int)$this->request->getPost('acak_opsi'),
                'pakai_token'         => (int)$this->request->getPost('pakai_token'),
                'durasi_ujian'        => (int)$this->request->getPost('durasi_ujian'),
                'minimal_durasi'      => (int)$this->request->getPost('minimal_durasi'),
                'tampil_nilai'        => (int)$this->request->getPost('tampil_nilai'),
                'tampil_pembahasan'   => (int)$this->request->getPost('tampil_pembahasan'),
                'pakai_webcam'        => (int)$this->request->getPost('pakai_webcam'),
                'perangkat_terkunci'  => (int)$this->request->getPost('perangkat_terkunci'),
                'single_login'        => (int)$this->request->getPost('single_login'),
                'created_by'          => $this->request->getPost('created_by'),
                'waktu_mulai'         => $this->request->getPost('waktu_mulai'),
                'waktu_selesai'       => $this->request->getPost('waktu_selesai'),
                'updated_at'          => date('Y-m-d H:i:s')
            ];

            $this->ujianModel->update($id, $data);

            return $this->response->setJSON([
                'status' => true,
                'message' => 'Ujian berhasil diperbarui.'
            ]);
        }
        return $this->fail('Hanya bisa diakses via AJAX.');
    }

    public function delete($id = null)
    {
        if ($this->request->isAJAX()) {
            $this->ujianModel->delete($id);
            return $this->response->setJSON([
                'status' => true,
                'message' => 'Ujian berhasil dihapus.'
            ]);
        }
        return $this->fail('Hanya bisa diakses via AJAX.');
    }

    private function fail($message)
    {
        return $this->response->setJSON([
            'status' => false,
            'message' => $message
        ]);
    }

    private $db;
    //========================= PESERTA ============================
    public function filterPeserta($ujianId)
    {
        if ($this->request->isAJAX()) {
            $pesertaModel = new \App\Models\PesertaModel();

            $filters = $this->request->getGet();

            $peserta = $pesertaModel
                ->select('peserta.id, peserta.nama, peserta.nisn')
                ->whereNotIn('peserta.id', function ($builder) use ($ujianId) {
                    return $builder->select('peserta_id')->from('hasil_ujian')->where('ujian_id', $ujianId);
                });

            if (!empty($filters['tingkat_id'])) {
                $peserta->where('tingkat_id', $filters['tingkat_id']);
            }
            if (!empty($filters['kelas_id'])) {
                $peserta->where('kelas_id', $filters['kelas_id']);
            }
            if (!empty($filters['jurusan_id'])) {
                $peserta->where('jurusan_id', $filters['jurusan_id']);
            }
            if (!empty($filters['agama_id'])) {
                $peserta->where('agama_id', $filters['agama_id']);
            }

            $result = $peserta->orderBy('nama')->findAll();

            return $this->response->setJSON([
                'status' => true,
                'data'   => $result,
            ]);
        }

        return $this->fail('Hanya bisa diakses via AJAX.');
    }


    public function pesertaUjian($ujianId)
    {
        if ($this->request->isAJAX()) {
            $builder = $this->db->table('hasil_ujian h');
            $builder->select('p.id, p.nama, p.nisn');
            $builder->join('peserta p', 'p.id = h.peserta_id');
            $builder->where('h.ujian_id', $ujianId);
            $builder->orderBy('p.nama', 'ASC');

            $data = $builder->get()->getResultArray();

            return $this->response->setJSON([
                'status' => true,
                'data'   => $data,
            ]);
        }

        return $this->fail('Hanya bisa diakses via AJAX.');
    }


    public function addPeserta()
    {
        if ($this->request->isAJAX()) {
            $ujianId = $this->request->getPost('ujian_id');
            $pesertaIds = $this->request->getPost('peserta_id');

            if (!$ujianId || empty($pesertaIds)) {
                return $this->response->setJSON([
                    'status'  => false,
                    'message' => 'Data tidak lengkap.'
                ]);
            }

            $builder = $this->db->table('hasil_ujian');

            // Cek peserta yang sudah ada agar tidak insert duplikat
            $existing = $builder->select('peserta_id')->where('ujian_id', $ujianId)->get()->getResultArray();
            $existingIds = array_column($existing, 'peserta_id');

            $insertData = [];
            foreach ($pesertaIds as $id) {
                if (in_array($id, $existingIds)) continue;

                $insertData[] = [
                    'id'         => \Ramsey\Uuid\Uuid::uuid4()->toString(),
                    'ujian_id'   => $ujianId,
                    'peserta_id' => $id,
                    'status'     => 'belum_mulai',
                    'created_at' => date('Y-m-d H:i:s'),
                ];
            }

            if (!empty($insertData)) {
                $builder->insertBatch($insertData);
            }

            return $this->response->setJSON([
                'status'  => true,
                'message' => 'Peserta berhasil ditambahkan.'
            ]);
        }

        return $this->fail('Hanya bisa diakses via AJAX.');
    }

    public function cekPesertaDiuji()
    {
        if ($this->request->isAJAX()) {
            $ujianId    = $this->request->getPost('ujian_id');
            $pesertaIds = $this->request->getPost('peserta_id');

            if (!$ujianId || !is_array($pesertaIds)) {
                return $this->response->setJSON([
                    'status'  => false,
                    'message' => 'Data tidak lengkap.'
                ]);
            }

            $query = $this->db->table('hasil_ujian')
                ->select('peserta_id')
                ->where('ujian_id', $ujianId)
                ->whereIn('peserta_id', $pesertaIds)
                ->get()
                ->getResultArray();

            $sudahAda = array_column($query, 'peserta_id');
            $belumAda = array_diff($pesertaIds, $sudahAda);

            return $this->response->setJSON([
                'status' => true,
                'data'   => [
                    'sudahAda' => array_values($sudahAda),
                    'belumAda' => array_values($belumAda)
                ]
            ]);
        }

        return $this->fail('Hanya bisa diakses via AJAX.');
    }
    public function removePeserta()
    {
        if ($this->request->isAJAX()) {
            $ujianId    = $this->request->getPost('ujian_id');
            $pesertaIds = $this->request->getPost('peserta_id');

            if (!$ujianId || !is_array($pesertaIds)) {
                return $this->response->setJSON([
                    'status'  => false,
                    'message' => 'Data tidak lengkap.'
                ]);
            }

            $this->db->table('hasil_ujian')
                ->where('ujian_id', $ujianId)
                ->whereIn('peserta_id', $pesertaIds)
                ->delete();

            return $this->response->setJSON([
                'status'  => true,
                'message' => 'Peserta berhasil dihapus dari ujian beserta nilai-nilainya.'
            ]);
        }

        return $this->fail('Hanya bisa diakses via AJAX.');
    }
}
