<?php

namespace App\Controllers\Panel\BankSoal;

use App\Controllers\Panel\BC;
use App\Models\Panel\BankSoal as BankSoalModel;
use App\Models\Panel\UserModel;
use CodeIgniter\API\ResponseTrait;
use ZipArchive;

class Editor extends BC
{
    use ResponseTrait;
    private $BSM;
    public function __construct()
    {
        parent::__construct();
        $this->BSM = new BankSoalModel();
    }
    public function index($id)
    {
        $bank = $this->BSM->find($id);
        if (!$bank) return view('Utils/404');
        return view('Panel/BankSoal/editor', ['page_title' => "Editor Soal", 'bank' => $bank]);
    }
    public function soals($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $opt['limit'] = (int) $this->request->getGet('limit');
        $opt['notIds'] = explode(',', $this->request->getGet('notIds') ?? "");
        $bank = $this->BSM->find($id);
        if (!$bank) return $this->failNotFound('Bank Soal Tidak Ditemukan');
        $soal = $this->BSM->getSoalsBankId($id, $opt);
        return $this->respond($soal);
    }
    public function delete($bid, $sid)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        if (!$this->BSM->find($bid)) return $this->failNotFound('Bank Soal Tidak Ditemukan');
        $bs = db_connect()->table('m_banksoal')->where('id', $bid)->get()->getRowArray();
        db_connect()->table('soal_data')->where('id', $sid)->delete();
        setLog("Menghapus soal pada bank soal $bs[kode]");
        return $this->respond("Berhasil menghapus soal");
    }
    public function save($id)
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        if (!$this->BSM->find($id)) return $this->failNotFound('Bank Soal Tidak Ditemukan');
        $dataSoals = $this->request->getVar('soals');
        if (!$dataSoals) return $this->failValidationErrors("Soal tidak valid");
        $dataSoals = json_decode($dataSoals, true);
        $db = db_connect();
        $db->transStart();
        $needOption = ['1', '3', '4', '6'];
        $needQuestion = ['4'];
        $soal_data = [];
        $soal_data_couple = [];
        $soal_opsi = [];
        $newID = [
            'soal' => [],
            'opsi' => [],
            'couple' => [],
        ];
        $images = [];
        foreach ($dataSoals as $k => $soal) {
            $nomor = $k + 1;
            $soal['isnew'] = $soal['isnew'] ?? false;
            $soal['couples'] = $soal['couples'] ?? [];
            $soal['options'] = $soal['options'] ?? [];
            $soal['shortentry'] = trim($soal['shortentry'] ?? '', ' ');
            if (in_array($soal['jenis_soal'], $needQuestion) && count($soal['couples']) == 0) return $this->failValidationErrors("Minimal 1 Pertanyaan Pada Soal Nomor $nomor");
            if (in_array($soal['jenis_soal'], $needOption) && count($soal['options']) == 0) return $this->failValidationErrors("Minimal 1 Opsi Jawaban Pada Soal Nomor $nomor");

            $soal['question'] = str_replace(["{…}", "{&hellip;}"], ["{...}", "{...}"], $soal['question']);
            $q = base64ToImage($soal['question']);
            $soal['question'] = $q['str'];
            $soal['question'] = $soal['question'];

            if ($soal['isnew']) {
                $db->table('soal_data')->insert([
                    'bank_id' => $id,
                    'true_default_point' => $soal['true_default_point'],
                    'false_default_point' => $soal['false_default_point'],
                    'question' => $soal['question'],
                    'jenis_soal' => $soal['jenis_soal'],
                    'shortentry' => $soal['shortentry'],
                    'created_at' => time(),
                    'updated_at' => time(),
                ]);
                $oid = $soal['id'];
                $soal['id'] = $db->insertID();
                $newID['soal'][$oid] = $soal['id'];
            }
            $images[$soal['id']] = [
                'q' => $q['replacer'],
                'o' => [],
                'c' => [],
            ];
            $soal_data[] = [
                'id' => $soal['id'],
                'bank_id' => $id,
                'true_default_point' => $soal['true_default_point'],
                'false_default_point' => $soal['false_default_point'],
                'jenis_soal' => $soal['jenis_soal'],
                'question' => $soal['question'],
                'shortentry' => $soal['shortentry'],
                'updated_at' => time(),
            ];
            switch ($soal['jenis_soal']) {
                case '1':
                    // PG
                    break;
                case '2':
                    // ESAI
                    break;
                case '3':
                    // PGM
                    break;
                case '4':
                    // PGC
                    $sdcid = [];
                    foreach ($soal['couples'] as $kc => $vc) {
                        $vc['isnew'] = $vc['isnew'] ?? false;
                        $bd = base64ToImage($vc['body']);
                        $vc['body'] = $bd['str'];
                        if ($vc['isnew']) {
                            $db->table('soal_data_couple')->insert([
                                'soal_id' => $soal['id'],
                                'body' => $vc['body'],
                            ]);
                            $oid = $vc['id'];
                            $vc['id'] = $db->insertID();
                            $newID['couple'][$oid] = $vc['id'];
                            foreach ($soal['options'] as $ko => $vo) {
                                if ($vo['soal_couple_id'] == $oid) {
                                    $soal['options'][$ko]['soal_couple_id'] = $vc['id'];
                                    break;
                                }
                            }
                            $soal['couples'][$kc]['id'] = $vc['id'];
                        }
                        $images[$soal['id']]['c'][$vc['id']] = $bd['replacer'];
                        $sdcid[] = $vc['id'];
                        $soal_data_couple[] = [
                            'id' => $vc['id'],
                            'body' => $vc['body'],
                            'soal_id' => $soal['id'],
                        ];
                    }
                    if (count($sdcid) == 0) $db->table('soal_data_couple')->where('soal_id', $soal['id'])->delete();
                    else if (count($sdcid) > 0)  $db->table('soal_data_couple')->whereNotIn('id', $sdcid)->where('soal_id', $soal['id'])->delete();
                    break;
                case '5':
                    // SE
                    break;
                case '6':
                    // PGTF
                    break;

                default:
                    return $this->fail("Jenis soal tidak valid");
            }
            $sdoid = [];
            foreach ($soal['options'] as $ko => $vo) {
                $vo['isnew'] = $vo['isnew'] ?? false;
                $bd = base64ToImage($vo['body']);
                $vo['body'] = $bd['str'];
                if ($vo['isnew']) {
                    $db->table('soal_opsi')->insert([
                        'soal_couple_id' => $vo['soal_couple_id'] ?? null,
                        'soal_id' => $soal['id'],
                        'body' => $vo['body'],
                        'is_key' => $vo['is_key'] ?? '0',
                    ]);
                    $oid = $vo['id'];
                    $vo['id'] = $db->insertID();
                    $newID['opsi'][$oid] = $vo['id'];
                }

                $images[$soal['id']]['o'][$vo['id']] = $bd['replacer'];
                $sdoid[] = $vo['id'];
                $soal_opsi[] = [
                    'id' => $vo['id'],
                    'soal_couple_id' => $vo['soal_couple_id'] ?? null,
                    'body' => $vo['body'],
                    'soal_id' => $soal['id'],
                    'is_key' => $vo['is_key'] ?? '0',
                ];
            }
            if (count($sdoid) == 0) $db->table('soal_opsi')->where('soal_id', $soal['id'])->delete();
            else if (count($sdoid) > 0)  $db->table('soal_opsi')->whereNotIn('id', $sdoid)->where('soal_id', $soal['id'])->delete();
        }
        if (count($soal_data) > 0) $db->table('soal_data')->updateBatch($soal_data, 'id');
        if (count($soal_data_couple) > 0) $db->table('soal_data_couple')->updateBatch($soal_data_couple, 'id');
        if (count($soal_opsi) > 0) $db->table('soal_opsi')->updateBatch($soal_opsi, 'id');
        $db->table('m_banksoal')->set(['updated_at' => time()])->update();
        $db->transComplete();
        if ($db->transStatus() === FALSE) {
            $db->transRollback();
            return $this->fail("Gagal menyimpan data soal");
        }
        $bs = $db->table('m_banksoal')->where('id', $id)->get()->getRowArray();
        setLog("Mengubah soal pada bank soal $bs[kode]");
        return $this->respond(['message' => "Berhasil menyimpan data soal", 'newID' => $newID, 'images' => $images]);
    }
}
