<?php

namespace Database\Seeders;

use App\Models\Booking;
use App\Models\Lapangan;
use App\Models\TimeSlot;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     * Membuat data dummy untuk pengembangan dan testing.
     */
    public function run(): void
    {
        $this->command->info('🌱 Mulai seeding database Booking Lapangan Olahraga...');

        // Urutan seeding penting! (FK dependencies)
        $this->seedUsers();
        $this->seedLapangan();
        $this->seedTimeSlots();
        $this->seedBookings();

        $this->command->info('✅ Seeding selesai!');
    }

    // =============================================
    // SEED USERS
    // =============================================

    private function seedUsers(): void
    {
        $this->command->info('   → Membuat users...');

        // Hapus data lama
        User::truncate();

        // --- Admin ---
        $admins = [
            [
                'name'      => 'Budi Admin',
                'email'     => 'admin@example.com',
                'password'  => Hash::make('password'),
                'phone'     => '081234567890',
                'role'      => 'admin',
                'is_active' => true,
            ],
            [
                'name'      => 'Siti Admin',
                'email'     => 'admin2@example.com',
                'password'  => Hash::make('password'),
                'phone'     => '081234567891',
                'role'      => 'admin',
                'is_active' => true,
            ],
        ];

        // --- Customer ---
        $customers = [
            [
                'name'      => 'Customer Satu',
                'email'     => 'customer1@example.com',
                'password'  => Hash::make('password'),
                'phone'     => '082111111111',
                'role'      => 'customer',
                'is_active' => true,
            ],
            [
                'name'      => 'Customer Dua',
                'email'     => 'customer2@example.com',
                'password'  => Hash::make('password'),
                'phone'     => '082222222222',
                'role'      => 'customer',
                'is_active' => true,
            ],
            [
                'name'      => 'Customer Tiga',
                'email'     => 'customer3@example.com',
                'password'  => Hash::make('password'),
                'phone'     => '082333333333',
                'role'      => 'customer',
                'is_active' => true,
            ],
        ];

        foreach (array_merge($admins, $customers) as $userData) {
            User::create($userData);
        }

        $this->command->info('   ✓ ' . User::count() . ' users dibuat.');
    }

    // =============================================
    // SEED LAPANGAN
    // =============================================

    private function seedLapangan(): void
    {
        $this->command->info('   → Membuat lapangan...');

        Lapangan::truncate();

        $admin1 = User::where('email', 'admin@example.com')->first();
        $admin2 = User::where('email', 'admin2@example.com')->first();

        $lapanganData = [
            [
                'nama'           => 'Futsal Arena Merdeka',
                'deskripsi'      => 'Lapangan futsal premium dengan rumput sintetis berkualitas tinggi, pencahayaan LED, dan tribun penonton. Cocok untuk turnamen dan latihan rutin.',
                'jenis_olahraga' => 'futsal',
                'harga_per_jam'  => 100000,
                'lokasi'         => 'Jakarta Selatan',
                'alamat'         => 'Jl. Merdeka No. 10, Kebayoran Baru, Jakarta Selatan',
                'foto'           => [
                    'https://via.placeholder.com/800x600?text=Futsal+Arena+Merdeka+1',
                    'https://via.placeholder.com/800x600?text=Futsal+Arena+Merdeka+2',
                ],
                'fasilitas'      => ['Parkir Luas', 'Toilet', 'Ruang Ganti', 'Kantin', 'WiFi', 'AC'],
                'jam_buka'       => '08:00:00',
                'jam_tutup'      => '22:00:00',
                'is_active'      => true,
                'rating'         => 4.8,
                'total_review'   => 125,
                'owner_id'       => $admin1->id,
            ],
            [
                'nama'           => 'GOR Badminton Bintang',
                'deskripsi'      => 'GOR badminton dengan 6 lapangan, lantai kayu berkualitas, lampu standar internasional. Tersedia untuk sewa per jam dan bulanan.',
                'jenis_olahraga' => 'badminton',
                'harga_per_jam'  => 75000,
                'lokasi'         => 'Bandung',
                'alamat'         => 'Jl. Asia Afrika No. 55, Lengkong, Bandung',
                'foto'           => [
                    'https://via.placeholder.com/800x600?text=GOR+Badminton+Bintang+1',
                    'https://via.placeholder.com/800x600?text=GOR+Badminton+Bintang+2',
                ],
                'fasilitas'      => ['Parkir', 'Toilet', 'Ruang Ganti', 'Kafetaria', 'Penyewaan Raket'],
                'jam_buka'       => '07:00:00',
                'jam_tutup'      => '23:00:00',
                'is_active'      => true,
                'rating'         => 4.5,
                'total_review'   => 89,
                'owner_id'       => $admin1->id,
            ],
            [
                'nama'           => 'Basketball Court Pro',
                'deskripsi'      => 'Lapangan basket outdoor dengan permukaan aspal premium, ring standar NBA, dan area penonton. Lokasi strategis di pusat kota.',
                'jenis_olahraga' => 'basket',
                'harga_per_jam'  => 80000,
                'lokasi'         => 'Surabaya',
                'alamat'         => 'Jl. Pemuda No. 33, Genteng, Surabaya',
                'foto'           => [
                    'https://via.placeholder.com/800x600?text=Basketball+Court+Pro+1',
                ],
                'fasilitas'      => ['Parkir', 'Toilet', 'Mini Market', 'Area Warming Up'],
                'jam_buka'       => '06:00:00',
                'jam_tutup'      => '21:00:00',
                'is_active'      => true,
                'rating'         => 4.2,
                'total_review'   => 56,
                'owner_id'       => $admin2->id,
            ],
            [
                'nama'           => 'Voli Beach Nusantara',
                'deskripsi'      => 'Lapangan voli pasir (beach volleyball) dengan pasir impor berkualitas. Suasana seperti di tepi pantai, cocok untuk santai bersama keluarga dan teman.',
                'jenis_olahraga' => 'voli',
                'harga_per_jam'  => 60000,
                'lokasi'         => 'Yogyakarta',
                'alamat'         => 'Jl. Ring Road Utara No. 22, Sleman, Yogyakarta',
                'foto'           => [
                    'https://via.placeholder.com/800x600?text=Voli+Beach+Nusantara+1',
                    'https://via.placeholder.com/800x600?text=Voli+Beach+Nusantara+2',
                    'https://via.placeholder.com/800x600?text=Voli+Beach+Nusantara+3',
                ],
                'fasilitas'      => ['Parkir', 'Toilet', 'Shower', 'Warung Makan', 'Tempat Duduk'],
                'jam_buka'       => '08:00:00',
                'jam_tutup'      => '20:00:00',
                'is_active'      => true,
                'rating'         => 4.6,
                'total_review'   => 73,
                'owner_id'       => $admin2->id,
            ],
            [
                'nama'           => 'Tenis Club Senayan',
                'deskripsi'      => 'Lapangan tenis indoor dengan permukaan hard court standar ITF. Dilengkapi pelatih profesional dan ball machine. Cocok untuk pemula hingga profesional.',
                'jenis_olahraga' => 'tenis',
                'harga_per_jam'  => 150000,
                'lokasi'         => 'Jakarta Pusat',
                'alamat'         => 'Jl. Senayan No. 7, Gelora, Jakarta Pusat',
                'foto'           => [
                    'https://via.placeholder.com/800x600?text=Tenis+Club+Senayan+1',
                    'https://via.placeholder.com/800x600?text=Tenis+Club+Senayan+2',
                ],
                'fasilitas'      => ['Parkir VIP', 'Locker Room', 'Shower', 'Restoran', 'Pro Shop', 'Pelatih'],
                'jam_buka'       => '06:00:00',
                'jam_tutup'      => '22:00:00',
                'is_active'      => true,
                'rating'         => 4.9,
                'total_review'   => 201,
                'owner_id'       => $admin1->id,
            ],
        ];

        foreach ($lapanganData as $data) {
            Lapangan::create($data);
        }

        $this->command->info('   ✓ ' . Lapangan::count() . ' lapangan dibuat.');
    }

    // =============================================
    // SEED TIME SLOTS
    // =============================================

    private function seedTimeSlots(): void
    {
        $this->command->info('   → Membuat time slots (08:00 - 22:00, per jam)...');

        TimeSlot::truncate();

        $lapangans = Lapangan::all();
        $slotCount = 0;

        foreach ($lapangans as $lapangan) {
            // Buat slot per jam mulai dari jam_buka hingga jam_tutup
            $jamBuka   = Carbon::createFromFormat('H:i:s', $lapangan->jam_buka);
            $jamTutup  = Carbon::createFromFormat('H:i:s', $lapangan->jam_tutup);
            $jamSaatIni = clone $jamBuka;

            while ($jamSaatIni->copy()->addHour()->lte($jamTutup)) {
                $jamMulai   = $jamSaatIni->format('H:i:s');
                $jamSelesai = $jamSaatIni->copy()->addHour()->format('H:i:s');

                TimeSlot::create([
                    'lapangan_id'  => $lapangan->id,
                    'jam_mulai'    => $jamMulai,
                    'jam_selesai'  => $jamSelesai,
                    'is_available' => true,
                    'harga'        => null, // null = ikuti harga lapangan
                ]);

                $slotCount++;
                $jamSaatIni->addHour();
            }
        }

        $this->command->info("   ✓ {$slotCount} time slots dibuat.");
    }

    // =============================================
    // SEED BOOKINGS
    // =============================================

    private function seedBookings(): void
    {
        $this->command->info('   → Membuat bookings...');

        Booking::truncate();

        $customer1 = User::where('email', 'customer1@example.com')->first();
        $customer2 = User::where('email', 'customer2@example.com')->first();
        $customer3 = User::where('email', 'customer3@example.com')->first();

        $lapangan1 = Lapangan::where('jenis_olahraga', 'futsal')->first();
        $lapangan2 = Lapangan::where('jenis_olahraga', 'badminton')->first();
        $lapangan3 = Lapangan::where('jenis_olahraga', 'basket')->first();
        $lapangan4 = Lapangan::where('jenis_olahraga', 'voli')->first();
        $lapangan5 = Lapangan::where('jenis_olahraga', 'tenis')->first();

        $bookingsData = [
            // Booking pending - hari ini
            [
                'user_id'     => $customer1->id,
                'lapangan_id' => $lapangan1->id,
                'tanggal'     => Carbon::today()->toDateString(),
                'jam_mulai'   => '09:00:00',
                'jam_selesai' => '11:00:00',
                'durasi_jam'  => 2,
                'total_harga' => $lapangan1->harga_per_jam * 2,
                'status'      => 'pending',
                'catatan'     => 'Tolong siapkan bola futsal ekstra.',
            ],
            // Booking confirmed - besok
            [
                'user_id'     => $customer2->id,
                'lapangan_id' => $lapangan2->id,
                'tanggal'     => Carbon::tomorrow()->toDateString(),
                'jam_mulai'   => '15:00:00',
                'jam_selesai' => '17:00:00',
                'durasi_jam'  => 2,
                'total_harga' => $lapangan2->harga_per_jam * 2,
                'status'      => 'confirmed',
                'catatan'     => null,
            ],
            // Booking completed - 3 hari lalu
            [
                'user_id'     => $customer3->id,
                'lapangan_id' => $lapangan3->id,
                'tanggal'     => Carbon::now()->subDays(3)->toDateString(),
                'jam_mulai'   => '10:00:00',
                'jam_selesai' => '12:00:00',
                'durasi_jam'  => 2,
                'total_harga' => $lapangan3->harga_per_jam * 2,
                'status'      => 'completed',
                'catatan'     => 'Kami ada turnamen kecil-kecilan.',
            ],
            // Booking cancelled - seminggu lalu
            [
                'user_id'     => $customer1->id,
                'lapangan_id' => $lapangan4->id,
                'tanggal'     => Carbon::now()->subWeek()->toDateString(),
                'jam_mulai'   => '13:00:00',
                'jam_selesai' => '15:00:00',
                'durasi_jam'  => 2,
                'total_harga' => $lapangan4->harga_per_jam * 2,
                'status'      => 'cancelled',
                'catatan'     => null,
            ],
            // Booking rejected
            [
                'user_id'     => $customer2->id,
                'lapangan_id' => $lapangan5->id,
                'tanggal'     => Carbon::now()->subDays(5)->toDateString(),
                'jam_mulai'   => '08:00:00',
                'jam_selesai' => '10:00:00',
                'durasi_jam'  => 2,
                'total_harga' => $lapangan5->harga_per_jam * 2,
                'status'      => 'rejected',
                'catatan'     => 'Pesan untuk latihan tenis.',
                'alasan_penolakan' => 'Lapangan sedang dalam perbaikan pada tanggal tersebut.',
            ],
            // Booking pending lainnya
            [
                'user_id'     => $customer3->id,
                'lapangan_id' => $lapangan1->id,
                'tanggal'     => Carbon::now()->addDays(2)->toDateString(),
                'jam_mulai'   => '16:00:00',
                'jam_selesai' => '18:00:00',
                'durasi_jam'  => 2,
                'total_harga' => $lapangan1->harga_per_jam * 2,
                'status'      => 'pending',
                'catatan'     => null,
            ],
            // Booking confirmed minggu depan
            [
                'user_id'     => $customer1->id,
                'lapangan_id' => $lapangan2->id,
                'tanggal'     => Carbon::now()->addDays(7)->toDateString(),
                'jam_mulai'   => '19:00:00',
                'jam_selesai' => '21:00:00',
                'durasi_jam'  => 2,
                'total_harga' => $lapangan2->harga_per_jam * 2,
                'status'      => 'confirmed',
                'catatan'     => 'Tolong sediakan shuttlecock extra.',
            ],
            // Booking completed bulan lalu
            [
                'user_id'     => $customer2->id,
                'lapangan_id' => $lapangan3->id,
                'tanggal'     => Carbon::now()->subMonth()->toDateString(),
                'jam_mulai'   => '07:00:00',
                'jam_selesai' => '09:00:00',
                'durasi_jam'  => 2,
                'total_harga' => $lapangan3->harga_per_jam * 2,
                'status'      => 'completed',
                'catatan'     => null,
            ],
            // Booking completed bulan lalu (2)
            [
                'user_id'     => $customer3->id,
                'lapangan_id' => $lapangan4->id,
                'tanggal'     => Carbon::now()->subMonth()->addDays(5)->toDateString(),
                'jam_mulai'   => '14:00:00',
                'jam_selesai' => '16:00:00',
                'durasi_jam'  => 2,
                'total_harga' => $lapangan4->harga_per_jam * 2,
                'status'      => 'completed',
                'catatan'     => null,
            ],
            // Booking pending hari ini (2)
            [
                'user_id'     => $customer1->id,
                'lapangan_id' => $lapangan5->id,
                'tanggal'     => Carbon::today()->toDateString(),
                'jam_mulai'   => '12:00:00',
                'jam_selesai' => '14:00:00',
                'durasi_jam'  => 2,
                'total_harga' => $lapangan5->harga_per_jam * 2,
                'status'      => 'pending',
                'catatan'     => 'Ada teman yang join, mohon ring tersedia.',
            ],
        ];

        foreach ($bookingsData as $data) {
            Booking::create($data);
        }

        $this->command->info('   ✓ ' . Booking::count() . ' bookings dibuat.');
        $this->command->newLine();
        $this->command->info('📊 Ringkasan data:');
        $this->command->table(
            ['Model', 'Total'],
            [
                ['Users', User::count()],
                ['Lapangan', Lapangan::count()],
                ['Time Slots', TimeSlot::count()],
                ['Bookings', Booking::count()],
            ]
        );
        $this->command->newLine();
        $this->command->info('🔑 Akun login:');
        $this->command->info('   Admin  : admin@example.com / password');
        $this->command->info('   Admin2 : admin2@example.com / password');
        $this->command->info('   Customer1: customer1@example.com / password');
        $this->command->info('   Customer2: customer2@example.com / password');
        $this->command->info('   Customer3: customer3@example.com / password');
    }
}
