<?php

namespace App\Controllers\PPDB;

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

class Frontend extends BaseController
{
    protected $ppdbModel;

    public function __construct()
    {
        helper(['text','form']);
        $this->ppdbModel = new PpdbModel();
    }

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

    public function submit()
    {
        $path = $this->request->getPost('registration_path');

        /* ================= VALIDASI ================= */
        $rules = [
            'name'  => 'required|min_length[3]',
            'nisn'  => 'required|numeric',
            'phone' => 'required',
            'gender'=> 'required',
            'birth_place' => 'required',
            'birth_date'  => 'required',
            'address'     => 'required',
            'school_origin' => 'required',
            'registration_path' => 'required',
            'photo_file' => 'uploaded[photo_file]|max_size[photo_file,2048]|ext_in[photo_file,jpg,jpeg,png]',
        ];

        if ($path === 'ZONASI') {
            $rules['kk_file'] = 'uploaded[kk_file]';
            $rules['domicile_distance'] = 'required|numeric';
        }

        if ($path === 'PRESTASI') {
            $rules['raport_file'] = 'uploaded[raport_file]';
            $rules['achievement_desc'] = 'required';
        }

        if ($path === 'AFIRMASI') {
            $rules['akta_file'] = 'uploaded[akta_file]';
            $rules['affirmation_type'] = 'required';
        }

        if (!$this->validate($rules)) {
            // 🔥 WAJIB supaya ketahuan error
            return redirect()->back()
                ->withInput()
                ->with('errors', $this->validator->getErrors());
        }

        /* ================= UPLOAD ================= */
        $uploadPath = WRITEPATH . 'uploads/ppdb/';
        if (!is_dir($uploadPath)) mkdir($uploadPath, 0777, true);

        $photoFile = $this->request->getFile('photo_file');
        $photoName = null;

        if ($photoFile && $photoFile->isValid()) {
            $photoName = $photoFile->getRandomName();
            $photoFile->move($uploadPath, $photoName);
        }

        $kkName = null;
        if ($path === 'ZONASI') {
            $kk = $this->request->getFile('kk_file');
            if ($kk && $kk->isValid()) {
                $kkName = $kk->getRandomName();
                $kk->move($uploadPath, $kkName);
            }
        }

        $raportName = null;
        if ($path === 'PRESTASI') {
            $raport = $this->request->getFile('raport_file');
            if ($raport && $raport->isValid()) {
                $raportName = $raport->getRandomName();
                $raport->move($uploadPath, $raportName);
            }
        }

        $aktaName = null;
        if ($path === 'AFIRMASI') {
            $akta = $this->request->getFile('akta_file');
            if ($akta && $akta->isValid()) {
                $aktaName = $akta->getRandomName();
                $akta->move($uploadPath, $aktaName);
            }
        }

        /* ================= INSERT DB ================= */
        $insert = $this->ppdbModel->insert([
            'reg_no' => 'PPDB-' . date('Y') . '-' . strtoupper(random_string('alnum', 6)),
            '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'),

            'registration_path' => $path,
            'achievement_desc'  => $this->request->getPost('achievement_desc'),
            'affirmation_type'  => $this->request->getPost('affirmation_type'),
            'domicile_distance' => $this->request->getPost('domicile_distance'),

            'photo_file'  => $photoName,
            'kk_file'     => $kkName,
            'raport_file' => $raportName,
            'akta_file'   => $aktaName,

            'status' => 'PENDING'
        ]);

        // 🔥 DEBUG kalau gagal
        if ($insert === false) {
            return redirect()->back()
                ->with('errors', $this->ppdbModel->errors());
        }

        return redirect()->to(site_url('ppdb/status'))
            ->with('success', 'Pendaftaran berhasil. Simpan nomor pendaftaran Anda.');
    }
}
