<?php
namespace App\Controllers;

use Config\Database;

class Applications 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 */ }
    }

    public function index()
    {
        $db = Database::connect();
        $this->ensureApplicationsTable();
        $apps = [];
        try {
            $apps = $db->table('applications')->orderBy('id','desc')->get()->getResultArray();
        } catch (\Throwable $e) { $apps = []; }
        return view('applications/index', [
            'title' => 'Applications',
            'applications' => $apps,
        ]);
    }

    public function approve($id)
    {
        $db = Database::connect();
        try { $db->table('applications')->where('id', (int) $id)->update(['status' => 'Approved']); } catch (\Throwable $e) {}
        return redirect()->to('/applications')->with('success', 'Application approved.');
    }

    public function reject($id)
    {
        $db = Database::connect();
        try { $db->table('applications')->where('id', (int) $id)->update(['status' => 'Rejected']); } catch (\Throwable $e) {}
        return redirect()->to('/applications')->with('success', 'Application rejected.');
    }

    public function delete($id)
    {
        $db = Database::connect();
        try { $db->table('applications')->where('id', (int) $id)->delete(); } catch (\Throwable $e) {}
        return redirect()->to('/applications')->with('success', 'Application deleted.');
    }

    public function continue($id)
    {
        $db = Database::connect();
        $app = [];
        try { $app = $db->table('applications')->where('id', (int)$id)->get()->getRowArray(); } catch (\Throwable $e) { $app = []; }
        if (! $app) { return redirect()->to('/applications')->with('error', 'Application not found'); }

        // Build lists similar to Enrollment::index
        $locale = service('language')->getLocale();
        $isArabic = ($locale === 'ar');
        $schoolYears = $classes = $sections = $paymentTypes = $nationalities = $religions = [];
        try { $schoolYears = $db->table('school_years')->get()->getResultArray(); } catch (\Throwable $e) { $schoolYears = []; }
        try { $classes = $db->table('classes')->get()->getResultArray(); } catch (\Throwable $e) { $classes = []; }
        try { $sections = $db->table('sections')->get()->getResultArray(); } catch (\Throwable $e) { $sections = []; }
        try { $paymentTypes = $db->table('payment_types')->get()->getResultArray(); } catch (\Throwable $e) { $paymentTypes = []; }
        try { $nationalities = $db->table('nationalities')->get()->getResultArray(); } catch (\Throwable $e) { $nationalities = []; }
        try { $religions = $db->table('religions')->get()->getResultArray(); } catch (\Throwable $e) { $religions = []; }

        $nationalityList = [];
        if ($nationalities) {
            foreach ($nationalities as $n) {
                $name = $isArabic ? ($n['name_ar'] ?? $n['name_en']) : $n['name_en'];
                if ($name) { $nationalityList[] = ['value' => $n['name_en'], 'display' => $name]; }
            }
        }
        $religionList = [];
        if ($religions) {
            foreach ($religions as $r) {
                $name = $isArabic ? ($r['name_ar'] ?? $r['name_en']) : $r['name_en'];
                if ($name) { $religionList[] = ['value' => $r['name_en'], 'display' => $name]; }
            }
        }
        $classList = [];
        foreach ($classes as $c) {
            $name = $isArabic ? ($c['name_ar'] ?? $c['name_en']) : $c['name_en'];
            if ($name) { $classList[] = ['id' => $c['id'], 'display' => $name]; }
        }
        $sectionsList = [];
        foreach ($sections as $s) {
            $name = $isArabic ? ($s['name_ar'] ?? $s['name_en']) : $s['name_en'];
            if ($name) { $sectionsList[] = ['id' => $s['id'], 'class_id' => $s['class_id'] ?? null, 'display' => $name]; }
        }
        $paymentTypeList = [];
        foreach ($paymentTypes as $pt) {
            $name = $isArabic ? ($pt['description_ar'] ?? $pt['description_en']) : ($pt['description_en'] ?? '');
            if ($name) { $paymentTypeList[] = ['id' => $pt['id'], 'display' => $name]; }
        }
        $genderOptions = $isArabic ? 
            [['value' => 'Male', 'display' => 'ذكر'], ['value' => 'Female', 'display' => 'أنثى']] :
            [['value' => 'Male', 'display' => 'Male'], ['value' => 'Female', 'display' => 'Female']];
        $childOrderOptions = $isArabic ? 
            [['value' => '1st Child', 'display' => 'الطفل الأول'], ['value' => '2nd Child', 'display' => 'الطفل الثاني'], ['value' => '3rd Child', 'display' => 'الطفل الثالث'], ['value' => '4th Child+', 'display' => 'الطفل الرابع+']] :
            [['value' => '1st Child', 'display' => '1st Child'], ['value' => '2nd Child', 'display' => '2nd Child'], ['value' => '3rd Child', 'display' => '3rd Child'], ['value' => '4th Child+', 'display' => '4th Child+']];

        $prefill = [
            'name_en' => $app['name_en'] ?? '',
            'name_ar' => $app['name_ar'] ?? '',
            'gender' => $app['gender'] ?? 'Male',
            'mobile' => $app['mobile'] ?? '',
            'student_iqama' => $app['student_iqama'] ?? '',
            'address' => $app['address'] ?? '',
            'father_name' => $app['father_name'] ?? '',
            'occupation' => $app['occupation'] ?? '',
            'parent_iqama' => $app['parent_iqama'] ?? '',
            'telephone' => $app['telephone'] ?? '',
            // Prefer pre-selected class from application if present
            'class_id' => $app['class_id'] ?? null,
            // Include application id so Enrollment::save can update status
            'application_id' => $app['id'] ?? null,
        ];

        return view('enrollment/index', [
            'title' => lang('App.enrollment') . ' (from application) ',
            'schoolYears' => $schoolYears,
            'classes' => $classList,
            'sections' => $sectionsList,
            'paymentTypes' => $paymentTypeList,
            'genders' => $genderOptions,
            'religions' => $religionList,
            'nationalities' => $nationalityList,
            'childOrders' => $childOrderOptions,
            'prefill' => $prefill,
        ]);
    }
}

