<?php

namespace App\Controllers\Panel\Ujian\Jadwal\Export;

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

class BelumUjian extends BC
{
    use ResponseTrait;
    private $jadwalModel;
    public function __construct()
    {
        parent::__construct();
        $this->jadwalModel = new Jadwal();
    }
    public function index()
    {
        $id = $this->request->getGet('id') ?? '';
        $id = explode(',', $id);
        if (!$id) return $this->failForbidden('Invalid id');
        $opt = [];
        if (!user()->hasRole('admin')) {
            $opt['user_id'] = user()->id;
            $opt['pengawas_id'] = user()->id;
        }
        $opt['id'] = $id;
        $spreadsheet = new Spreadsheet();
        $spreadsheet->getActiveSheet()->setTitle("Belum Mengerjakan Ujian");
        $worksheet = $spreadsheet->setActiveSheetIndex(0);
        $today = date("Y-m-d");
        $path = WRITEPATH . "/file/ujian/belum-mengerjakan-$today.xlsx";
        $startRow = 2;
        $number = $startRow - 1;
        $worksheet->setCellValue("A1", "No")->setCellValue("B1", "Nomor Induk")->setCellValue("C1", "Nama")->setCellValue("D1", "Kelas")->setCellValue("E1", "Nama Ujian")->setCellValue("F1", "Mata Pelajaran");
        $data = $this->jadwalModel->getAll($opt);
        foreach ($data as $d) {
            $popt['status'] = ['0'];
            $peserta = $this->jadwalModel->peserta($d['id'], $popt);
            foreach ($peserta as $kp => $vp) {
                $worksheet
                    ->setCellValue("A$startRow", $number)
                    ->setCellValue("B$startRow", $vp['nomor_induk'])
                    ->setCellValue("C$startRow", $vp['nama'])
                    ->setCellValue("D$startRow", $vp['nama_kelas'])
                    ->setCellValue("E$startRow", $d['nama'])
                    ->setCellValue("F$startRow", $d['nama_mapel']);
                $startRow++;
                $number++;
            }
        }
        $worksheet->getColumnDimensionByColumn(1)->setAutoSize(true);
        $worksheet->getColumnDimensionByColumn(2)->setAutoSize(true);
        $worksheet->getColumnDimensionByColumn(3)->setAutoSize(true);
        $worksheet->getColumnDimensionByColumn(4)->setAutoSize(true);
        $worksheet->getColumnDimensionByColumn(5)->setAutoSize(true);
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Xlsx");
        $writer->save($path);
        return $this->response->download($path, null);
    }
}
