<?php

namespace App\Controllers;

use Core\Controller;
use Core\Database;
use FPDF;

require_once __DIR__ . '/../libraries/fpdf/fpdf.php';

class PDF extends FPDF
{
    function Header()
    {
        $this->Image('assets/img/kop_surat.jpg', 3, 3, 205);
        $this->Ln(35);
    }

    function CellWithImage($x, $y, $number, $imgPath)
    {
        $this->SetXY($x, $y);
        $this->Cell(10, 7, $number, 0, 0, 'C');
        $this->Image($imgPath, $x + 12, $y, 5, 5);
    }
}

class PDFKompreController extends Controller
{
public function hasilPDF()
{
    $nim = $_SESSION['user']['nim'] ?? null;

    if (!$nim) {
        echo "<div class='alert alert-danger'>NIM tidak ditemukan dalam sesi.</div>";
        exit;
    }

    $db = Database::getConnection();

    // Ambil data mahasiswa
    $stmt = $db->prepare("SELECT nama FROM tb_mahasiswa WHERE nim = ?");
    $stmt->execute([$nim]);
    $mahasiswa = $stmt->fetch(\PDO::FETCH_ASSOC);

    if (!$mahasiswa) {
        echo "<div class='alert alert-danger'>Data mahasiswa tidak ditemukan.</div>";
        exit;
    }
    $nama_mahasiswa = $mahasiswa['nama'];

    // Ambil data ujian terakhir (urut berdasarkan waktu_mulai)
    $stmt = $db->prepare("SELECT id_ujiankompre, waktu_mulai FROM tb_ujiankompre WHERE nim = ? ORDER BY waktu_mulai DESC LIMIT 1");
    $stmt->execute([$nim]);
    $ujian = $stmt->fetch(\PDO::FETCH_ASSOC);

    if (!$ujian) {
        echo "<div class='alert alert-danger'>Data ujian tidak ditemukan.</div>";
        exit;
    }

    $id_ujiankompre = $ujian['id_ujiankompre'];
    $tanggal_ujian = date("d-m-Y", strtotime($ujian['waktu_mulai']));

    // Ambil skor sama seperti di getHasil() supaya konsisten
    $stmt = $db->prepare("
        SELECT 
            COUNT(*) AS total,
            COALESCE(SUM(jk.jawaban = sk.jawaban), 0) AS benar
        FROM 
            tb_jawabankompre jk
        JOIN 
            tb_soal_kompre sk ON jk.id_kompre = sk.id_kompre
        WHERE 
            jk.id_ujiankompre = ?
    ");
    $stmt->execute([$id_ujiankompre]);
    $hasilRow = $stmt->fetch(\PDO::FETCH_ASSOC);

    $totalAnswered = (int) ($hasilRow['total'] ?? 0);
    $skor = (int) ($hasilRow['benar'] ?? 0);

    // Ambil daftar soal + jawaban mahasiswa + jawaban benar (untuk grid dan detail)
    $stmt = $db->prepare("
        SELECT 
            sk.id_kompre AS id_soal, 
            sk.pertanyaan,
            jk.jawaban AS jawaban_mahasiswa, 
            sk.jawaban AS jawaban_benar
        FROM tb_soal_kompre sk
        LEFT JOIN tb_jawabankompre jk 
            ON sk.id_kompre = jk.id_kompre 
           AND jk.id_ujiankompre = ?
        WHERE sk.id_prodi = (
            SELECT id_prodi FROM tb_mahasiswa WHERE nim = ?
        )
        ORDER BY sk.id_kompre ASC
    ");
    $stmt->execute([$id_ujiankompre, $nim]);
    $jawaban = $stmt->fetchAll(\PDO::FETCH_ASSOC);

    if (!$jawaban) {
        echo "<div class='alert alert-danger'>Tidak ada jawaban ditemukan.</div>";
        exit;
    }

    // Persiapan grid (20x5)
    $grid = array_fill(0, 20, array_fill(0, 5, ''));
    $index = 0;

    foreach ($jawaban as $data) {
        $jawabanMahasiswa = strtoupper(trim($data['jawaban_mahasiswa'] ?? ''));
        $jawabanBenar     = strtoupper(trim($data['jawaban_benar'] ?? ''));
    
        if ($jawabanMahasiswa !== '' && $jawabanMahasiswa === $jawabanBenar) {
            $iconPath = 'assets/img/check.png'; // ✅ benar
        } else {
            $iconPath = 'assets/img/cross.png'; // ❌ salah atau kosong
        }
    
        $row = $index % 20;
        $col = floor($index / 20);
        $grid[$row][$col] = [
            'number' => ($index + 1),
            'icon'   => $iconPath
        ];
    
        $index++;
    }

    // Generate PDF (sama seperti sebelumnya)
    $pdf = new PDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial', 'B', 14);
    $pdf->Cell(0, 10, 'Hasil Ujian CBT Komprehensif', 0, 1, 'C');
    $pdf->Ln(5);

    $pdf->SetFont('Arial', '', 12);
    $pdf->Cell(40, 7, 'Nama', 0, 0);
    $pdf->Cell(100, 7, ': ' . $nama_mahasiswa, 0, 1);
    $pdf->Cell(40, 7, 'NIM', 0, 0);
    $pdf->Cell(100, 7, ': ' . $nim, 0, 1);
    $pdf->Cell(40, 7, 'Tanggal Ujian', 0, 0);
    $pdf->Cell(100, 7, ': ' . $tanggal_ujian, 0, 1);

    // Tampilkan skor sesuai query getHasil (benar / total answered)
    $pdf->Cell(40, 7, 'Skor', 0, 0);
    $pdf->Cell(100, 7, ': ' . $skor . ' / ' . $totalAnswered, 0, 1);
    $pdf->Ln(5);

    $x_start = 20;
    $y_start = $pdf->GetY();
    $cell_width = 40;
    $cell_height = 7;

    for ($row = 0; $row < 20; $row++) {
        for ($col = 0; $col < 5; $col++) {
            if (!empty($grid[$row][$col])) {
                $x = $x_start + ($col * $cell_width);
                $y = $y_start + ($row * $cell_height);
                $pdf->CellWithImage($x, $y, $grid[$row][$col]['number'], $grid[$row][$col]['icon']);
            }
        }
        $pdf->Ln();
    }

    $pdf->Output("Hasil_Ujian_$nim.pdf", 'I');
}

}
