<?php
namespace App\Controllers;

use Config\Database;

class Enrollment extends BaseController
{
    public function index()
    {
        $db = Database::connect();
        
        // Get current locale to determine which name column to use
        $locale = service('language')->getLocale();
        $isArabic = ($locale === 'ar');
        $nameCol = $isArabic ? 'name_ar' : 'name_en';

        $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 = []; }

        // Create localized lists using appropriate name column, with fallback to English
        $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'], // Always use English as value for database storage
                        'display' => $name
                    ];
                }
            }
        } else {
            // Fallback list
            $fallbackNationalities = $isArabic ? 
                ['السعودية', 'مصر', 'باكستان', 'الهند', 'بنغلاديش', 'أخرى'] : 
                ['Saudi Arabia', 'Egypt', 'Pakistan', 'India', 'Bangladesh', 'Other'];
            foreach ($fallbackNationalities as $i => $name) {
                $englishNames = ['Saudi Arabia', 'Egypt', 'Pakistan', 'India', 'Bangladesh', 'Other'];
                $nationalityList[] = [
                    'value' => $englishNames[$i],
                    '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'], // Always use English as value for database storage
                        'display' => $name
                    ];
                }
            }
        } else {
            // Fallback list
            $fallbackReligions = $isArabic ? 
                ['مسلم', 'مسيحي', 'أخرى'] : 
                ['Muslim', 'Christian', 'Other'];
            foreach ($fallbackReligions as $i => $name) {
                $englishNames = ['Muslim', 'Christian', 'Other'];
                $religionList[] = [
                    'value' => $englishNames[$i],
                    'display' => $name
                ];
            }
        }

        // Create localized classes list
        $classList = [];
        foreach ($classes as $c) {
            $name = $isArabic ? ($c['name_ar'] ?? $c['name_en']) : $c['name_en'];
            if ($name) {
                $classList[] = [
                    'id' => $c['id'],
                    'name_en' => $c['name_en'],
                    'name_ar' => $c['name_ar'] ?? '',
                    'display' => $name
                ];
            }
        }

        // Create localized sections list
        $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,
                    'name_en' => $s['name_en'],
                    'name_ar' => $s['name_ar'] ?? '',
                    'display' => $name
                ];
            }
        }

        // Localized gender options
        $genderOptions = $isArabic ? 
            [['value' => 'Male', 'display' => 'ذكر'], ['value' => 'Female', 'display' => 'أنثى']] :
            [['value' => 'Male', 'display' => 'Male'], ['value' => 'Female', 'display' => 'Female']];

        // Localized child order options
        $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+']];

        // Localized payment type options
        $paymentTypeList = [];
        foreach ($paymentTypes as $pt) {
            $name = $isArabic ? ($pt['description_ar'] ?? $pt['description_en']) : ($pt['description_en'] ?? '');
            if ($name) {
                $paymentTypeList[] = [
                    'id' => $pt['id'],
                    'display' => $name
                ];
            }
        }

        $data = [
            // Localized page title
            'title' => lang('App.enrollment'),
            'schoolYears' => $schoolYears,
            'classes' => $classList,
            'sections' => $sectionsList,
            'paymentTypes' => $paymentTypeList,
            // Option lists for form controls
            'genders' => $genderOptions,
            'religions' => $religionList,
            'nationalities' => $nationalityList,
            'childOrders' => $childOrderOptions,
        ];

        return view('enrollment/index', $data);
    }

    public function show($id)
    {
        $db = Database::connect();
        // ... existing code to load $enrollment and related entities ...

        return view('enrollment/show', [
            // Localized detail title prefix
            'title' => lang('App.enrollment') . ' ' . ($enrollment['enrollment_id'] ?? ''),
            'enrollment' => $enrollment,
            'student' => $student,
            'class' => $class,
            'section' => $section,
            'paymentType' => $paymentType,
            'schoolYear' => $schoolYear,
        ]);
    }

    public function save()
    {
        $db = Database::connect();
        $request = $this->request;
        $db->transStart();
        try {
            $photoPath = null;
            $photo = $request->getFile('photo');
            if ($photo && $photo->isValid() && !$photo->hasMoved()) {
                $newName = $photo->getRandomName();
                $photo->move(WRITEPATH . 'uploads/photos', $newName);
                $photoPath = 'uploads/photos/' . $newName;
            }

            // Create student record
            // Map names from form: name_en -> first/last, name_ar -> name_ar
            $nameEn = trim((string) $request->getPost('name_en'));
            $nameAr = trim((string) $request->getPost('name_ar'));
            $firstName = '';
            $lastName = '';
            if ($nameEn !== '') {
                $parts = preg_split('/\s+/', $nameEn);
                $firstName = $parts[0] ?? '';
                $lastName = count($parts) > 1 ? implode(' ', array_slice($parts, 1)) : '';
            }
            $studentCode = 'STD-' . date('Ymd-His');
            // Store only filename for photo to match existing photo serving route
            $photoFilename = $photoPath ? basename($photoPath) : null;
            $studentData = [
                'student_id' => $studentCode,
                'first_name' => $firstName,
                'last_name' => $lastName,
                'name_ar' => ($nameAr !== '' ? $nameAr : null),
                'gender' => ($request->getPost('gender') === 'Female' ? 'F' : 'M'),
                'dob' => $request->getPost('dob_g') ?: null,
                'nationality' => $request->getPost('nationality') ?: null,
                'religion' => $request->getPost('religion') ?: null,
                'mobile' => $request->getPost('mobile') ?: null,
                'student_iqama' => $request->getPost('student_iqama') ?: null,
                'parent_name' => $request->getPost('father_name') ?: null,
                'parent_phone' => $request->getPost('telephone') ?: null,
                'occupation' => $request->getPost('occupation') ?: null,
                'parent_iqama' => $request->getPost('parent_iqama') ?: null,
                'iqama_issue_date' => $request->getPost('iqama_issue_date') ?: null,
                'iqama_expiry_date' => $request->getPost('iqama_expiry_date') ?: null,
                'place_of_issue' => $request->getPost('place_of_issue') ?: null,
                'company_name' => $request->getPost('company_name') ?: null,
                'address' => $request->getPost('address') ?: null,
                'photo' => $photoFilename,
            ];
            $db->table('students')->insert($studentData);
            $studentId = (int) $db->insertID();

            // Insert enrollment
            $enrollmentId = 'ENR-' . date('Ymd-His');
            $plan = $request->getPost('plan') ?: '1';
            $paymentTypeId = $request->getPost('payment_type_id');

            $enrollData = [
                'enrollment_id' => $enrollmentId,
                'school_year_id' => (int) $request->getPost('school_year_id'),
                'student_id' => $studentId,
                'class_id' => (int) $request->getPost('class_id'),
                'section_id' => (int) $request->getPost('section_id'),
                'payment_type_id' => $paymentTypeId ? (int) $paymentTypeId : null,
                'plan' => in_array($plan, ['10','4','2','1'], true) ? $plan : '1',
                'tuition_total' => 0,
            ];
            $db->table('enrollments')->insert($enrollData);

            // If coming from a pending application, mark it Approved
            $applicationId = (int) ($request->getPost('application_id') ?? 0);
            if ($applicationId > 0) {
                try {
                    $db->table('applications')->where('id', $applicationId)->update(['status' => 'Approved']);
                } catch (\Throwable $e) { /* ignore status update errors */ }
            }

            $db->transComplete();

            return redirect()->to('/enrollment')
                ->with('success', 'Enrollment saved successfully. Student No: ' . $studentCode . ' | Enrollment ID: ' . $enrollmentId)
                ->with('enrollment_id', $enrollmentId)
                ->with('student_code', $studentCode);
        } catch (\Throwable $e) {
            $db->transRollback();
            return redirect()->back()->with('error', 'Failed to save enrollment: ' . $e->getMessage())->withInput();
        }
    }

    public function print($enrollmentId)
    {
        $db = Database::connect();
        $enrollment = $student = $class = $section = $paymentType = [];
        try {
            $enrollment = $db->table('enrollments')->where('enrollment_id', (string) $enrollmentId)->get()->getRowArray();
        } catch (\Throwable $e) { $enrollment = []; }
        if (! $enrollment) {
            // If enrollment record is missing, quietly return to enrollment form
            // This avoids flashing an error when admin is still registering.
            return redirect()->to('/enrollment');
        }
        try {
            $student = $db->table('students')->where('id', (int) ($enrollment['student_id'] ?? 0))->get()->getRowArray();
        } catch (\Throwable $e) { $student = []; }
        try { $class = $db->table('classes')->where('id', (int) ($enrollment['class_id'] ?? 0))->get()->getRowArray(); } catch (\Throwable $e) { $class = []; }
        try { $section = $db->table('sections')->where('id', (int) ($enrollment['section_id'] ?? 0))->get()->getRowArray(); } catch (\Throwable $e) { $section = []; }
        try { $paymentType = $db->table('payment_types')->where('id', (int) ($enrollment['payment_type_id'] ?? 0))->get()->getRowArray(); } catch (\Throwable $e) { $paymentType = []; }
        // Load school year
        $schoolYear = [];
        try { $schoolYear = $db->table('school_years')->where('id', (int) ($enrollment['school_year_id'] ?? 0))->get()->getRowArray(); } catch (\Throwable $e) { $schoolYear = []; }

        return view('enrollment/print', [
            'title' => lang('App.enrollment') . ' ' . ($enrollment['enrollment_id'] ?? ''),
            'enrollment' => $enrollment,
            'student' => $student,
            'class' => $class,
            'section' => $section,
            'paymentType' => $paymentType,
            'schoolYear' => $schoolYear,
        ]);
    }
}