<?php
namespace App\Database\Seeds;

use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Database\Seeder;

class BackfillArabicSeeder extends Seeder
{
    /** @var BaseConnection */
    protected $db;

    public function run()
    {
        $db = \Config\Database::connect();

        // Nationalities - targeted backfill for commonly used entries
        $pairs = [
            'Saudi Arabia' => 'السعودية',
            'Egypt' => 'مصر',
            'Pakistan' => 'باكستان',
            'India' => 'الهند',
            'Bangladesh' => 'بنغلاديش',
            'Other' => 'أخرى',
            'Portugal' => 'البرتغال',
            'Qatar' => 'قطر',
            'Romania' => 'رومانيا',
            'Russia' => 'روسيا',
            'Rwanda' => 'رواندا',
            'Saint Kitts and Nevis' => 'سانت كيتس ونيفيس',
            'Saint Lucia' => 'سانت لوسيا',
            'Saint Vincent and the Grenadines' => 'سانت فينسنت والغرينادين',
            'Samoa' => 'ساموا',
            'San Marino' => 'سان مارينو',
            'Sao Tome and Principe' => 'ساو تومي وبرينسيبي'
        ];
        foreach ($pairs as $en => $ar) {
            $this->updateIfExists($db, 'nationalities', 'name_en', $en, ['name_ar' => $ar]);
        }

        // If many nationalities still have empty Arabic names, refresh them from the main seeder
        try {
            $builder = $db->table('nationalities');
            $builder->groupStart()->where('name_ar', null)->groupEnd()->delete();
            $builder = $db->table('nationalities');
            $builder->groupStart()->where('name_ar', '')->groupEnd()->delete();
            // Re-seed full list with Arabic names where missing
            $this->call('NationalitiesSeeder');
        } catch (\Throwable $e) {
            // ignore
        }
 
        // Religions
        $this->updateIfExists($db, 'religions', 'name_en', 'Muslim', ['name_ar' => 'مسلم']);
        $this->updateIfExists($db, 'religions', 'name_en', 'Christian', ['name_ar' => 'مسيحي']);
        $this->updateIfExists($db, 'religions', 'name_en', 'Other', ['name_ar' => 'أخرى']);

        // Classes
        $this->updateIfExists($db, 'classes', 'name_en', 'Nursery', ['name_ar' => 'روضة']);
        $this->updateIfExists($db, 'classes', 'name_en', 'Kindergarten', ['name_ar' => 'رياض الأطفال']);
        $this->updateIfExists($db, 'classes', 'name_en', 'Pre-K', ['name_ar' => 'ما قبل الروضة']);
        // Common Grades (add only if present)
        for ($i = 1; $i <= 12; $i++) {
            $en = 'Grade ' . $i;
            $ar = 'الصف ' . $i;
            $this->updateIfExists($db, 'classes', 'name_en', $en, ['name_ar' => $ar]);
        }

        // Sections
        $this->updateIfExists($db, 'sections', 'name_en', 'Boys', ['name_ar' => 'بنين']);
        $this->updateIfExists($db, 'sections', 'name_en', 'Girls', ['name_ar' => 'بنات']);
        // If sections like A/B/C exist, ensure Arabic equivalents
        $this->updateIfExists($db, 'sections', 'name_en', 'Section A', ['name_ar' => 'الشعبة أ']);
        $this->updateIfExists($db, 'sections', 'name_en', 'Section B', ['name_ar' => 'الشعبة ب']);
        $this->updateIfExists($db, 'sections', 'name_en', 'Section C', ['name_ar' => 'الشعبة ج']);

        // Payment Types
        $this->updateIfExists($db, 'payment_types', 'description_en', 'Tuition', ['description_ar' => 'رسوم دراسية']);
        $this->updateIfExists($db, 'payment_types', 'description_en', 'Books', ['description_ar' => 'كتب']);
        $this->updateIfExists($db, 'payment_types', 'description_en', 'Miscellaneous', ['description_ar' => 'متفرقات']);
        $this->updateIfExists($db, 'payment_types', 'description_en', 'Registration Fee', ['description_ar' => 'رسوم التسجيل']);
    }

    /**
     * Update a table row when the English column matches and Arabic column is empty or different.
     */
    private function updateIfExists(BaseConnection $db, string $table, string $colEn, string $matchEn, array $setAr): void
    {
        try {
            $builder = $db->table($table);
            $row = $builder->where($colEn, $matchEn)->get()->getRowArray();
            if ($row) {
                // Only set Arabic if empty or not set
                $shouldUpdate = false;
                foreach ($setAr as $key => $val) {
                    if (!isset($row[$key]) || trim((string)$row[$key]) === '') {
                        $shouldUpdate = true; break;
                    }
                }
                if ($shouldUpdate) {
                    $builder->where('id', $row['id'])->update($setAr);
                }
            }
        } catch (\Throwable $e) {
            // ignore
        }
    }
}
