<?php
namespace App\Controllers;

use Core\Controller;
use App\Utils\Flasher;
use App\Models\Absensi;
use App\Models\DosenMk;

class EditAbsensiController extends Controller
{
    private $absensiModel;
    private $dosenMkModel;

    public function __construct()
    {
        $this->absensiModel = $this->model('Absensi');
        $this->dosenMkModel = $this->model('DosenMk');
    }

	public function index()
	{
		$dosenMkModel = new DosenMk();
		$tahunAkademik = $dosenMkModel->getTahunAkademikAktif();
		$niy = $_SESSION['user']['niy'] ?? null;

		$matkuls = $dosenMkModel->getMatkulByDosen($niy, $tahunAkademik);

		$absensi = [];
		$selectedDmk = null;
		$selectedPertemuan = null;
		$error = null;

		if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cari'])) {
			$selectedDmk = $_POST['id_dmk'];
			$selectedPertemuan = (int) $_POST['edit_pertemuan'];

			$lastPertemuan = $this->absensiModel->getLastPertemuan($selectedDmk);

			if ($selectedPertemuan > $lastPertemuan) {
				$error = "Presensi pada pertemuan ke-$selectedPertemuan belum tersedia, karena anda baru melakukan presensi pada kelas ini hingga pertemuan ke-$lastPertemuan.";
				$absensi = []; // kosongkan supaya tabel tidak muncul
			} else {
				$absensi = $this->absensiModel->getAbsensiForEdit(
					$selectedDmk,
					$selectedPertemuan,
					$tahunAkademik
				);
			}
		}

		$this->view('dosen/editpresensi', [
			'matkuls' => $matkuls,
			'absensi' => $absensi,
			'selectedDmk' => $selectedDmk,
			'selectedPertemuan' => $selectedPertemuan,
			'error' => $error
		]);
	}

    public function update()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_absensi'])) {
            $idDmk = $_POST['id_dmk'];
            $pertemuan = $_POST['edit_pertemuan'];
            $latitude = $_POST['latitude'] ?? null;
            $longitude = $_POST['longitude'] ?? null;
            $keteranganLokasi = $_POST['keterangan_lokasi'] ?? null;
    
            $tahunAkademik = (new DosenMk())->getTahunAkademikAktif();
    
            $nimList = $_POST['nim'] ?? [];
            $statusList = $_POST['status_edit'] ?? [];
    
            foreach ($nimList as $index => $nim) {
                $status = $statusList[$index] ?? null;
    
                $detail = $this->absensiModel->getDetailDmk($idDmk);
                $idKrs = $this->absensiModel->getIdKrs($nim, $detail['kode_mk'], $detail['tahun_akademik']);
    
                if ($idKrs) {
                	if ($this->absensiModel->checkAbsensiExists($idKrs, $pertemuan)) {
                		// ✅ UPDATE
                		$this->absensiModel->updateAbsensiMahasiswa(
                			$idKrs,
                			$pertemuan,
                			$status,
                			$latitude,
                			$longitude,
                			$keteranganLokasi
                		);
                	} else {
                		// ✅ INSERT
                		$this->absensiModel->simpanAbsensi([
                			'id_krs' => $idKrs,
                			'kode_mk' => $detail['kode_mk'],
                			'kode_kelas' => $detail['kode_kelas'],
                			'pertemuan_ke' => $pertemuan,
                			'status' => $status,
                			'tanggal_absensi' => date('Y-m-d H:i:s'),
                			'tahun_akademik' => $detail['tahun_akademik'],
                			'latitude' => $latitude,
                			'longitude' => $longitude,
                			'keterangan_lokasi' => $keteranganLokasi
                		]);
                	}
                }

            }
    
            Flasher::setFlash('Absensi berhasil diperbarui', 'success');
            header('Location: /dashboard/dosen-editabsen_mahasiswa');
            exit;
        }
    }

public function cetakExcel()
{
    ini_set('display_errors', '0');
    ini_set('display_startup_errors', '0');
    error_reporting(0);

    $idDmk = $_GET['id_dmk'] ?? null;
    if (!$idDmk) exit;

    $lastPertemuan = $this->absensiModel->getLastPertemuan($idDmk);
    if ($lastPertemuan < 16) exit;

    $detail = $this->absensiModel->getDetailDmk($idDmk);
    if (!$detail) exit;

    $kodeMk    = preg_replace('/[^A-Za-z0-9\-]/', '_', $detail['kode_mk']);
    $kodeKelas = preg_replace('/[^A-Za-z0-9\-]/', '_', $detail['kode_kelas']);
    $ta        = preg_replace('/[^A-Za-z0-9\-]/', '_', $detail['tahun_akademik']);

    $filename = "Rekap_Presensi_{$kodeMk}_Kelas_{$kodeKelas}_{$ta}.csv";

    $data = $this->absensiModel->getRekapAbsensi16($idDmk, $detail['tahun_akademik']);

    while (ob_get_level()) ob_end_clean();

    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="'.$filename.'"');
    header('Pragma: no-cache');
    header('Expires: 0');

    $out = fopen('php://output', 'w');

    // BOM
    fwrite($out, "\xEF\xBB\xBF");
    // Paksa delimiter Excel
    fwrite($out, "sep=;\n");

    $header = ['No', 'NIM', 'Nama'];
    for ($i = 1; $i <= 16; $i++) $header[] = "P{$i}";
    $header[] = 'Alfa';
    $header[] = 'Izin';
    $header[] = 'Sakit';

    fputcsv($out, $header, ';');

    $no = 1;
    foreach ($data as $mhs) {
        $row = [$no++, $mhs['nim'], $mhs['nama']];
        $alfa = $izin = $sakit = 0;

        for ($p = 1; $p <= 16; $p++) {
            $status = $mhs['p'.$p] ?? '';

            if ($status === 'Hadir') {
                $val = '=UNICHAR(10003)'; // ✓
            } elseif ($status === 'Alfa') {
                $val = '=UNICHAR(10007)'; // ✗
                $alfa++;
            } elseif ($status === 'Izin') {
                $val = 'I';
                $izin++;
            } elseif ($status === 'Sakit') {
                $val = 'S';
                $sakit++;
            } else {
                $val = '';
            }

            $row[] = $val;
        }

        $row[] = $alfa;
        $row[] = $izin;
        $row[] = $sakit;

        fputcsv($out, $row, ';');
    }

    fclose($out);
    exit;
}

}
