<?php

namespace Database\Seeders;

use App\Models\Role;
use App\Models\Permission;
use App\Models\District;
use App\Models\Club;
use App\Models\User;
use App\Models\Member;
use App\Models\Referee;
use App\Models\Coach;
use App\Models\NewsCategory;
use App\Models\News;
use App\Models\Album;
use App\Models\GalleryItem;
use App\Models\Event;
use App\Models\Achievement;
use App\Models\Document;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // 1. Seed Roles
        $roles = [
            ['name' => 'admin', 'display_name' => 'Super Administrator', 'description' => 'Has full control over the association website and database.'],
            ['name' => 'editor', 'display_name' => 'Content Editor', 'description' => 'Can manage news, gallery, and download sections.'],
            ['name' => 'district_manager', 'display_name' => 'District Manager', 'description' => 'Can manage clubs, coaches, and members in their district.'],
            ['name' => 'coach', 'display_name' => 'Club Trainer/Coach', 'description' => 'Can view their club members and recommend belt promotions.'],
            ['name' => 'member', 'display_name' => 'Registered Member/Athlete', 'description' => 'Can view their profile, rank history, and print certificates.']
        ];

        $roleModels = [];
        foreach ($roles as $role) {
            $roleModels[$role['name']] = Role::create($role);
        }

        // 2. Seed Permissions
        $permissions = [
            ['name' => 'manage_settings', 'display_name' => 'Manage Settings', 'description' => 'Edit website metadata, address, contact info, logo.'],
            ['name' => 'manage_users', 'display_name' => 'Manage Users', 'description' => 'Create/Edit system administrators and editors.'],
            ['name' => 'manage_members', 'display_name' => 'Manage Members', 'description' => 'Approve, suspend, and search registered members.'],
            ['name' => 'manage_referees', 'display_name' => 'Manage Referees', 'description' => 'Add/Edit official referees and certifications.'],
            ['name' => 'manage_coaches', 'display_name' => 'Manage Coaches', 'description' => 'Add/Edit affiliated coaches and training qualifications.'],
            ['name' => 'manage_news', 'display_name' => 'Manage News', 'description' => 'Create and publish news articles and announcements.'],
            ['name' => 'manage_events', 'display_name' => 'Manage Events', 'description' => 'Add matches, tournaments, and schedules.'],
            ['name' => 'manage_gallery', 'display_name' => 'Manage Gallery', 'description' => 'Create albums and upload photos/videos.'],
            ['name' => 'manage_downloads', 'display_name' => 'Manage Downloads', 'description' => 'Upload rules, guidelines, and application forms.']
        ];

        foreach ($permissions as $perm) {
            $permissionModel = Permission::create($perm);
            // Assign permissions to roles
            // Admin gets everything (handled dynamically or explicitly)
            $roleModels['admin']->permissions()->attach($permissionModel);
            
            // Editor permissions
            if (in_array($perm['name'], ['manage_news', 'manage_events', 'manage_gallery', 'manage_downloads'])) {
                $roleModels['editor']->permissions()->attach($permissionModel);
            }

            // District Manager permissions
            if (in_array($perm['name'], ['manage_members', 'manage_coaches'])) {
                $roleModels['district_manager']->permissions()->attach($permissionModel);
            }
        }

        // 3. Seed Districts of Lumbini Province
        $districts = [
            'Rupandehi',
            'Kapilvastu',
            'Nawalparasi West',
            'Palpa',
            'Arghakhanchi',
            'Gulmi',
            'Dang',
            'Pyuthan',
            'Rolpa',
            'Eastern Rukum',
            'Banke',
            'Bardiya'
        ];

        $districtModels = [];
        foreach ($districts as $dName) {
            $districtModels[$dName] = District::create(['name' => $dName]);
        }

        // 4. Seed Clubs
        $clubs = [
            ['district_id' => $districtModels['Rupandehi']->id, 'name' => 'Butwal Taekwondo Dojang', 'address' => 'Milanchowk, Butwal', 'contact_person' => 'Ram Prasad Shrestha', 'contact_phone' => '9857012345'],
            ['district_id' => $districtModels['Rupandehi']->id, 'name' => 'Bhairahawa Taekwondo Academy', 'address' => 'Siddharthanagar, Bhairahawa', 'contact_person' => 'Gita Rana', 'contact_phone' => '9857054321'],
            ['district_id' => $districtModels['Kapilvastu']->id, 'name' => 'Taulihawa TKD Club', 'address' => 'Taulihawa Bazar', 'contact_person' => 'Suresh Chaudhary', 'contact_phone' => '9847067890'],
            ['district_id' => $districtModels['Dang']->id, 'name' => 'Ghorahi Taekwondo Center', 'address' => 'Ghorahi, Dang', 'contact_person' => 'Janak Oli', 'contact_phone' => '9857811223'],
            ['district_id' => $districtModels['Banke']->id, 'name' => 'Nepalgunj TKD Club', 'address' => 'Surkhet Road, Nepalgunj', 'contact_person' => 'Bimal Budha', 'contact_phone' => '9848099887'],
        ];

        $clubModels = [];
        foreach ($clubs as $club) {
            $clubModels[] = Club::create($club);
        }

        // 5. Seed Users
        $adminUser = User::create([
            'name' => 'LPTA Administrator',
            'email' => 'admin@lumbinitkd.org',
            'password' => 'password',
            'role_id' => $roleModels['admin']->id,
            'status' => 'active'
        ]);

        $editorUser = User::create([
            'name' => 'Ramesh Bhandari',
            'email' => 'editor@lumbinitkd.org',
            'password' => 'password',
            'role_id' => $roleModels['editor']->id,
            'status' => 'active'
        ]);

        $managerUser = User::create([
            'name' => 'Sunil Thapa',
            'email' => 'manager@lumbinitkd.org',
            'password' => 'password',
            'role_id' => $roleModels['district_manager']->id,
            'status' => 'active'
        ]);

        $coachUser = User::create([
            'name' => 'Devendra Bahadur Singh',
            'email' => 'coach@lumbinitkd.org',
            'password' => 'password',
            'role_id' => $roleModels['coach']->id,
            'status' => 'active'
        ]);

        $memberUser = User::create([
            'name' => 'Roshan Shrestha',
            'email' => 'member@lumbinitkd.org',
            'password' => 'password',
            'role_id' => $roleModels['member']->id,
            'status' => 'active'
        ]);

        // 6. Seed Coaches (Trainers) table
        $coachesData = [
            [
                'name' => 'Devendra Bahadur Singh',
                'qualification' => '4th Dan Black Belt, National Coach Course',
                'experience_years' => 12,
                'achievements' => 'Gold Medalist in 7th National Games (2016). Trained over 300 black belts.',
                'specialization' => 'Kyorugi (Sparring) Tactics & Conditioning',
                'contact_phone' => '9857011223',
                'email' => 'coach@lumbinitkd.org',
                'photo' => null,
                'bio' => 'Devendra is one of the most respected coaches in Rupandehi. He has served as a provincial coach in multiple national tournaments.',
                'club_id' => $clubModels[0]->id, // Butwal Dojang
                'status' => 'active'
            ],
            [
                'name' => 'Kabita Rana',
                'qualification' => '3rd Dan Black Belt, Poomsae Instructor License',
                'experience_years' => 7,
                'achievements' => 'Bronze Medalist in South Asian Games (2019). Special Award for Best Female Coach 2024.',
                'specialization' => 'Poomsae (Forms) & Flexibility Training',
                'contact_phone' => '9847055667',
                'email' => 'kabita@lumbinitkd.org',
                'photo' => null,
                'bio' => 'Kabita specializes in artistic forms and flexibilities. She heads the junior classes at Bhairahawa Taekwondo Academy.',
                'club_id' => $clubModels[1]->id, // Bhairahawa
                'status' => 'active'
            ],
            [
                'name' => 'Janak Oli',
                'qualification' => '3rd Dan Black Belt',
                'experience_years' => 8,
                'achievements' => 'National Referee, Coach at Lumbini Sports Club',
                'specialization' => 'Self Defense & Kid Taekwondo',
                'contact_phone' => '9857811223',
                'email' => 'janak@lumbinitkd.org',
                'photo' => null,
                'bio' => 'Janak heads the Ghorahi Taekwondo Center, promoting physical fitness and self-defense for youth in Dang.',
                'club_id' => $clubModels[3]->id, // Ghorahi
                'status' => 'active'
            ]
        ];

        foreach ($coachesData as $coach) {
            Coach::create($coach);
        }

        // 7. Seed Referees
        $refereesData = [
            [
                'name' => 'Milan Shrestha',
                'certification_level' => 'International Referee (IR) Class A',
                'experience_years' => 16,
                'contact_phone' => '9857099887',
                'email' => 'milan.referee@gmail.com',
                'photo' => null,
                'bio' => 'Milan has officiated in world-level championships and is the chief referee coordinator for Lumbini Province.',
                'status' => 'active'
            ],
            [
                'name' => 'Rina Thapa',
                'certification_level' => 'National Referee Class B',
                'experience_years' => 9,
                'contact_phone' => '9847012987',
                'email' => 'rina.tkd@yahoo.com',
                'photo' => null,
                'bio' => 'Rina is an experienced national level referee specializing in Poomsae judging.',
                'status' => 'active'
            ],
            [
                'name' => 'Suresh Chaudhary',
                'certification_level' => 'National Referee Class C',
                'experience_years' => 5,
                'contact_phone' => '9847067890',
                'email' => 'suresh.referee@gmail.com',
                'photo' => null,
                'bio' => 'Suresh represents Kapilvastu District and has been active in local sparring judging for 5 years.',
                'status' => 'active'
            ]
        ];

        foreach ($refereesData as $ref) {
            Referee::create($ref);
        }

        // 8. Seed Members
        $membersData = [
            [
                'user_id' => $memberUser->id,
                'member_id' => 'LPTA-00001',
                'first_name' => 'Roshan',
                'last_name' => 'Shrestha',
                'email' => 'member@lumbinitkd.org',
                'phone' => '9812345678',
                'gender' => 'Male',
                'dob' => '2004-05-15',
                'address' => 'Devinagar, Butwal',
                'belt_rank' => '1st Dan Black Belt',
                'district_id' => $districtModels['Rupandehi']->id,
                'club_id' => $clubModels[0]->id,
                'photo' => null,
                'status' => 'active',
                'expiry_date' => '2027-12-31'
            ],
            [
                'user_id' => null,
                'member_id' => 'LPTA-00002',
                'first_name' => 'Saraswati',
                'last_name' => 'Adhikari',
                'email' => 'saraswati@gmail.com',
                'phone' => '9822334455',
                'gender' => 'Female',
                'dob' => '2006-08-20',
                'address' => 'Siddharthanagar, Bhairahawa',
                'belt_rank' => 'Red Belt',
                'district_id' => $districtModels['Rupandehi']->id,
                'club_id' => $clubModels[1]->id,
                'photo' => null,
                'status' => 'active',
                'expiry_date' => '2026-12-31'
            ],
            [
                'user_id' => null,
                'member_id' => 'LPTA-00003',
                'first_name' => 'Anil',
                'last_name' => 'Thapa',
                'email' => 'anil.thapa@gmail.com',
                'phone' => '9818822334',
                'gender' => 'Male',
                'dob' => '2005-02-10',
                'address' => 'Taulihawa, Kapilvastu',
                'belt_rank' => 'Blue Belt',
                'district_id' => $districtModels['Kapilvastu']->id,
                'club_id' => $clubModels[2]->id,
                'photo' => null,
                'status' => 'active',
                'expiry_date' => '2026-12-31'
            ],
            [
                'user_id' => null,
                'member_id' => 'LPTA-00004',
                'first_name' => 'Bipin',
                'last_name' => 'Budha',
                'email' => 'bipin@gmail.com',
                'phone' => '9801122334',
                'gender' => 'Male',
                'dob' => '2007-11-05',
                'address' => 'Nepalgunj, Banke',
                'belt_rank' => 'Green Belt',
                'district_id' => $districtModels['Banke']->id,
                'club_id' => $clubModels[4]->id,
                'photo' => null,
                'status' => 'active',
                'expiry_date' => '2026-12-31'
            ],
            [
                'user_id' => null,
                'member_id' => 'LPTA-00005',
                'first_name' => 'Rupa',
                'last_name' => 'Chaudhary',
                'email' => 'rupa.c@gmail.com',
                'phone' => '9845011928',
                'gender' => 'Female',
                'dob' => '2008-03-12',
                'address' => 'Ghorahi, Dang',
                'belt_rank' => 'Yellow Belt',
                'district_id' => $districtModels['Dang']->id,
                'club_id' => $clubModels[3]->id,
                'photo' => null,
                'status' => 'pending',
                'expiry_date' => null
            ]
        ];

        foreach ($membersData as $memb) {
            Member::create($memb);
        }

        // 9. Seed News Categories
        $categories = ['Championships', 'Announcements', 'Seminars', 'Belts & Grading'];
        $catModels = [];
        foreach ($categories as $cat) {
            $catModels[$cat] = NewsCategory::create([
                'name' => $cat,
                'slug' => Str::slug($cat)
            ]);
        }

        // 10. Seed News
        $newsData = [
            [
                'category_id' => $catModels['Championships']->id,
                'title' => 'Lumbini Province Selection Tournament 2026 Announced',
                'slug' => 'lumbini-province-selection-tournament-2026-announced',
                'content' => 'The Lumbini Province Taekwondo Association (LPTA) is pleased to announce that the upcoming Provincial Selection Tournament will be held from July 15 to July 18, 2026, at the Butwal Covered Hall. The tournament will select athletes to represent Lumbini Province in the upcoming National Games. Athletes must be registered and approved by their respective districts. Registrations are open through our online Member Portal. Weigh-ins will take place on July 14. We encourage all coaches to prepare their players and register them on time.',
                'image' => null,
                'is_featured' => true,
                'views' => 125,
                'author_id' => $adminUser->id,
                'status' => 'published'
            ],
            [
                'category_id' => $catModels['Belts & Grading']->id,
                'title' => 'Black Belt Grading Ceremony Held in Rupandehi Dojang',
                'slug' => 'black-belt-grading-ceremony-held-in-rupandehi-dojang',
                'content' => 'A grand Black Belt Grading Ceremony was successfully conducted on June 10, 2026, at the Butwal Taekwondo Dojang. Over 45 junior and senior athletes were graded by the grandmaster panel led by Chief Instructor Devendra Bahadur Singh. The athletes were evaluated on basic techniques, sparring (Kyorugi), forms (Poomsae), self-defense, and breaking (Gyokpa). Ten players successfully obtained their 1st Dan Black Belt, while three athletes advanced to 2nd Dan. Congratulations to all successful athletes!',
                'image' => null,
                'is_featured' => false,
                'views' => 84,
                'author_id' => $adminUser->id,
                'status' => 'published'
            ],
            [
                'category_id' => $catModels['Seminars']->id,
                'title' => 'Referees Refresher Course Scheduled for August in Dang',
                'slug' => 'referees-refresher-course-scheduled-for-august-in-dang',
                'content' => 'Lumbini Province Taekwondo Association is organizing a provincial Referee Refresher Course on August 5, 2026, in Ghorahi, Dang. This course is mandatory for all Class B and Class C referees in the province to update their knowledge regarding the latest World Taekwondo (WT) sparring competition rules. The course will be conducted by International Referee Milan Shrestha. Registration starts on July 1 and ends on July 25. Accommodations will be provided for out-district participants.',
                'image' => null,
                'is_featured' => true,
                'views' => 62,
                'author_id' => $editorUser->id,
                'status' => 'published'
            ],
            [
                'category_id' => $catModels['Championships']->id,
                'title' => 'Lumbini Athletes Win 12 Medals in National Junior Championship',
                'slug' => 'lumbini-athletes-win-12-medals-in-national-junior-championship',
                'content' => 'Lumbini Province Taekwondo team achieved an outstanding victory in the recently concluded National Junior Taekwondo Championship held in Kathmandu. The team secured 4 Gold, 5 Silver, and 3 Bronze medals, finishing as the second runner-up in the overall team standing. Roshan Shrestha won Gold in the junior male under-54kg division, while Saraswati Adhikari bagged Silver in Individual Poomsae. LPTA President congratulated the team and announced a cash reward program to support their development.',
                'image' => null,
                'is_featured' => false,
                'views' => 210,
                'author_id' => $editorUser->id,
                'status' => 'published'
            ]
        ];

        foreach ($newsData as $n) {
            News::create($n);
        }

        // 11. Seed Events
        $eventsData = [
            [
                'title' => 'Lumbini Provincial Taekwondo Championship 2026',
                'slug' => 'lumbini-provincial-taekwondo-championship-2026',
                'description' => 'Official selection championship for the upcoming National Games. Competitions will include Kyorugi (Sparring) and Poomsae (Forms) for Cadet, Junior, and Senior divisions.',
                'start_date' => '2026-07-15 09:00:00',
                'end_date' => '2026-07-18 17:00:00',
                'venue' => 'Butwal Covered Hall, Rupandehi',
                'registration_status' => 'open',
                'image' => null
            ],
            [
                'title' => 'Referees Refresher Course 2026',
                'slug' => 'referees-refresher-course-2026',
                'description' => 'Mandatory rules update course for national and district referees. Highlights include video replay training, scorekeeper software usage, and penalty criteria updates.',
                'start_date' => '2026-08-05 08:00:00',
                'end_date' => '2026-08-05 18:00:00',
                'venue' => 'Ghorahi Multipurpose Hall, Dang',
                'registration_status' => 'open',
                'image' => null
            ],
            [
                'title' => 'District Belt Grading - Palpa & Gulmi',
                'slug' => 'district-belt-grading-palpa-gulmi',
                'description' => 'Combined belt testing ceremony for Color Belts (Yellow to Red) from Palpa and Gulmi districts.',
                'start_date' => '2026-06-28 10:00:00',
                'end_date' => '2026-06-28 16:00:00',
                'venue' => 'Tansen Covered Hall, Palpa',
                'registration_status' => 'closed',
                'image' => null
            ]
        ];

        foreach ($eventsData as $event) {
            Event::create($event);
        }

        // 12. Seed Achievements
        $achievementsData = [
            [
                'title' => 'Gold Medal in 9th National Games',
                'description' => 'Won Gold in the Flyweight (under 54kg) sparring division, defeating Province 3 in the finals.',
                'type' => 'national',
                'medal_type' => 'gold',
                'player_name' => 'Roshan Shrestha',
                'achievement_date' => '2024-10-18',
                'photo' => null
            ],
            [
                'title' => 'Silver Medal in National Poomsae Championship',
                'description' => 'Scored 7.65 points in individual female under-18 Poomsae category to secure the Silver medal.',
                'type' => 'national',
                'medal_type' => 'silver',
                'player_name' => 'Saraswati Adhikari',
                'achievement_date' => '2025-03-22',
                'photo' => null
            ],
            [
                'title' => 'Bronze Medal in South Asian TKD Championship',
                'description' => 'Represented Nepal in the 68kg Sparring and secured Bronze after a tight semi-final against India.',
                'type' => 'international',
                'medal_type' => 'bronze',
                'player_name' => 'Anil Thapa',
                'achievement_date' => '2024-12-05',
                'photo' => null
            ]
        ];

        foreach ($achievementsData as $ach) {
            Achievement::create($ach);
        }

        // 13. Seed Albums and Gallery
        $album = Album::create([
            'name' => 'Provincial Selection 2025',
            'description' => 'Memorable highlights and action moments from the 2025 Lumbini Selection Championship.',
            'cover_image' => null
        ]);

        $galleryItems = [
            ['album_id' => $album->id, 'type' => 'image', 'file_path' => 'demo_action1.jpg', 'caption' => 'Gold medal match in progress'],
            ['album_id' => $album->id, 'type' => 'image', 'file_path' => 'demo_action2.jpg', 'caption' => 'Award ceremony with LPTA committee'],
            ['album_id' => $album->id, 'type' => 'video', 'file_path' => 'https://www.youtube.com/embed/dQw4w9WgXcQ', 'caption' => 'Championship final matches video highlight']
        ];

        foreach ($galleryItems as $item) {
            GalleryItem::create($item);
        }

        // 14. Seed Documents (Downloads)
        $documentsData = [
            [
                'title' => 'New Member Registration Guideline Form 2026',
                'file_path' => 'downloads/member_form_2026.pdf',
                'file_type' => 'pdf',
                'description' => 'Complete PDF application form and details needed for obtaining official association membership.'
            ],
            [
                'title' => 'LPTA Official Tournament Rules & Regulations 2026',
                'file_path' => 'downloads/tournament_rules_2026.pdf',
                'file_type' => 'pdf',
                'description' => 'Detailed competition guidelines, scoring protocols, and weight boundaries for provincial matches.'
            ],
            [
                'title' => 'Dan Promotion Grading Application Form',
                'file_path' => 'downloads/dan_grading_form.docx',
                'file_type' => 'docx',
                'description' => 'Official application form required for Black Belt Dan promotions (1st Dan to 4th Dan).'
            ]
        ];

        foreach ($documentsData as $doc) {
            Document::create($doc);
        }
    }
}
