<?php
namespace App\Controllers;

use Config\Database;

class Apply extends BaseController
{
    private function ensureApplicationsTable()
    {
        $db = Database::connect();
        try {
            $db->query("CREATE TABLE IF NOT EXISTS applications (
                id INT AUTO_INCREMENT PRIMARY KEY,
                application_no VARCHAR(32) NOT NULL,
                name_en VARCHAR(255) NOT NULL,
                name_ar VARCHAR(255) NULL,
                gender VARCHAR(16) NULL,
                class_id INT NULL,
                program VARCHAR(255) NULL,
                mobile VARCHAR(64) NULL,
                student_iqama VARCHAR(64) NULL,
                father_name VARCHAR(255) NULL,
                occupation VARCHAR(255) NULL,
                parent_iqama VARCHAR(64) NULL,
                telephone VARCHAR(64) NULL,
                address TEXT NULL,
                status VARCHAR(32) NOT NULL DEFAULT 'Pending',
                apply_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
            )");
        } catch (\Throwable $e) {
            // ignore creation errors
        }
    }

    public function index()
    {
        $db = Database::connect();
        $classes = [];
        try { $classes = $db->table('classes')->orderBy('name_en','asc')->get()->getResultArray(); } catch (\Throwable $e) { $classes = []; }
        return view('public/apply', [
            'title' => 'Apply for Admission',
            'classes' => $classes,
        ]);
    }

    public function submit()
    {
        $db = Database::connect();
        $req = $this->request;
        $this->ensureApplicationsTable();
        try {
            $nameEn = trim((string) $req->getPost('name_en'));
            $nameAr = trim((string) $req->getPost('name_ar'));
            if ($nameEn === '') { throw new \RuntimeException('Name is required'); }
            $applicationNo = 'APP-' . date('Ymd-His');
            $db->table('applications')->insert([
                'application_no' => $applicationNo,
                'name_en' => $nameEn,
                'name_ar' => ($nameAr !== '' ? $nameAr : null),
                'gender' => $req->getPost('gender') ?: null,
                'class_id' => ($req->getPost('class_id') ? (int)$req->getPost('class_id') : null),
                'program' => $req->getPost('program') ?: null,
                'mobile' => $req->getPost('mobile') ?: null,
                'student_iqama' => $req->getPost('student_iqama') ?: null,
                'father_name' => $req->getPost('father_name') ?: null,
                'occupation' => $req->getPost('occupation') ?: null,
                'parent_iqama' => $req->getPost('parent_iqama') ?: null,
                'telephone' => $req->getPost('telephone') ?: null,
                'address' => $req->getPost('address') ?: null,
                'status' => 'Pending',
            ]);
            return redirect()->to('/apply')->with('success', 'Application submitted successfully. Your reference: ' . $applicationNo);
        } catch (\Throwable $e) {
            return redirect()->back()->with('error', 'Failed to submit application: ' . $e->getMessage())->withInput();
        }
    }
}
