<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\SiswaModel;
use App\Models\GuruModel;
use App\Models\KelasModel;
use App\Models\SekolahModel;
use ZipArchive;

class CetakKartu extends BaseController
{
    protected $siswaModel;
    protected $guruModel;
    protected $kelasModel;
    protected $sekolahModel;

    public function __construct()
    {
        $this->siswaModel = new SiswaModel();
        $this->guruModel = new GuruModel();
        $this->kelasModel = new KelasModel();
        $this->sekolahModel = new SekolahModel();
    }

    public function index()
    {
        return view('admin/cetak_kartu/index', [
            'title' => 'Cetak Kartu Absensi',
            'kelas' => $this->kelasModel->findAll(),
            'segment' => 'cetak_kartu'
        ]);
    }

    public function prosesGuru()
    {
        $desainId = $this->request->getPost('desain_id') ?? 1;
        $data = $this->guruModel->findAll();
        if (empty($data)) return redirect()->back()->with('error', 'Data Guru tidak ditemukan.');
        return $this->generateZip($data, 'guru', '', $desainId);
    }

    public function prosesSiswa()
    {
        $kelasId = $this->request->getPost('kelas_id');
        $desainId = $this->request->getPost('desain_id') ?? 1;
        
        if (!$kelasId) return redirect()->back()->with('error', 'Silakan pilih kelas terlebih dahulu.');

        $data = $this->siswaModel->select('siswa.*, kelas.nama_kelas, kelas.jurusan')
                                 ->join('kelas', 'kelas.id = siswa.kelas_id')
                                 ->where('siswa.kelas_id', $kelasId)
                                 ->findAll();
        
        if (empty($data)) return redirect()->back()->with('error', 'Tidak ada data siswa.');
        return $this->generateZip($data, 'siswa', $data[0]['nama_kelas'] ?? 'Kelas', $desainId);
    }

    private function generateZip($dataList, $type, $suffix = '', $desainId = 1)
    {
        $zip = new ZipArchive();
        $zipName = "Kartu_" . ucfirst($type) . "_Desain" . $desainId . "_" . str_replace([' ', '/'], '_', $suffix) . "_" . date('His') . ".zip";
        $tempDir = WRITEPATH . 'temp/';
        $zipPath = $tempDir . $zipName;

        if (!is_dir($tempDir)) mkdir($tempDir, 0777, true);
        if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) return "Gagal membuat ZIP.";

        $sekolah = $this->sekolahModel->first();

        foreach ($dataList as $item) {
            $jpgContent = $this->renderCard($item, $type, $desainId, $sekolah);
            $rawName = ($type == 'guru') ? ($item['nama_guru'] ?? 'Guru') : ($item['nama_lengkap'] ?? 'Siswa');
            $fileName = str_replace([' ', '/', '\\'], '_', $rawName) . ".jpg";
            $zip->addFromString($fileName, $jpgContent);
        }

        $zip->close();
        return $this->response->download($zipPath, null)->setFileName($zipName);
    }

    private function renderCard($data, $type, $desainId = 1, $sekolah = null)
    {
        $displayName = ($type == 'guru') ? ($data['nama_guru'] ?? 'TANPA NAMA') : ($data['nama_lengkap'] ?? 'TANPA NAMA');
        $displayId   = ($type == 'guru') ? ($data['nip'] ?? '-') : ($data['nisn'] ?? '-');
        $displaySub  = ($type == 'guru') ? ($data['jabatan'] ?? 'Staff Pengajar') : ($data['nama_kelas'] . " - " . ($data['jurusan'] ?? ''));
        $qrCodeName  = $data['qr_code'] ?? 'default.png';
        $namaSekolah = ($sekolah && isset($sekolah['nama_sekolah'])) ? $sekolah['nama_sekolah'] : "SMK NEGERI INDONESIA";

        $w = 1011; $h = 638;
        $img = imagecreatetruecolor($w, $h);
        
        $white = imagecolorallocate($img, 255, 255, 255);
        $black = imagecolorallocate($img, 0, 0, 0);
        $text_color = $white;

        switch ($desainId) {
            case 2: 
                imagefilledrectangle($img, 0, 0, $w, $h, $white);
                $primary = ($type == 'guru') ? imagecolorallocate($img, 30, 58, 138) : imagecolorallocate($img, 153, 27, 27);
                imagefilledrectangle($img, 0, 0, 40, $h, $primary);
                $text_color = imagecolorallocate($img, 31, 41, 55);
                break;

            case 3: 
                for ($i = 0; $i < $w; $i++) {
                    $p = $i / $w;
                    $r = ($type == 'guru') ? (59 + (37 * $p)) : (220 + (35 * $p));
                    $g = ($type == 'guru') ? (130 - (50 * $p)) : (38 + (100 * $p));
                    $b = ($type == 'guru') ? (246 - (100 * $p)) : (38 - (10 * $p));
                    $col = imagecolorallocate($img, $r, $g, $b);
                    imageline($img, $i, 0, $i, $h, $col);
                }
                break;

            case 4: 
                $bg = ($type == 'guru') ? imagecolorallocate($img, 15, 23, 42) : imagecolorallocate($img, 69, 10, 10);
                imagefilledrectangle($img, 0, 0, $w, $h, $bg);
                $accent = imagecolorallocatealpha($img, 255, 255, 255, 115);
                for($i=0; $i<$w; $i+=50) imageline($img, $i, 0, $w, $h-$i, $accent);
                break;

            default: 
                for ($i = 0; $i < $w; $i++) {
                    $p = $i / $w;
                    $r = ($type == 'guru') ? (15 + (15 * $p)) : (69 + (80 * $p));
                    $g = ($type == 'guru') ? (23 + (15 * $p)) : (10 + (10 * $p));
                    $b = ($type == 'guru') ? (42 + (100 * $p)) : (10 + (10 * $p));
                    $col = imagecolorallocate($img, $r, $g, $b);
                    imageline($img, $i, 0, $i, $h, $col);
                }
                break;
        }

        $fontPath = FCPATH . 'assets/fonts/Montserrat-Bold.ttf';
        $margin_left = 430;

        if (file_exists($fontPath)) {
            imagettftext($img, 22, 0, $margin_left, 100, $text_color, $fontPath, strtoupper($namaSekolah));
            imagettftext($img, 32, 0, $margin_left, 300, $text_color, $fontPath, strtoupper($displayName));
            imagettftext($img, 18, 0, $margin_left, 350, $text_color, $fontPath, $displaySub);
            imagettftext($img, 14, 0, $margin_left, 390, $text_color, $fontPath, ($type == 'guru' ? "NIP: " : "NISN: ") . $displayId);
        }

        $fotoDir = ($type == 'guru') ? 'uploads/foto_guru/' : 'uploads/foto_siswa/';
        $fotoPath = FCPATH . $fotoDir . ($data['foto'] ?: 'default.jpg');
        $px = 85; $py = 175; $ps = 280;
        if (file_exists($fotoPath) && !is_dir($fotoPath)) {
            $info = @getimagesize($fotoPath);
            if ($info) {
                $userImg = ($info[2] == IMAGETYPE_PNG) ? @imagecreatefrompng($fotoPath) : @imagecreatefromjpeg($fotoPath);
                if ($userImg) {
                    imagefilledrectangle($img, $px-5, $py-5, $px+$ps+5, $py+$ps+5, $white);
                    imagecopyresampled($img, $userImg, $px, $py, 0, 0, $ps, $ps, imagesx($userImg), imagesy($userImg));
                    imagedestroy($userImg);
                }
            }
        }

        $qrPath = FCPATH . 'uploads/qr/' . $qrCodeName;
        $qs = 180; $qx = $w - $qs - 80; $qy = $h - $qs - 70;
        if (file_exists($qrPath) && !is_dir($qrPath)) {
            $qrImg = @imagecreatefrompng($qrPath);
            if ($qrImg) {
                imagefilledrectangle($img, $qx-10, $qy-10, $qx+$qs+10, $qy+$qs+10, $white);
                imagecopyresampled($img, $qrImg, $qx, $qy, 0, 0, $qs, $qs, imagesx($qrImg), imagesy($qrImg));
                imagedestroy($qrImg);
            }
        }

        ob_start();
        imagejpeg($img, null, 90);
        $content = ob_get_clean();
        imagedestroy($img);
        return $content;
    }
}