<?php
namespace App\Controllers\PPDB;

use App\Controllers\BaseController;
use App\Models\PpdbModel;

class Admin extends BaseController
{
    public function index()
    {
        $model = new PpdbModel();
        $data['applicants'] = $model->orderBy('id', 'DESC')->findAll();
        return view('ppdb/admin/index', $data);
    }

    public function detail_reg($id)
    {
        $model = new \App\Models\PpdbModel();
        $record = $model->find($id);

        if (!$record) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        // === CEK KELENGKAPAN DOKUMEN ===
        $rapors = json_decode($record['rapor_file'] ?? '[]', true);

        $docComplete =
            !empty($rapors) &&
            !empty($record['kk_file']) &&
            !empty($record['akta_file']) &&
            !empty($record['photo_file']);

        return view('ppdb/admin/detail_reg', [
            'record' => $record,
            'docComplete' => $docComplete
        ]);
    }



    public function detail($id)
    {
        $model = new \App\Models\PpdbModel();
        $record = $model->find($id);

        if (!$record) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        // === CEK KELENGKAPAN DOKUMEN ===
        $rapors = json_decode($record['rapor_file'] ?? '[]', true);

        $docComplete =
            !empty($rapors) &&
            !empty($record['kk_file']) &&
            !empty($record['akta_file']) &&
            !empty($record['photo_file']);

        return view('ppdb/admin/detail', [
            'record' => $record,
            'docComplete' => $docComplete
        ]);
    }

    public function approve($id)
    {
        $model = new PpdbModel();
        $record = $model->find($id);

        if (!$record) {
            return $this->response->setJSON([
                'status' => false,
                'message' => 'Data tidak ditemukan'
            ]);
        }

        $token = bin2hex(random_bytes(16));

        $model->update($id, [
            'status' => 'APPROVED',
            'announcement_token' => $token,
            'approved_at' => date('Y-m-d H:i:s')
        ]);

        return $this->response->setJSON([
            'status' => true,
            'message' => '✅ Pendaftaran BERHASIL DISETUJUI'
        ]);
    }

    public function reject($id)
    {
        $model = new PpdbModel();

        $data = $this->request->getJSON(true);
        $note = $data['reject_note'] ?? null;

        if (!$note) {
            return $this->response->setJSON([
                'status' => false,
                'message' => 'Alasan penolakan wajib diisi'
            ]);
        }

        $model->update($id, [
            'status' => 'REJECTED',
            'reject_note' => $note,
            'updated_at' => date('Y-m-d H:i:s')
        ]);

        return $this->response->setJSON([
            'status' => true,
            'message' => '❌ Pendaftaran berhasil DITOLAK'
        ]);
    }


    public function data()
    {
        $model = new \App\Models\PpdbModel();
        $data = $model->orderBy('id', 'DESC')->findAll();

        return $this->response->setJSON([
            "data" => $data
        ]);
    }
    public function selectionDashboard()
    {
        $model = new \App\Models\PpdbModel();

        $data = [
            'total' => $model->countAll(),
            'approved' => $model->where('status', 'APPROVED')->countAllResults(),
            'submit' => $model->where('status', 'SUBMIT')->countAllResults(),
            'rejected' => $model->where('status', 'REJECTED')->countAllResults(),
            'rank' => $model->orderBy('score', 'DESC')->findAll(), // kalau pakai nilai
        ];

        return view('ppdb/admin/selection_dashboard', $data);
    }

    public function verification()
    {
        $model = new \App\Models\PpdbModel();

        $data = [
            'submit' => $model->where('status', 'SUBMIT')->countAllResults(),
            'approved' => $model->where('status', 'APPROVED')->countAllResults(),
            'rejected' => $model->where('status', 'REJECTED')->countAllResults(),
            'list' => $model->orderBy('id', 'DESC')->findAll()
        ];

        return view('ppdb/admin/verification', $data);
    }

    public function edit($id)
    {
        $model = new \App\Models\PpdbModel();
        $record = $model->find($id);

        if (!$record) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        return view('ppdb/admin/edit', [
            'record' => $record
        ]);
    }


    public function update($id)
    {
        $model = new \App\Models\PpdbModel();
        $record = $model->find($id);

        if (!$record) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

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

        // ================= FILE SINGLE =================
        $saveFile = function ($field, $old = null) use ($uploadPath) {
            $file = $this->request->getFile($field);
            if ($file && $file->isValid() && !$file->hasMoved()) {
                $name = $file->getRandomName();
                $file->move($uploadPath, $name);
                return $name;
            }
            return $old;
        };

        // ================= FILE RAPOR (MULTI) =================
        $oldRapor = json_decode($record['rapor_file'] ?? '[]', true);
        $newRapor = [];

        $raporFiles = $this->request->getFileMultiple('rapor_file');

        if ($raporFiles) {
            foreach ($raporFiles as $file) {
                if ($file->isValid() && !$file->hasMoved()) {
                    $name = $file->getRandomName();
                    $file->move($uploadPath, $name);
                    $newRapor[] = $name;
                }
            }
        }

        // MERGE RAPOR LAMA + BARU
        $finalRapor = array_merge($oldRapor, $newRapor);


        // ================= UPDATE DATA =================
        $model->update($id, [
            'name' => $this->request->getPost('name'),
            'nisn' => $this->request->getPost('nisn'),
            'birth_place' => $this->request->getPost('birth_place'),
            'birth_date' => $this->request->getPost('birth_date'),
            'gender' => $this->request->getPost('gender'),
            'phone' => $this->request->getPost('phone'),
            'address' => $this->request->getPost('address'),

            'father_name' => $this->request->getPost('father_name'),
            'father_job' => $this->request->getPost('father_job'),
            'mother_name' => $this->request->getPost('mother_name'),
            'mother_job' => $this->request->getPost('mother_job'),

            'school_origin' => $this->request->getPost('school_origin'),
            'school_address' => $this->request->getPost('school_address'),

            'rapor_file' => json_encode($finalRapor),
            'kk_file' => $saveFile('kk_file', $record['kk_file']),
            'akta_file' => $saveFile('akta_file', $record['akta_file']),
            'photo_file' => $saveFile('photo_file', $record['photo_file']),
        ]);

        return redirect()->to(site_url('ppdb/admin/detail_reg/' . $id))
            ->with('success', '✅ Data PPDB berhasil diperbarui');
    }
    private function isDocumentComplete(array $r): bool
    {
        $rapor = json_decode($r['rapor_file'] ?? '[]', true);

        return !empty($rapor)
            && !empty($r['kk_file'])
            && !empty($r['akta_file'])
            && !empty($r['photo_file']);
    }
    public function print($id)
    {
        $model = new \App\Models\PPDBModel();
        $record = $model->find($id);

        if (!$record) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        return view('ppdb/admin/print', [
            'record' => $record
        ]);
    }
}
