<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CountrySectionsContent extends Model
{
    protected $fillable = ['content'];

    protected function casts(): array
    {
        return [
            'content' => 'array',
        ];
    }

    public static function defaults(): array
    {
        return [
            'subjects' => [
                'title_prefix' => 'Popular Subjects To Study in',
                'items' => [
                    ['id' => 'it', 'title' => 'Information Technology / Computer Science', 'image' => 'https://images.unsplash.com/photo-1518770660439-4636190af475?auto=format&fit=crop&w=1200&q=80'],
                    ['id' => 'engineering', 'title' => 'Engineering', 'image' => 'https://images.unsplash.com/photo-1581092160607-ee22621dd758?auto=format&fit=crop&w=1200&q=80'],
                    ['id' => 'business', 'title' => 'Business & Management', 'image' => 'https://images.unsplash.com/photo-1552664730-d307ca884978?auto=format&fit=crop&w=1200&q=80'],
                    ['id' => 'nursing', 'title' => 'Nursing & Health Sciences', 'image' => 'https://images.unsplash.com/photo-1576091160550-2173dba999ef?auto=format&fit=crop&w=1200&q=80'],
                ],
                'country_map' => [],
            ],
            'process' => [
                'title' => 'Admission & Visa Process',
                'subtitle' => 'A clear step-by-step path from counseling to visa approval.',
                'items' => [
                    ['id' => 'counseling', 'title' => 'Free Personalized Counseling', 'text' => 'Profile review and country-course matching based on your goal and budget.', 'image' => 'https://images.unsplash.com/photo-1521791136064-7986c2920216?auto=format&fit=crop&w=1000&q=80'],
                    ['id' => 'admission', 'title' => 'Admission Confirmation', 'text' => 'University shortlisting, application submission, and offer follow-up.', 'image' => 'https://images.unsplash.com/photo-1523240795612-9a054b0db644?auto=format&fit=crop&w=1000&q=80'],
                    ['id' => 'visa_docs', 'title' => 'Prepare Documents for Visa', 'text' => 'Financial and supporting document checklist with expert review.', 'image' => 'https://images.unsplash.com/photo-1542744173-8e7e53415bb0?auto=format&fit=crop&w=1000&q=80'],
                    ['id' => 'visa_apply', 'title' => 'Apply for the Visa', 'text' => 'Complete visa filing and final pre-departure guidance.', 'image' => 'https://images.unsplash.com/photo-1450101499163-c8848c66ca85?auto=format&fit=crop&w=1000&q=80'],
                ],
                'country_map' => [],
            ],
            'entry' => [
                'title' => 'Entry Requirements',
                'rotate_ms' => 3500,
                'items' => [
                    ['id' => 'foundation', 'title' => 'Foundation Program', 'text' => 'Completion of SSC/O Levels equivalent pathway.', 'icon' => 'F', 'image' => 'https://images.unsplash.com/photo-1523050854058-8df90110c9f1?auto=format&fit=crop&w=800&q=80'],
                    ['id' => 'diploma', 'title' => 'Diploma Program', 'text' => 'Academic: HSC/A-Level. IELTS/PTE as required by institution.', 'icon' => 'D', 'image' => 'https://images.unsplash.com/photo-1434030216411-0b793f4b4173?auto=format&fit=crop&w=800&q=80'],
                    ['id' => 'bachelor', 'title' => "Bachelor's Program", 'text' => 'Academic qualifications and English score based on course criteria.', 'icon' => 'B', 'image' => 'https://images.unsplash.com/photo-1513258496099-48168024aec0?auto=format&fit=crop&w=800&q=80'],
                    ['id' => 'masters', 'title' => "Master's Program", 'text' => 'Recognized bachelor degree and required IELTS/PTE/TOEFL score.', 'icon' => 'M', 'image' => 'https://images.unsplash.com/photo-1523240794102-9a054b0db644?auto=format&fit=crop&w=800&q=80'],
                ],
                'country_map' => [],
            ],
            'intakes' => [
                'title' => 'Major Admission Intakes',
                'items' => [
                    ['id' => 'feb', 'title' => 'February Intake / Mid Year', 'text' => 'Best for students preparing early documents and visa.'],
                    ['id' => 'july', 'title' => 'July Intake / Second Main', 'text' => 'Popular intake with broad program availability.'],
                    ['id' => 'nov', 'title' => 'November Intake / Limited', 'text' => 'Available in selected institutions and courses.'],
                ],
                'country_map' => [],
            ],
        ];
    }

    public static function getContent(): array
    {
        $row = static::query()->first();
        $stored = $row?->content ?? [];

        return array_replace_recursive(static::defaults(), $stored);
    }

    public static function saveContent(array $content): void
    {
        static::query()->updateOrCreate(
            ['id' => 1],
            ['content' => $content]
        );
    }

    public static function resolveForCountry(string $slug, string $countryName): array
    {
        $content = static::getContent();

        return [
            'subjects' => [
                'title' => ($content['subjects']['title_prefix'] ?? 'Popular Subjects To Study in') . ' ' . $countryName,
                'items' => static::mappedItems($content['subjects'] ?? [], $slug),
            ],
            'process' => [
                'title' => $content['process']['title'] ?? 'Admission & Visa Process',
                'subtitle' => $content['process']['subtitle'] ?? '',
                'items' => static::mappedItems($content['process'] ?? [], $slug),
            ],
            'entry' => [
                'title' => $content['entry']['title'] ?? 'Entry Requirements',
                'rotate_ms' => max((int) ($content['entry']['rotate_ms'] ?? 3500), 1000),
                'items' => static::mappedItems($content['entry'] ?? [], $slug),
            ],
            'intakes' => [
                'title' => $content['intakes']['title'] ?? 'Major Admission Intakes',
                'items' => static::mappedItems($content['intakes'] ?? [], $slug),
            ],
        ];
    }

    private static function mappedItems(array $section, string $slug): array
    {
        $items = array_values(array_filter($section['items'] ?? [], fn ($item) => !empty($item['title'])));
        $map = $section['country_map'][$slug] ?? [];

        if (empty($map)) {
            return $items;
        }

        $byId = [];
        foreach ($items as $item) {
            $id = trim((string) ($item['id'] ?? ''));
            if ($id !== '') {
                $byId[$id] = $item;
            }
        }

        $selected = [];
        foreach ($map as $id) {
            $id = trim((string) $id);
            if (isset($byId[$id])) {
                $selected[] = $byId[$id];
            }
        }

        return $selected ?: $items;
    }
}
