<?php

namespace App\Controllers\Panel\BankSoal;

use App\Controllers\Panel\BC;
use App\Models\Panel\BankSoal;
use CodeIgniter\API\ResponseTrait;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use ZipArchive;

class Export extends BC
{
    use ResponseTrait;
    private $bankSoalModel;
    public function __construct()
    {
        parent::__construct();
        $this->bankSoalModel = new BankSoal();
    }
    public function run($bank_id)
    {
        $bank = $this->bankSoalModel->find($bank_id);
        if (!$bank) return $this->failNotFound();
        $db = db_connect();
        $soalData = $db->table('soal_data')->where('bank_id', $bank_id)->orderBy('id', "ASC")->get()->getResultArray();
        $soalOpsi = $db->table('soal_opsi so')->select('so.*')->join('soal_data sd', 'sd.id=so.soal_id')->where('sd.bank_id', $bank_id)->get()->getResultArray();
        $soalCouple = $db->table('soal_data_couple sc')->select('sc.*')->join('soal_data sd', 'sd.id=sc.soal_id')->where('sd.bank_id', $bank_id)->get()->getResultArray();
        $pathTemp = WRITEPATH . "file/e-soal";
        $files = glob("$pathTemp/*"); // get all file names
        foreach ($files as $file) { // iterate files
            if (is_file($file) && !(strpos($file, "index.html") !== false)) {
                unlink($file); // delete file
            }
        }
        $fileExcel = $pathTemp . "/soal.xlsx";
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet
            ->setCellValue('A1', 'Pertanyaan')
            ->setCellValue('B1', 'Pilihan')
            ->setCellValue('C1', 'Pilihan')
            ->setCellValue('D1', 'Pilihan')
            ->setCellValue('E1', 'Pilihan')
            ->setCellValue('F1', 'Pilihan')
            ->setCellValue('G1', 'Kunci')
            ->setCellValue('H1', 'Jenis')
            ->setCellValue('I1', 'Point Benar')
            ->setCellValue('J1', 'Point Salah')
            ->setCellValue('K1', 'Pertanyaan')
            ->setCellValue('L1', 'Pertanyaan')
            ->setCellValue('M1', 'Pertanyaan')
            ->setCellValue('N1', 'Pertanyaan')
            ->setCellValue('O1', 'Pertanyaan');
        foreach ($soalData as $key => $value) {
            if (empty($value['question']) && in_array($value['jenis_soal'], [(new BankSoal())->jenis('pg'), (new BankSoal())->jenis('pgmulti'), (new BankSoal())->jenis('shortentry'), (new BankSoal())->jenis('pgtf'), (new BankSoal())->jenis('esai')])) continue;
            $value['question'] = str_replace([base_url()], '{BASEURL}', $value['question']);
            $coupleId = [];
            $row = $key + 2;
            $ci = 0;
            $cc = ["K", "L", "M", "N", "O"];
            foreach ($soalCouple as $sk => $sv) {
                if ($sv['soal_id'] != $value['id']) continue;
                $sv['body'] = str_replace([base_url()], '{BASEURL}', $sv['body']);
                $worksheet->setCellValue("{$cc[$ci++]}{$row}", $sv['body']);
                $coupleId[$sv['id']] = $ci;
                $this->moveResource($sv['body'], $pathTemp);
            }

            $kunci = [];
            $oi = [];
            $co = ["B", "C", "D", "E", "F"];
            if (!in_array($value['jenis_soal'], [5, 2])) {
                foreach ($soalOpsi as $sk => $sv) {
                    if ($sv['soal_id'] != $value['id']) continue;
                    if (!isset($oi[$value['id']])) $oi[$value['id']] = 0;
                    $soi = $oi[$value['id']]++;
                    if ($sv['is_key'] && in_array($value['jenis_soal'], [1, 3])) $kunci[] = $soi + 1;
                    if ($value['jenis_soal'] == 4 && $sv['soal_couple_id'] && isset($coupleId[$sv['soal_couple_id']])) {
                        $kunci[] = $coupleId[$sv['soal_couple_id']] . '-' . ($soi + 1);
                    } else if ($value['jenis_soal'] == 6) {
                        $kunci[] = ($soi + 1) . "-" . $sv['is_key'];
                    }
                    $sv['body'] = str_replace([base_url()], '{BASEURL}', $sv['body']);
                    $worksheet->setCellValue("{$co[$soi]}{$row}", $sv['body']);
                    $this->moveResource($sv['body'], $pathTemp);
                }
            }
            $this->moveResource($value['question'], $pathTemp);
            $worksheet
                ->setCellValue("A{$row}", $value['question'])
                ->setCellValue("G{$row}", $value['jenis_soal'] == 5 ? $value['shortentry'] : implode(',', $kunci))
                ->setCellValue("H{$row}", $value['jenis_soal'])
                ->setCellValue("I{$row}", $value['true_default_point'])
                ->setCellValue("J{$row}", $value['false_default_point']);
        }
        // dd("A");
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Xlsx");
        $writer->save($fileExcel);
        $zipName = $pathTemp . "/$bank[kode].zip";
        $za = new ZipArchive;
        $za->open($zipName, ZipArchive::CREATE | ZipArchive::OVERWRITE);

        // Create recursive directory iterator
        /** @var SplFileInfo[] $files */
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($pathTemp),
            RecursiveIteratorIterator::LEAVES_ONLY
        );

        foreach ($files as $name => $file) {
            // Skip directories (they would be added automatically)
            if (!$file->isDir()) {
                if (strpos(basename($name), ".zip") !== false) continue;
                // Get real and relative path for current file
                $filePath = $file->getRealPath();
                $relativePath = substr($filePath, strlen($pathTemp) + 1);

                // Add current file to archive
                $za->addFile($filePath, $relativePath);
            }
        }

        // Zip archive will be created only after closing object
        $za->close();
        setLog("Mengunduh soal $bank[kode]");
        return $this->response->download($zipName, null);
    }
    private function moveResource($str, $path)
    {

        // pattern extract source
        $pattern = '/<source[^>]+src="([^">]+)/i';
        if (preg_match_all($pattern, $str, $matches)) {
            foreach ($matches[1] as $sk => $sv) {
                $file = str_replace(["{BASEURL}", "../../..", base_url()], [FCPATH, FCPATH, FCPATH], $sv);
                if (file_exists($file)) {
                    $name = basename($file);
                    copy($file, "$path/$name");
                }
            }
        }
        $pattern = '/<img[^>]+src="([^">]+)/i';
        if (preg_match_all($pattern, $str, $matches)) {
            foreach ($matches[1] as $sk => $sv) {
                $file = str_replace(["{BASEURL}", "../../..", base_url()], [FCPATH, FCPATH, FCPATH], $sv);
                if (file_exists($file)) {
                    $name = basename($file);
                    copy($file, "$path/$name");
                }
            }
        }
    }
}
