<?php

namespace App\Controllers\PPDB;

use App\Controllers\BaseController;
use App\Models\PpdbModel;
use App\Models\PPDBPaymentModel;
use CodeIgniter\Database\Config;

class Register extends BaseController
{
    protected $ppdbModel;
    protected $paymentModel;
    protected $db;

    public function __construct()
    {
        helper('text');
        $this->ppdbModel = new PpdbModel();
        $this->paymentModel = new PPDBPaymentModel();
        $this->db = Config::connect(); // ✅ FIX VS CODE KUNING
    }

    /* ===============================
     * HALAMAN
     * =============================== */
    public function index()
    {
        return view('ppdb/admin/index');
    }

    public function form()
    {
        return view('ppdb/admin/form');
    }

    /* ===============================
     * SUBMIT PENDAFTARAN
     * =============================== */
    public function submit()
    {
        $post = $this->request->getPost();
        $db = $this->db;
        $db->transBegin();

        try {

            $uploadPath = FCPATH . 'uploads/ppdb/';
            if (!is_dir($uploadPath)) {
                mkdir($uploadPath, 0777, true);
            }

            $saveFile = function ($name) use ($uploadPath) {
                $file = $this->request->getFile($name);
                if ($file && $file->isValid() && !$file->hasMoved()) {
                    $newName = time() . '_' . $file->getRandomName();
                    $file->move($uploadPath, $newName);
                    return $newName;
                }
                return null;
            };

            /* ==============================
               DATA UTAMA
            ============================== */
            $data = [

                // REG
                'reg_no' => 'PPDB-' . date('Y') . '-' . strtoupper(random_string('alnum', 6)),
                'school_level' => $post['school_level'],
                'registration_path' => $post['registration_path'],

                // SISWA
                'name' => $post['name'],
                'nickname' => $post['nickname'],
                'gender' => $post['gender'],
                'nisn' => $post['nisn'],
                'nik' => $post['nik'],
                'akta_number' => $post['akta_number'],
                'birth_place' => $post['birth_place'],
                'birth_date' => $post['birth_date'],
                'religion' => $post['religion'],
                'citizenship' => $post['citizenship'],
                'child_order' => $post['child_order'],
                'siblings' => $post['siblings'],
                'special_needs' => $post['special_needs'] ?? null,

                // ALAMAT
                'address_street' => $post['address_street'],
                'rt_rw' => $post['rt_rw'],
                'postal_code' => $post['postal_code'],
                'province' => $post['province'],
                'city' => $post['city'],
                'district' => $post['district'],
                'village' => $post['village'],
                'live_with' => $post['live_with'],
                'transport_mode' => $post['transport_mode'],
                'distance_to_school' => $post['distance_to_school'],
                'travel_time' => $post['travel_time'],

                // ORTU
                'parent_status' => $post['parent_status'],

                'father_name' => $post['father_name'] ?? null,
                'father_nik' => $post['father_nik'] ?? null,
                'father_birth_year' => $post['father_birth_year'] ?? null,
                'father_address' => $post['father_address'] ?? null,
                'father_education' => $post['father_education'] ?? null,
                'father_job' => $post['father_job'] ?? null,
                'father_income' => $post['father_income'] ?? null,
                'father_phone' => $post['father_phone'] ?? null,

                'mother_name' => $post['mother_name'] ?? null,
                'mother_nik' => $post['mother_nik'] ?? null,
                'mother_birth_year' => $post['mother_birth_year'] ?? null,
                'mother_address' => $post['mother_address'] ?? null,
                'mother_education' => $post['mother_education'] ?? null,
                'mother_job' => $post['mother_job'] ?? null,
                'mother_income' => $post['mother_income'] ?? null,
                'mother_phone' => $post['mother_phone'] ?? null,

                // WALI
                'guardian_name' => $post['guardian_name'] ?? null,
                'guardian_nik' => $post['guardian_nik'] ?? null,
                'guardian_birth_year' => $post['guardian_birth_year'] ?? null,
                'guardian_address' => $post['guardian_address'] ?? null,
                'guardian_education' => $post['guardian_education'] ?? null,
                'guardian_job' => $post['guardian_job'] ?? null,
                'guardian_income' => $post['guardian_income'] ?? null,
                'guardian_phone' => $post['guardian_phone'] ?? null,

                // SEKOLAH ASAL
                'origin_school_level' => $post['origin_school_level'],
                'school_status' => $post['school_status'],
                'school_origin' => $post['school_origin'],
                'school_npsn' => $post['school_npsn'],
                'school_city' => $post['school_city'],
                'graduation_year' => $post['graduation_year'],
                'certificate_number' => $post['certificate_number'],

                // FILE UMUM
                'photo_file' => $saveFile('photo_file'),
                'kk_file' => $saveFile('kk_file'),
                'akta_file' => $saveFile('akta_file'),
                'ktp_parent_file' => $saveFile('ktp_parent_file'),
                'rapor_file' => $saveFile('rapor_file'),
                'kip_file' => $saveFile('kip_file'),
                'ijazah_file' => $saveFile('ijazah_file'),
                'skl_file' => $saveFile('skl_file'),

                // SYSTEM
                'status' => 'SUBMIT'
            ];

            /* ==============================
               PRESTASI (KONDISIONAL)
            ============================== */
            if ($post['registration_path'] === 'PRESTASI') {

                $data['prestasi_type'] = $post['prestasi_type'];

                if ($post['prestasi_type'] === 'AKADEMIK') {

                    $data['prestasi_academic_level'] = $post['prestasi_academic_level'];
                    $data['prestasi_academic_rank'] = $post['prestasi_academic_rank'];
                    $data['prestasi_academic_subject'] = $post['prestasi_academic_subject'];
                    $data['prestasi_academic_year'] = $post['prestasi_academic_year'];

                } elseif ($post['prestasi_type'] === 'NON_AKADEMIK') {

                    $data['prestasi_non_type'] = $post['prestasi_non_type'];
                    $data['prestasi_non_level'] = $post['prestasi_non_level'];
                    $data['prestasi_non_rank'] = $post['prestasi_non_rank'];
                    $data['prestasi_non_year'] = $post['prestasi_non_year'];
                    $data['prestasi_non_organizer'] = $post['prestasi_non_organizer'];
                    $data['prestasi_certificate_file'] = $saveFile('prestasi_certificate_file');
                }
            }

            $this->ppdbModel->insert($data);

            $db->transCommit();

            return redirect()->to(site_url('ppdb'))
                ->with('success', '✅ Pendaftaran berhasil dikirim');

        } catch (\Throwable $e) {

            $db->transRollback();
            return redirect()->back()->with('error', $e->getMessage());
        }
    }


    /* ===============================
     * CEK STATUS
     * =============================== */
    public function status()
    {
        return view('ppdb/status');
    }

    public function checkStatus()
    {
        $keyword = $this->request->getPost('keyword');

        $ppdb = $this->ppdbModel
            ->groupStart()
            ->where('reg_no', $keyword)
            ->orWhere('nisn', $keyword)
            ->groupEnd()
            ->first();

        if (!$ppdb) {
            return redirect()->back()->with('error', 'Data tidak ditemukan');
        }

        $payment = $this->paymentModel
            ->where('student_id', $ppdb['id'])
            ->first();

        return view('ppdb/status_result', compact('ppdb', 'payment'));
    }

    /* ===============================
     * DETAIL & PRINT
     * =============================== */
    public function detail_reg($id)
    {
        $record = $this->ppdbModel->find($id);
        if (!$record) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }
        return view('ppdb/admin/detail_reg', compact('record'));
    }

    public function print($id)
    {
        $record = $this->ppdbModel->find($id);
        if (!$record) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }
        return view('ppdb/admin/print', compact('record'));
    }

    /* ===============================
     * CEK KUOTA (AJAX)
     * =============================== */
    public function checkQuota()
    {
        $level = $this->request->getPost('school_level');
        $path = $this->request->getPost('registration_path');

        if (!$level || !$path) {
            return $this->response->setJSON(['available' => false]);
        }

        $quota = $this->db->table('ppdb_quotas')
            ->where([
                'school_level' => $level,
                'registration_path' => $path
            ])
            ->get()
            ->getRowArray();

        if (!$quota) {
            return $this->response->setJSON([
                'available' => false,
                'quota' => 0,
                'used' => 0,
                'remaining' => 0
            ]);
        }

        $used = $this->ppdbModel
            ->where('school_level', $level)
            ->where('registration_path', $path)
            ->countAllResults();

        $remaining = max($quota['quota'] - $used, 0);

        return $this->response->setJSON([
            'available' => $remaining > 0,
            'quota' => (int) $quota['quota'],
            'used' => (int) $used,
            'remaining' => (int) $remaining
        ]);
    }
    private function addWatermark($filePath)
    {
        $text = 'PPDB ' . date('Y');
        $fontSize = 14;
        $margin = 15;

        $info = getimagesize($filePath);
        if (!$info)
            return;

        switch ($info['mime']) {
            case 'image/jpeg':
                $image = imagecreatefromjpeg($filePath);
                break;
            case 'image/png':
                $image = imagecreatefrompng($filePath);
                break;
            default:
                return;
        }

        $color = imagecolorallocatealpha($image, 255, 255, 255, 60);

        $x = imagesx($image) - (strlen($text) * 9) - $margin;
        $y = imagesy($image) - $margin;

        imagestring($image, 5, $x, $y, $text, $color);

        if ($info['mime'] === 'image/png') {
            imagepng($image, $filePath);
        } else {
            imagejpeg($image, $filePath, 90);
        }

        imagedestroy($image);
    }
    public function checkDuplicate()
    {
        $nisn = $this->request->getPost('nisn');
        $nik = $this->request->getPost('nik');

        $db = \Config\Database::connect();

        $exists = $db->table('ppdb_registrations')
            ->where('nisn', $nisn)
            ->orWhere('nik', $nik)
            ->countAllResults();

        if ($exists > 0) {
            return $this->response->setJSON([
                'status' => 'duplicate',
                'message' => '❌ NISN atau NIK sudah terdaftar'
            ]);
        }

        return $this->response->setJSON([
            'status' => 'ok'
        ]);
    }

}
