<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Country extends Model
{
    protected $fillable = [
        'name',
        'slug',
        'flag_image',
        'hero_image',
        'short_description',
        'content',
        'page_sections',
        'seo_title',
        'seo_description',
        'is_active',
        'sort_order',
    ];

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

    // ── Auto-generate slug before saving ──────────────────────────
    protected static function booted(): void
    {
        static::creating(function (Country $country) {
            if (empty($country->slug)) {
                $country->slug = static::uniqueSlug($country->name);
            }
        });

        static::updating(function (Country $country) {
            if ($country->isDirty('name') && ! $country->isDirty('slug')) {
                $country->slug = static::uniqueSlug($country->name, $country->id);
            }
        });
    }

    public static function uniqueSlug(string $name, ?int $ignoreId = null): string
    {
        $base = Str::slug($name);
        $slug = $base;
        $i    = 1;

        while (
            static::where('slug', $slug)
                  ->when($ignoreId, fn ($q) => $q->where('id', '!=', $ignoreId))
                  ->exists()
        ) {
            $slug = "{$base}-{$i}";
            $i++;
        }

        return $slug;
    }

    // ── Scopes ────────────────────────────────────────────────────
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order')->orderBy('name');
    }

    // ── Helpers ───────────────────────────────────────────────────
    public function getFlagUrlAttribute(): ?string
    {
        return $this->flag_image ? asset('storage/' . $this->flag_image) : null;
    }

    public function getHeroUrlAttribute(): ?string
    {
        return $this->hero_image ? asset('storage/' . $this->hero_image) : null;
    }

    public function getPublicUrlAttribute(): string
    {
        return route('countries.show', $this->slug);
    }

    public static function defaultPageSections(?string $countryName = null): array
    {
        $country = $countryName ?: 'this destination';

        return [
            'highlights' => [
                'title' => "Why Study In {$country}",
                'subtitle' => "A practical overview to help you prepare a stronger {$country} study plan.",
                'items' => [
                    ['title' => 'Globally recognized degrees', 'text' => 'Study at institutions known for strong academic standards and graduate outcomes.'],
                    ['title' => 'Post-study opportunities', 'text' => 'Build a path from education to work experience through destination-specific options.'],
                    ['title' => 'Diverse student life', 'text' => 'Experience a multicultural environment with strong support for international students.'],
                    ['title' => 'Future-ready programs', 'text' => 'Choose courses aligned with market demand, innovation, and employability.'],
                ],
            ],
            'quick_facts' => [
                'title' => 'Quick Facts',
                'items' => [
                    ['label' => 'Typical intakes', 'value' => '2-3 intakes per year'],
                    ['label' => 'Popular levels', 'value' => 'Bachelor, Masters, Postgraduate'],
                    ['label' => 'Processing window', 'value' => 'Varies by institution and intake'],
                    ['label' => 'Part-time work', 'value' => 'As permitted by local regulations'],
                    ['label' => 'Teaching style', 'value' => 'Practical, research, project-focused'],
                    ['label' => 'Support services', 'value' => 'Academic and student wellbeing support'],
                ],
            ],
            'courses' => [
                'title' => 'Popular Study Areas',
                'items' => [
                    'Business and Management',
                    'Computer Science and IT',
                    'Engineering',
                    'Health and Nursing',
                    'Data Science and AI',
                    'Tourism and Hospitality',
                ],
            ],
            'costs' => [
                'title' => 'Cost Snapshot',
                'tuition' => 'Tuition depends on university, program, and level of study.',
                'living' => 'Living expenses vary by city, accommodation type, and lifestyle.',
                'visa' => 'Visa and health insurance costs are mandatory and depend on policy updates.',
                'scholarship' => 'Merit and university-based scholarships may reduce overall cost.',
            ],
            'requirements' => [
                'title' => 'Basic Requirements',
                'items' => [
                    'Academic transcripts and certificates',
                    'Valid passport',
                    'English proficiency score (IELTS/PTE/TOEFL or equivalent)',
                    'Statement of purpose and supporting documents',
                    'Financial documents as required',
                ],
            ],
            'timeline' => [
                'title' => 'Application Roadmap',
                'items' => [
                    'Profile evaluation and course-country matching',
                    'University shortlisting and document preparation',
                    'Application submission and offer follow-up',
                    'Tuition deposit, visa filing, and pre-departure support',
                ],
            ],
            'faq' => [
                'title' => 'Common Questions',
                'items' => [
                    ['q' => "How early should I apply for {$country}?", 'a' => 'Applying early improves seat availability and gives more time for visa preparation.'],
                    ['q' => 'Can I apply with a study gap?', 'a' => 'Yes, many students can apply with a gap if the profile and documentation are prepared properly.'],
                    ['q' => 'Do I need a scholarship to start?', 'a' => 'Not always. Scholarships help, but many students apply through budget-matched options.'],
                ],
            ],
            'cta' => [
                'title' => "Ready to Start Your {$country} Plan?",
                'text' => 'Book a free session with our counselors for course selection, budget planning, and next steps.',
                'button' => 'Book Free Consultation',
            ],
        ];
    }

    public function resolvedPageSections(): array
    {
        return array_replace_recursive(
            static::defaultPageSections($this->name),
            $this->page_sections ?? []
        );
    }

    public const DEMO_ITEMS = [
        ['name' => 'Australia',      'slug' => 'australia'],
        ['name' => 'United Kingdom', 'slug' => 'united-kingdom'],
        ['name' => 'Canada',         'slug' => 'canada'],
        ['name' => 'United States',  'slug' => 'united-states'],
        ['name' => 'Germany',        'slug' => 'germany'],
        ['name' => 'New Zealand',    'slug' => 'new-zealand'],
        ['name' => 'Japan',          'slug' => 'japan'],
        ['name' => 'Malaysia',       'slug' => 'malaysia'],
        ['name' => 'Ireland',        'slug' => 'ireland'],
        ['name' => 'Sweden',         'slug' => 'sweden'],
        ['name' => 'Netherlands',    'slug' => 'netherlands'],
        ['name' => 'South Korea',    'slug' => 'south-korea'],
    ];

    public static function ensureDemoItems(): void
    {
        $existingSlugs = static::pluck('slug')->flip();

        foreach (self::DEMO_ITEMS as $index => $item) {
            if ($existingSlugs->has($item['slug'])) {
                continue;
            }

            static::create([
                'name'       => $item['name'],
                'slug'       => $item['slug'],
                'is_active'  => true,
                'sort_order' => $index + 1,
            ]);
        }
    }
}
