<?php

namespace Database\Seeders;

use App\Models\AdmissionGuide;
use App\Models\Application;
use App\Models\BlogCategory;
use App\Models\BlogPost;
use App\Models\ConsultationRequest;
use App\Models\Country;
use App\Models\Document;
use App\Models\Exam;
use App\Models\Faq;
use App\Models\NewsletterSubscription;
use App\Models\PartnerUniversity;
use App\Models\Program as StudyProgram;
use App\Models\Scholarship;
use App\Models\Service;
use App\Models\Setting;
use App\Models\Testimonial;
use App\Models\University;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        User::unguarded(function (): void {
            $password = Hash::make('password');

            $admin = User::updateOrCreate(
                ['email' => 'admin@example.com'],
                [
                    'name' => 'Admin',
                    'password' => $password,
                    'email_verified_at' => now(),
                    'role' => 'admin',
                ],
            );

            $studentNames = [
                'Ayesha Khan', 'Bilal Ahmed', 'Sara Malik', 'Hamza Ali', 'Fatima Noor',
                'Usman Tariq', 'Maham Raza', 'Danish Iqbal', 'Hina Shah', 'Zain Abbas',
                'Maryam Saeed', 'Farhan Qureshi', 'Iqra Javed', 'Ahmed Rauf', 'Sana Yousaf',
                'Omar Siddiqui', 'Nimra Aslam', 'Taha Mahmood', 'Laiba Hussain', 'Rehan Mir',
            ];

            $users = collect($studentNames)->map(fn (string $name, int $index) => User::updateOrCreate(
                ['email' => 'student'.($index + 1).'@example.com'],
                [
                    'name' => $name,
                    'password' => $password,
                    'email_verified_at' => now()->subDays($index),
                    'role' => 'student',
                ],
            ))->prepend($admin)->values();

            $countriesData = [
                ['United States', 'USA', 'Flexible programs, strong research funding, and extensive campus choices.'],
                ['United Kingdom', 'GBR', 'Shorter degree routes with globally recognized universities.'],
                ['Canada', 'CAN', 'Popular destination with post-study work and immigration pathways.'],
                ['Australia', 'AUS', 'Career-focused programs and welcoming international student cities.'],
                ['Germany', 'DEU', 'Research-led public universities and many low-tuition options.'],
                ['France', 'FRA', 'Business, arts, engineering, and hospitality programs in major student cities.'],
                ['Italy', 'ITA', 'Affordable study routes in design, architecture, medicine, and engineering.'],
                ['Netherlands', 'NLD', 'English-taught degrees with practical learning and international classrooms.'],
                ['Sweden', 'SWE', 'Innovation-focused education with strong sustainability programs.'],
                ['Norway', 'NOR', 'High-quality public education and research-intensive institutions.'],
                ['Finland', 'FIN', 'Modern universities with strengths in technology and education.'],
                ['Ireland', 'IRL', 'Tech, business, and health science programs with work opportunities.'],
                ['New Zealand', 'NZL', 'Smaller campuses, safe cities, and applied learning pathways.'],
                ['Japan', 'JPN', 'Technology, business, and culture-rich international degree options.'],
                ['South Korea', 'KOR', 'STEM and creative programs with growing scholarship support.'],
                ['China', 'CHN', 'Large scholarship ecosystem and expanding English-taught programs.'],
                ['Malaysia', 'MYS', 'Affordable regional study hub with branch campuses.'],
                ['United Arab Emirates', 'ARE', 'International campuses and business-focused degrees close to home.'],
                ['Turkey', 'TUR', 'Government scholarships and diverse public/private universities.'],
                ['Saudi Arabia', 'SAU', 'Growing higher education investment and science-focused institutions.'],
            ];

            $countries = collect($countriesData)->map(fn (array $country, int $index) => Country::updateOrCreate(
                ['code' => $country[1]],
                [
                    'name' => $country[0],
                    'slug' => Str::slug($country[0]),
                    'is_popular' => $index < 8,
                    'description' => $country[2],
                    'flag_path' => 'flags/'.strtolower($country[1]).'.svg',
                    'is_active' => true,
                ],
            ))->values();

            $universitiesData = [
                'Harvard University', 'University of Oxford', 'University of Toronto', 'University of Melbourne',
                'Technical University of Munich', 'Sorbonne University', 'University of Bologna', 'Delft University of Technology',
                'Lund University', 'University of Oslo', 'University of Helsinki', 'Trinity College Dublin',
                'University of Auckland', 'University of Tokyo', 'Seoul National University', 'Tsinghua University',
                'University of Malaya', 'Khalifa University', 'Istanbul University', 'King Saud University',
            ];

            $universities = collect($universitiesData)->map(fn (string $name, int $index) => University::updateOrCreate(
                ['slug' => Str::slug($name)],
                [
                    'name' => $name,
                    'description' => $name.' offers international student support, strong academic departments, and guided admission routes.',
                    'location' => $countries[$index]->name.' Campus',
                    'ranking' => $index + 1,
                    'website' => 'https://www.'.Str::slug($name).'.edu',
                    'logo_path' => 'universities/'.Str::slug($name).'.png',
                    'country_id' => $countries[$index]->id,
                    'featured' => $index < 10,
                    'is_active' => true,
                ],
            ))->values();

            $programTitles = [
                'Computer Science', 'Business Administration', 'Data Science', 'Mechanical Engineering',
                'Public Health', 'International Relations', 'Artificial Intelligence', 'Civil Engineering',
                'Finance', 'Architecture', 'Cyber Security', 'Biomedical Sciences', 'Marketing Analytics',
                'Renewable Energy Engineering', 'Psychology', 'Education Leadership', 'Supply Chain Management',
                'Hospitality Management', 'Software Engineering', 'Environmental Science',
            ];

            $programs = collect($programTitles)->map(fn (string $title, int $index) => StudyProgram::updateOrCreate(
                [
                    'title' => $title,
                    'university_id' => $universities[$index]->id,
                ],
                [
                    'degree_level' => ['bachelor', 'master', 'phd'][$index % 3],
                    'duration' => [36, 24, 48][$index % 3].' months',
                    'fee' => 8500 + ($index * 1250),
                    'description' => $title.' prepares students for international careers through practical coursework, projects, and academic mentoring.',
                    'is_active' => true,
                    'application_deadline' => now()->addMonths($index + 2)->toDateString(),
                ],
            ))->values();

            $examsData = [
                ['IELTS Academic', 'IELTS', 'language', 165, 250, 24, 9, 6],
                ['TOEFL iBT', 'TOEFL', 'language', 116, 245, 24, 120, 80],
                ['PTE Academic', 'PTE', 'language', 120, 230, 24, 90, 58],
                ['Duolingo English Test', 'DET', 'language', 60, 65, 24, 160, 105],
                ['GRE General Test', 'GRE', 'graduate', 118, 220, 60, 340, 300],
                ['GMAT Focus Edition', 'GMAT', 'graduate', 135, 275, 60, 805, 555],
                ['SAT', 'SAT', 'undergraduate', 180, 111, 60, 1600, 1150],
                ['ACT', 'ACT', 'undergraduate', 175, 68, 60, 36, 24],
                ['MCAT', 'MCAT', 'professional', 450, 335, 36, 528, 500],
                ['LSAT', 'LSAT', 'professional', 140, 222, 60, 180, 150],
                ['UKCAT', 'UKCAT', 'professional', 120, 140, 12, 3600, 2400],
                ['LNAT', 'LNAT', 'undergraduate', 135, 75, 12, 42, 23],
                ['TestDaF', 'TESTDAF', 'language', 190, 215, 24, 20, 16],
                ['DELF B2', 'DELF', 'language', 150, 160, 999, 100, 50],
                ['TOPIK II', 'TOPIK', 'language', 180, 55, 24, 300, 150],
                ['JLPT N2', 'JLPT', 'language', 155, 45, 999, 180, 90],
                ['YOS', 'YOS', 'undergraduate', 120, 50, 12, 100, 60],
                ['Gaokao International', 'GAOKAO-INT', 'undergraduate', 240, 90, 12, 750, 500],
                ['GATE', 'GATE', 'graduate', 180, 25, 36, 100, 35],
                ['EmSAT English', 'EMSAT', 'language', 120, 75, 18, 2000, 1250],
            ];

            $exams = collect($examsData)->map(fn (array $exam, int $index) => Exam::updateOrCreate(
                ['code' => $exam[1]],
                [
                    'name' => $exam[0],
                    'slug' => Str::slug($exam[0]),
                    'short_description' => $exam[0].' is commonly requested for international admissions and scholarship review.',
                    'full_description' => 'Students use '.$exam[0].' scores to support applications, demonstrate readiness, and meet university entry criteria.',
                    'type' => $exam[2],
                    'duration' => $exam[3],
                    'fee' => $exam[4],
                    'validity_months' => $exam[5],
                    'total_score' => $exam[6],
                    'passing_score' => $exam[7],
                    'website_url' => 'https://example.com/exams/'.Str::slug($exam[0]),
                    'sample_paper_url' => 'https://example.com/exams/'.Str::slug($exam[0]).'/sample',
                    'registration_url' => 'https://example.com/exams/'.Str::slug($exam[0]).'/register',
                    'sections' => ['Reading', 'Writing', 'Listening', 'Speaking'],
                    'is_popular' => $index < 10,
                    'is_active' => true,
                    'views' => 1000 + ($index * 137),
                    'order' => $index + 1,
                ],
            ))->values();

            $scholarships = collect($programTitles)->map(fn (string $title, int $index) => Scholarship::updateOrCreate(
                ['slug' => Str::slug($title.' international scholarship')],
                [
                    'title' => $title.' International Scholarship',
                    'is_fully_funded' => $index % 4 === 0,
                    'description' => 'Merit-based funding for students applying to '.$programs[$index]->title.' at '.$universities[$index]->name.'.',
                    'eligibility' => 'Strong academic record, complete documents, admission eligibility, and proof of English or required entrance exam.',
                    'deadline' => now()->addMonths($index + 3)->toDateString(),
                    'amount' => $index % 4 === 0 ? null : 2500 + ($index * 600),
                    'country_id' => $countries[$index]->id,
                    'university_id' => $universities[$index]->id,
                    'program_level' => $programs[$index]->degree_level,
                    'created_by' => $admin->id,
                    'scholarship_type' => ['merit', 'need-based', 'research', 'country-specific'][$index % 4],
                    'status' => ['published', 'published', 'draft', 'expired'][$index % 4],
                    'meta_description' => 'Funding details, eligibility, and deadline for '.$title.' applicants.',
                ],
            ))->values();

            $scholarships->each(function (Scholarship $scholarship, int $index) use ($exams): void {
                $scholarship->exams()->syncWithoutDetaching([
                    $exams[$index]->id => ['minimum_score' => $exams[$index]->passing_score],
                    $exams[($index + 1) % $exams->count()]->id => ['minimum_score' => $exams[($index + 1) % $exams->count()]->passing_score],
                ]);
            });

            $applications = collect(range(0, 19))->map(fn (int $index) => Application::updateOrCreate(
                [
                    'user_id' => $users[$index + 1]->id,
                    'program_id' => $programs[$index]->id,
                ],
                [
                    'scholarship_id' => $scholarships[$index]->id,
                    'status' => ['draft', 'submitted', 'under_review', 'approved', 'rejected', 'visa_processing'][$index % 6],
                    'submitted_at' => $index % 6 === 0 ? null : now()->subDays(30 - $index),
                    'counselor_notes' => 'Counselor reviewed academic documents and next admission action for applicant '.($index + 1).'.',
                    'counselor_id' => $admin->id,
                ],
            ))->values();

            $documentTypes = ['passport', 'transcript', 'cv', 'motivation_letter', 'recommendation_letter', 'language_certificate', 'other'];

            collect(range(0, 19))->each(fn (int $index) => Document::updateOrCreate(
                [
                    'application_id' => $applications[$index]->id,
                    'type' => $documentTypes[$index % count($documentTypes)],
                ],
                [
                    'user_id' => $applications[$index]->user_id,
                    'file_path' => 'documents/application-'.$applications[$index]->id.'/'.$documentTypes[$index % count($documentTypes)].'.pdf',
                    'verified' => $index % 3 !== 0,
                    'uploaded_at' => now()->subDays(20 - $index),
                ],
            ));

            collect(range(0, 19))->each(fn (int $index) => AdmissionGuide::updateOrCreate(
                ['slug' => Str::slug($countries[$index]->name.' admission guide')],
                [
                    'title' => $countries[$index]->name.' Admission Guide',
                    'country_id' => $countries[$index]->id,
                    'content' => [
                        ['step_title' => 'Choose a program', 'step_body' => 'Compare entry requirements, tuition, deadlines, and career outcomes.', 'checklist_items' => ['Shortlist programs', 'Check degree level', 'Review deadlines']],
                        ['step_title' => 'Prepare documents', 'step_body' => 'Collect academic, identity, financial, and language documents before applying.', 'checklist_items' => ['Passport', 'Transcripts', 'Statement of purpose']],
                        ['step_title' => 'Submit application', 'step_body' => 'Apply through the university portal and track all admission responses.', 'checklist_items' => ['Complete form', 'Pay fee', 'Save confirmation']],
                    ],
                    'meta_description' => 'Step-by-step admission guidance for studying in '.$countries[$index]->name.'.',
                ],
            ));

            $categoryNames = [
                'Admissions', 'Scholarships', 'Visa Guidance', 'Study Abroad', 'Career Planning',
                'Student Life', 'Language Tests', 'University Rankings', 'Application Tips', 'Finance',
                'Accommodation', 'Part-Time Work', 'Post-Study Work', 'Country Guides', 'Exam Preparation',
                'Document Checklist', 'Interview Tips', 'Research Degrees', 'Undergraduate Study', 'Graduate Study',
            ];

            $categories = collect($categoryNames)->map(fn (string $name) => BlogCategory::updateOrCreate(
                ['slug' => Str::slug($name)],
                ['name' => $name],
            ))->values();

            collect(range(0, 19))->each(fn (int $index) => BlogPost::updateOrCreate(
                ['slug' => Str::slug($categoryNames[$index].' for international students')],
                [
                    'title' => $categoryNames[$index].' for International Students',
                    'is_published' => $index % 5 !== 0,
                    'content' => 'This article explains practical '.$categoryNames[$index].' steps for students planning international admissions with Sasi guidance.',
                    'featured_image' => 'blog/'.Str::slug($categoryNames[$index]).'.jpg',
                    'author_id' => $admin->id,
                    'category_id' => $categories[$index]->id,
                    'published_at' => now()->subDays($index + 1),
                    'views' => 250 + ($index * 41),
                ],
            ));

            collect(range(0, 19))->each(fn (int $index) => Testimonial::updateOrCreate(
                ['student_name' => $studentNames[$index]],
                [
                    'is_featured' => $index < 8,
                    'student_photo' => 'testimonials/student-'.($index + 1).'.jpg',
                    'university' => $universities[$index]->name,
                    'content' => 'Sasi helped me shortlist universities, prepare documents, and submit my application with confidence.',
                    'rating' => 4 + ($index % 2),
                    'is_approved' => true,
                ],
            ));

            $serviceTitles = [
                'University Shortlisting', 'Scholarship Matching', 'Admission Application Review', 'Visa File Preparation',
                'Statement of Purpose Editing', 'Recommendation Letter Guidance', 'IELTS Preparation Plan', 'Interview Coaching',
                'Document Verification', 'Financial Planning', 'Course Selection', 'Career Counseling',
                'Pre-Departure Briefing', 'Accommodation Guidance', 'Application Tracking', 'Research Proposal Review',
                'Portfolio Review', 'Transfer Admission Support', 'Post-Admission Support', 'Parent Counseling',
            ];

            collect($serviceTitles)->each(fn (string $title, int $index) => Service::updateOrCreate(
                ['slug' => Str::slug($title)],
                [
                    'title' => $title,
                    'icon_class' => ['fa-solid fa-graduation-cap', 'fa-solid fa-passport', 'fa-solid fa-file-lines', 'fa-solid fa-comments'][$index % 4],
                    'short_description' => 'Professional support for '.$title.'.',
                    'full_description' => 'Our counselors provide structured guidance, document checks, deadlines, and follow-up for '.$title.'.',
                    'order' => $index + 1,
                ],
            ));

            collect(range(0, 19))->each(fn (int $index) => Faq::updateOrCreate(
                ['question' => 'What should I know about '.$categoryNames[$index].'?'],
                [
                    'answer' => 'You should prepare early, confirm official requirements, and keep all supporting documents ready before the deadline.',
                    'order' => $index + 1,
                    'category' => $categoryNames[$index],
                ],
            ));

            collect(range(0, 19))->each(fn (int $index) => ConsultationRequest::updateOrCreate(
                ['email' => 'lead'.($index + 1).'@example.com'],
                [
                    'name' => $studentNames[$index],
                    'phone' => '+92-300-555-'.str_pad((string) (1000 + $index), 4, '0', STR_PAD_LEFT),
                    'message' => 'I need guidance for '.$programs[$index]->title.' admission and scholarship options in '.$countries[$index]->name.'.',
                    'preferred_date' => now()->addDays($index + 1)->toDateString(),
                    'status' => ['pending', 'contacted', 'completed'][$index % 3],
                ],
            ));

            collect($universitiesData)->each(fn (string $name, int $index) => PartnerUniversity::updateOrCreate(
                ['name' => $name],
                [
                    'logo_path' => 'partners/'.Str::slug($name).'.png',
                    'website' => 'https://www.'.Str::slug($name).'.edu',
                    'order' => $index + 1,
                ],
            ));

            $settings = [
                'site_name' => 'Sasi Education Consultants',
                'site_email' => 'info@sasi.test',
                'site_phone' => '+92-300-0000000',
                'office_address' => 'Main Boulevard, Lahore, Pakistan',
                'whatsapp_number' => '+92-300-1111111',
                'facebook_url' => 'https://facebook.com/sasi',
                'instagram_url' => 'https://instagram.com/sasi',
                'linkedin_url' => 'https://linkedin.com/company/sasi',
                'youtube_url' => 'https://youtube.com/@sasi',
                'default_currency' => 'USD',
                'consultation_fee' => '0',
                'office_hours' => 'Monday to Saturday, 10:00 AM - 6:00 PM',
                'hero_title' => 'Study Abroad With Expert Guidance',
                'hero_subtitle' => 'Admissions, scholarships, visa support, and counseling in one place.',
                'footer_text' => 'Helping students build international academic futures.',
                'privacy_contact' => 'privacy@sasi.test',
                'support_email' => 'support@sasi.test',
                'application_terms' => 'Applicants must provide complete and accurate documents.',
                'scholarship_notice' => 'Scholarship decisions depend on university and funding body rules.',
                'visa_notice' => 'Visa approval is subject to embassy assessment.',
            ];

            collect($settings)->each(fn (string $value, string $key) => Setting::updateOrCreate(
                ['key' => $key],
                ['value' => $value],
            ));

            collect(range(0, 19))->each(fn (int $index) => NewsletterSubscription::updateOrCreate(
                ['email' => 'subscriber'.($index + 1).'@example.com'],
            ));

            collect(range(0, 19))->each(fn (int $index) => DB::table('passkeys')->updateOrInsert(
                ['credential_id' => 'demo-credential-'.($index + 1)],
                [
                    'user_id' => $users[($index % 20) + 1]->id,
                    'name' => 'Demo Passkey '.($index + 1),
                    'credential' => json_encode(['id' => 'demo-credential-'.($index + 1), 'publicKey' => 'demo-public-key']),
                    'last_used_at' => now()->subDays($index),
                    'created_at' => now(),
                    'updated_at' => now(),
                ],
            ));

            collect(range(0, 19))->each(fn (int $index) => DB::table('notifications')->updateOrInsert(
                ['id' => sprintf('00000000-0000-0000-0000-%012d', $index + 1)],
                [
                    'type' => 'App\\Notifications\\ApplicationStatusUpdated',
                    'notifiable_type' => User::class,
                    'notifiable_id' => $users[($index % 20) + 1]->id,
                    'data' => json_encode(['message' => 'Application update for '.$programs[$index]->title]),
                    'read_at' => $index % 2 === 0 ? now() : null,
                    'created_at' => now()->subDays($index),
                    'updated_at' => now()->subDays($index),
                ],
            ));
        });
    }
}
