<?php

namespace Database\Seeders;

use App\Models\AdditionalFacility;
use App\Models\Category;
use App\Models\Client;
use App\Models\ClientPoint;
use App\Models\Package;
use App\Models\PackageFeature;
use App\Models\PointTransaction;
use App\Models\PropertyType;
use App\Models\Service;
use App\Models\Subscription;
use App\Models\Technician;
use Illuminate\Database\Seeder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class DemoDataSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // 1. Categories (الأقسام)
        $categories = [
            [
                'name' => ['ar' => 'كهرباء', 'en' => 'Electrical'],
                'description' => ['ar' => 'جميع خدمات الكهرباء والصيانة', 'en' => 'All electrical and maintenance services'],
                'icon' => 'heroicon-o-bolt',
                'is_active' => true,
                'sort_order' => 1
            ],
            [
                'name' => ['ar' => 'سباكة', 'en' => 'Plumbing'],
                'description' => ['ar' => 'خدمات السباكة وإصلاح التسريبات', 'en' => 'Plumbing services and leak repairs'],
                'icon' => 'heroicon-o-beaker',
                'is_active' => true,
                'sort_order' => 2
            ],
            [
                'name' => ['ar' => 'تكييف', 'en' => 'Air Conditioning'],
                'description' => ['ar' => 'صيانة وتركيب أجهزة التكييف', 'en' => 'AC maintenance and installation'],
                'icon' => 'heroicon-o-cog-6-tooth',
                'is_active' => true,
                'sort_order' => 3
            ],
            [
                'name' => ['ar' => 'نجارة', 'en' => 'Carpentry'],
                'description' => ['ar' => 'أعمال النجارة والديكور', 'en' => 'Carpentry and decoration work'],
                'icon' => 'heroicon-o-cube',
                'is_active' => true,
                'sort_order' => 4
            ],
            [
                'name' => ['ar' => 'دهان', 'en' => 'Painting'],
                'description' => ['ar' => 'خدمات الدهان والديكورات', 'en' => 'Painting and decoration services'],
                'icon' => 'heroicon-o-paint-brush',
                'is_active' => true,
                'sort_order' => 5
            ],
        ];

        $categoryIds = [];
        foreach ($categories as $cat) {
            $category = Category::whereJsonContains('name->ar', $cat['name']['ar'])->first();
            
            if (!$category) {
                $category = Category::create([
                    'name' => $cat['name'],
                    'description' => $cat['description'],
                    'icon' => $cat['icon'],
                    'is_active' => $cat['is_active'],
                    'sort_order' => $cat['sort_order'],
                ]);
            } else {
                $category->update([
                    'name' => $cat['name'],
                    'description' => $cat['description'],
                    'icon' => $cat['icon'],
                    'is_active' => $cat['is_active'],
                    'sort_order' => $cat['sort_order'],
                ]);
            }
            
            $categoryIds[] = $category->id;
        }

        // 2. Services (الخدمات)
        $services = [
            // كهرباء / Electrical
            ['category_id' => $categoryIds[0], 'name' => ['ar' => 'تمديد أسلاك كهربائية', 'en' => 'Electrical Wiring'], 'description' => ['ar' => 'تمديد وتوصيل الأسلاك الكهربائية', 'en' => 'Electrical wiring installation and connection'], 'price' => 150.00, 'points' => 150, 'icon' => 'heroicon-o-bolt', 'is_active' => true, 'sort_order' => 1],
            ['category_id' => $categoryIds[0], 'name' => ['ar' => 'إصلاح قواطع كهربائية', 'en' => 'Circuit Breaker Repair'], 'description' => ['ar' => 'صيانة وإصلاح القواطع الكهربائية', 'en' => 'Circuit breaker maintenance and repair'], 'price' => 100.00, 'points' => 100, 'icon' => 'heroicon-o-bolt', 'is_active' => true, 'sort_order' => 2],
            ['category_id' => $categoryIds[0], 'name' => ['ar' => 'تركيب لمبات LED', 'en' => 'LED Light Installation'], 'description' => ['ar' => 'تركيب وإصلاح الإضاءة', 'en' => 'LED light installation and repair'], 'price' => 80.00, 'points' => 80, 'icon' => 'heroicon-o-light-bulb', 'is_active' => true, 'sort_order' => 3],
            // سباكة / Plumbing
            ['category_id' => $categoryIds[1], 'name' => ['ar' => 'إصلاح تسريب مياه', 'en' => 'Water Leak Repair'], 'description' => ['ar' => 'إصلاح جميع أنواع التسريبات', 'en' => 'All types of leak repairs'], 'price' => 120.00, 'points' => 120, 'icon' => 'heroicon-o-beaker', 'is_active' => true, 'sort_order' => 1],
            ['category_id' => $categoryIds[1], 'name' => ['ar' => 'تركيب خلاطات', 'en' => 'Faucet Installation'], 'description' => ['ar' => 'تركيب وصيانة الخلاطات', 'en' => 'Faucet installation and maintenance'], 'price' => 90.00, 'points' => 90, 'icon' => 'heroicon-o-beaker', 'is_active' => true, 'sort_order' => 2],
            ['category_id' => $categoryIds[1], 'name' => ['ar' => 'تنظيف مجاري', 'en' => 'Drain Cleaning'], 'description' => ['ar' => 'تنظيف وإصلاح المجاري', 'en' => 'Drain cleaning and repair'], 'price' => 200.00, 'points' => 200, 'icon' => 'heroicon-o-beaker', 'is_active' => true, 'sort_order' => 3],
            // تكييف / Air Conditioning
            ['category_id' => $categoryIds[2], 'name' => ['ar' => 'تنظيف مكيف', 'en' => 'AC Cleaning'], 'description' => ['ar' => 'تنظيف شامل لأجهزة التكييف', 'en' => 'Complete AC cleaning service'], 'price' => 150.00, 'points' => 150, 'icon' => 'heroicon-o-cog-6-tooth', 'is_active' => true, 'sort_order' => 1],
            ['category_id' => $categoryIds[2], 'name' => ['ar' => 'صيانة مكيف', 'en' => 'AC Maintenance'], 'description' => ['ar' => 'صيانة دورية لأجهزة التكييف', 'en' => 'Regular AC maintenance service'], 'price' => 180.00, 'points' => 180, 'icon' => 'heroicon-o-cog-6-tooth', 'is_active' => true, 'sort_order' => 2],
            ['category_id' => $categoryIds[2], 'name' => ['ar' => 'تركيب مكيف جديد', 'en' => 'New AC Installation'], 'description' => ['ar' => 'تركيب أجهزة تكييف جديدة', 'en' => 'New air conditioning unit installation'], 'price' => 300.00, 'points' => 300, 'icon' => 'heroicon-o-cog-6-tooth', 'is_active' => true, 'sort_order' => 3],
            // نجارة / Carpentry
            ['category_id' => $categoryIds[3], 'name' => ['ar' => 'تركيب أرفف', 'en' => 'Shelf Installation'], 'description' => ['ar' => 'تركيب أرفف خشبية', 'en' => 'Wooden shelf installation'], 'price' => 250.00, 'points' => 250, 'icon' => 'heroicon-o-cube', 'is_active' => true, 'sort_order' => 1],
            ['category_id' => $categoryIds[3], 'name' => ['ar' => 'إصلاح أبواب', 'en' => 'Door Repair'], 'description' => ['ar' => 'إصلاح وصيانة الأبواب الخشبية', 'en' => 'Wooden door repair and maintenance'], 'price' => 200.00, 'points' => 200, 'icon' => 'heroicon-o-cube', 'is_active' => true, 'sort_order' => 2],
            ['category_id' => $categoryIds[3], 'name' => ['ar' => 'تركيب مطابخ', 'en' => 'Kitchen Installation'], 'description' => ['ar' => 'تركيب مطابخ مخصصة', 'en' => 'Custom kitchen installation'], 'price' => 1500.00, 'points' => 1500, 'icon' => 'heroicon-o-cube', 'is_active' => true, 'sort_order' => 3],
            // دهان / Painting
            ['category_id' => $categoryIds[4], 'name' => ['ar' => 'دهان جدران', 'en' => 'Wall Painting'], 'description' => ['ar' => 'دهان داخلي وخارجي', 'en' => 'Interior and exterior painting'], 'price' => 400.00, 'points' => 400, 'icon' => 'heroicon-o-paint-brush', 'is_active' => true, 'sort_order' => 1],
            ['category_id' => $categoryIds[4], 'name' => ['ar' => 'دهان أبواب', 'en' => 'Door Painting'], 'description' => ['ar' => 'دهان وتجديد الأبواب', 'en' => 'Door painting and renewal'], 'price' => 150.00, 'points' => 150, 'icon' => 'heroicon-o-paint-brush', 'is_active' => true, 'sort_order' => 2],
            ['category_id' => $categoryIds[4], 'name' => ['ar' => 'دهان ديكورات', 'en' => 'Decorative Painting'], 'description' => ['ar' => 'دهان ديكورات مخصصة', 'en' => 'Custom decorative painting'], 'price' => 500.00, 'points' => 500, 'icon' => 'heroicon-o-paint-brush', 'is_active' => true, 'sort_order' => 3],
        ];

        foreach ($services as $service) {
            $existingService = Service::whereJsonContains('name->ar', $service['name']['ar'])
                ->where('category_id', $service['category_id'])
                ->first();

            if (!$existingService) {
                Service::create($service);
            } else {
                $existingService->update($service);
            }
        }

        // 3. Packages (الباقات)
        $packagesData = [
            [
                'name' => ['ar' => 'أساسي', 'en' => 'Basic'],
                'description' => ['ar' => 'باقة أساسية نصف سنوية تشمل الخدمات الأساسية', 'en' => 'Basic semi-annual package including essential services'],
                'price' => 594.00,
                'monthly_price' => 99.00,
                'duration_days' => 180,
                'discount_percentage' => 10,
                'color' => '#f97316',
                'icon' => '👑',
                'badge_text' => ['ar' => 'وفّر 10% على كل خدمة - نصف سنوي', 'en' => 'Save 10% on every service - Semi-annual'],
                'free_maintenance_visits' => 0,
                'warranty_months' => 0,
                'priority_booking' => false,
                'support_24_7' => false,
                'is_active' => true,
                'is_featured' => false,
                'sort_order' => 1,
            ],
            [
                'name' => ['ar' => 'فضي', 'en' => 'Silver'],
                'description' => ['ar' => 'باقة متوسطة نصف سنوية مع مميزات إضافية', 'en' => 'Medium semi-annual package with additional features'],
                'price' => 1194.00,
                'monthly_price' => 199.00,
                'duration_days' => 180,
                'discount_percentage' => 15,
                'color' => '#a855f7',
                'icon' => '⭐',
                'badge_text' => ['ar' => 'وفّر 15% على كل خدمة - نصف سنوي', 'en' => 'Save 15% on every service - Semi-annual'],
                'free_maintenance_visits' => 1,
                'warranty_months' => 3,
                'priority_booking' => false,
                'support_24_7' => false,
                'is_active' => true,
                'is_featured' => false,
                'sort_order' => 2,
            ],
            [
                'name' => ['ar' => 'ذهبي', 'en' => 'Gold'],
                'description' => ['ar' => 'باقة مميزة سنوية مع جميع المميزات', 'en' => 'Premium annual package with all features'],
                'price' => 4188.00,
                'monthly_price' => 349.00,
                'duration_days' => 365,
                'discount_percentage' => 20,
                'color' => '#eab308',
                'icon' => '💎',
                'badge_text' => ['ar' => 'وفّر 20% على كل خدمة - سنوي', 'en' => 'Save 20% on every service - Annual'],
                'free_maintenance_visits' => 3,
                'warranty_months' => 6,
                'priority_booking' => true,
                'support_24_7' => true,
                'is_active' => true,
                'is_featured' => true,
                'sort_order' => 3,
            ],
        ];

        $packageModels = [];
        foreach ($packagesData as $pkgData) {
            $existing = Package::whereJsonContains('name->ar', $pkgData['name']['ar'])->first();
            if (!$existing) {
                $packageModels[] = Package::create($pkgData);
            } else {
                $existing->update($pkgData);
                $packageModels[] = $existing;
            }
        }

        $basicPackage = $packageModels[0];
        $silverPackage = $packageModels[1];
        $goldPackage = $packageModels[2];

        // ربط الباقات بالأقسام
        $basicPackage->categories()->sync([
            $categoryIds[0] => ['discount_percentage' => 10],
            $categoryIds[1] => ['discount_percentage' => 10],
        ]);

        $silverPackage->categories()->sync([
            $categoryIds[0] => ['discount_percentage' => 15],
            $categoryIds[1] => ['discount_percentage' => 15],
            $categoryIds[2] => ['discount_percentage' => 15],
        ]);

        $goldPackage->categories()->sync([
            $categoryIds[0] => ['discount_percentage' => 20],
            $categoryIds[1] => ['discount_percentage' => 20],
            $categoryIds[2] => ['discount_percentage' => 20],
            $categoryIds[3] => ['discount_percentage' => 20],
            $categoryIds[4] => ['discount_percentage' => 20],
        ]);

        // 4. Package Features (مميزات الباقات)
        $basicFeatures = [
            ['package_id' => $basicPackage->id, 'feature' => ['ar' => 'كهرباء', 'en' => 'Electrical'], 'icon' => '✅', 'sort_order' => 1],
            ['package_id' => $basicPackage->id, 'feature' => ['ar' => 'تكييف', 'en' => 'Air Conditioning'], 'icon' => '✅', 'sort_order' => 2],
            ['package_id' => $basicPackage->id, 'feature' => ['ar' => 'سباكة', 'en' => 'Plumbing'], 'icon' => '✅', 'sort_order' => 3],
        ];

        $silverFeatures = [
            ['package_id' => $silverPackage->id, 'feature' => ['ar' => 'خصم 15% على جميع الخدمات', 'en' => '15% discount on all services'], 'icon' => '✅', 'sort_order' => 1],
            ['package_id' => $silverPackage->id, 'feature' => ['ar' => 'زيارة صيانة مجانية واحدة', 'en' => 'One free maintenance visit'], 'icon' => '✅', 'sort_order' => 2],
            ['package_id' => $silverPackage->id, 'feature' => ['ar' => 'ضمان 3 أشهر على العمل', 'en' => '3 months work warranty'], 'icon' => '✅', 'sort_order' => 3],
        ];

        $goldFeatures = [
            ['package_id' => $goldPackage->id, 'feature' => ['ar' => 'خصم 20% على جميع الخدمات', 'en' => '20% discount on all services'], 'icon' => '✅', 'sort_order' => 1],
            ['package_id' => $goldPackage->id, 'feature' => ['ar' => '3 زيارات صيانة مجانية', 'en' => '3 free maintenance visits'], 'icon' => '✅', 'sort_order' => 2],
            ['package_id' => $goldPackage->id, 'feature' => ['ar' => 'ضمان 6 أشهر على العمل', 'en' => '6 months work warranty'], 'icon' => '✅', 'sort_order' => 3],
            ['package_id' => $goldPackage->id, 'feature' => ['ar' => 'أولوية الحجز', 'en' => 'Priority booking'], 'icon' => '✅', 'sort_order' => 4],
            ['package_id' => $goldPackage->id, 'feature' => ['ar' => 'دعم 24/7', 'en' => '24/7 Support'], 'icon' => '✅', 'sort_order' => 5],
        ];

        foreach ([$basicPackage, $silverPackage, $goldPackage] as $pkg) {
            $pkg->features()->delete();
        }

        foreach (array_merge($basicFeatures, $silverFeatures, $goldFeatures) as $feature) {
            PackageFeature::create($feature);
        }

        // 5. Property Types (أنواع العقارات)
        $propertyTypesData = [
            ['name' => ['ar' => 'فيلا مستقلة', 'en' => 'Standalone Villa'], 'icon' => '🏠', 'is_active' => true, 'sort_order' => 1],
            ['name' => ['ar' => 'شقة', 'en' => 'Apartment'], 'icon' => '🏢', 'is_active' => true, 'sort_order' => 2],
            ['name' => ['ar' => 'دوبلكس', 'en' => 'Duplex'], 'icon' => '🏘️', 'is_active' => true, 'sort_order' => 3],
            ['name' => ['ar' => 'قصر', 'en' => 'Palace'], 'icon' => '🏰', 'is_active' => true, 'sort_order' => 4],
            ['name' => ['ar' => 'استراحة', 'en' => 'Resort'], 'icon' => '🏡', 'is_active' => true, 'sort_order' => 5],
            ['name' => ['ar' => 'مبنى تجاري', 'en' => 'Commercial Building'], 'icon' => '🏬', 'is_active' => true, 'sort_order' => 6],
        ];

        $propertyTypeModels = [];
        foreach ($propertyTypesData as $ptData) {
            $existing = PropertyType::whereJsonContains('name->ar', $ptData['name']['ar'])->first();
            if (!$existing) {
                $propertyTypeModels[] = PropertyType::create($ptData);
            } else {
                $existing->update($ptData);
                $propertyTypeModels[] = $existing;
            }
        }

        // 6. Additional Facilities (المرافق الإضافية)
        $facilitiesData = [
            ['name' => ['ar' => 'غرفة', 'en' => 'Room'], 'price' => 20.00, 'icon' => '🛏️', 'is_active' => true, 'sort_order' => 1],
            ['name' => ['ar' => 'حمام', 'en' => 'Bathroom'], 'price' => 20.00, 'icon' => '🚿', 'is_active' => true, 'sort_order' => 2],
            ['name' => ['ar' => 'مطبخ', 'en' => 'Kitchen'], 'price' => 20.00, 'icon' => '🍳', 'is_active' => true, 'sort_order' => 3],
            ['name' => ['ar' => 'غرفة فندقية', 'en' => 'Hotel Room'], 'price' => 20.00, 'icon' => '🏨', 'is_active' => true, 'sort_order' => 4],
            ['name' => ['ar' => 'صالة', 'en' => 'Living Room'], 'price' => 25.00, 'icon' => '🛋️', 'is_active' => true, 'sort_order' => 5],
            ['name' => ['ar' => 'مجلس', 'en' => 'Majlis'], 'price' => 25.00, 'icon' => '🪑', 'is_active' => true, 'sort_order' => 6],
            ['name' => ['ar' => 'مسبح', 'en' => 'Swimming Pool'], 'price' => 50.00, 'icon' => '🏊', 'is_active' => true, 'sort_order' => 7],
            ['name' => ['ar' => 'حديقة', 'en' => 'Garden'], 'price' => 30.00, 'icon' => '🌿', 'is_active' => true, 'sort_order' => 8],
            ['name' => ['ar' => 'جراج', 'en' => 'Garage'], 'price' => 15.00, 'icon' => '🚗', 'is_active' => true, 'sort_order' => 9],
        ];

        $facilityModels = [];
        foreach ($facilitiesData as $facData) {
            $existing = AdditionalFacility::whereJsonContains('name->ar', $facData['name']['ar'])->first();
            if (!$existing) {
                $facilityModels[] = AdditionalFacility::create($facData);
            } else {
                $existing->update($facData);
                $facilityModels[] = $existing;
            }
        }

        // 7. Clients (العملاء)
        $clients = [
            ['name' => 'أحمد محمد العلي', 'email' => 'ahmed.ali@example.com', 'phone' => '+966501234567', 'gender' => 'Male', 'birth_date' => '1985-05-15', 'address' => 'حي النزهة، شارع الملك فهد', 'city' => 'الرياض', 'is_active' => true],
            ['name' => 'فاطمة عبدالله السالم', 'email' => 'fatima.salem@example.com', 'phone' => '+966502345678', 'gender' => 'Female', 'birth_date' => '1990-08-20', 'address' => 'حي العليا، شارع التحلية', 'city' => 'الرياض', 'is_active' => true],
            ['name' => 'خالد سعد الدوسري', 'email' => 'khalid.dosari@example.com', 'phone' => '+966503456789', 'gender' => 'Male', 'birth_date' => '1988-03-10', 'address' => 'حي الصفا، شارع الأمير سلطان', 'city' => 'جدة', 'is_active' => true],
            ['name' => 'سارة علي القحطاني', 'email' => 'sara.qhtani@example.com', 'phone' => '+966504567890', 'gender' => 'Female', 'birth_date' => '1992-11-25', 'address' => 'حي الروضة، شارع العليا', 'city' => 'الدمام', 'is_active' => true],
            ['name' => 'محمد فهد الحربي', 'email' => 'mohammed.harbi@example.com', 'phone' => '+966505678901', 'gender' => 'Male', 'birth_date' => '1987-07-12', 'address' => 'حي المطار، شارع الملك خالد', 'city' => 'الرياض', 'is_active' => true],
            ['name' => 'نورة حسن الشمري', 'email' => 'nora.shamri@example.com', 'phone' => '+966506789012', 'gender' => 'Female', 'birth_date' => '1995-02-18', 'address' => 'حي الزهراء، شارع الجامعة', 'city' => 'الرياض', 'is_active' => true],
            ['name' => 'عبدالرحمن يوسف العتيبي', 'email' => 'abdulrahman.otaibi@example.com', 'phone' => '+966507890123', 'gender' => 'Male', 'birth_date' => '1989-09-30', 'address' => 'حي السليمانية، شارع العروبة', 'city' => 'الرياض', 'is_active' => true],
            ['name' => 'لينا عبدالعزيز المطيري', 'email' => 'lina.mutairi@example.com', 'phone' => '+966508901234', 'gender' => 'Female', 'birth_date' => '1993-04-05', 'address' => 'حي الياسمين، شارع الأمير محمد', 'city' => 'جدة', 'is_active' => true],
            ['name' => 'يوسف ناصر الغامدي', 'email' => 'youssef.ghamdi@example.com', 'phone' => '+966509012345', 'gender' => 'Male', 'birth_date' => '1991-12-22', 'address' => 'حي الفيصلية، شارع الملك عبدالعزيز', 'city' => 'الدمام', 'is_active' => true],
            ['name' => 'ريم عبدالله الزهراني', 'email' => 'reem.zahrani@example.com', 'phone' => '+966500123456', 'gender' => 'Female', 'birth_date' => '1994-06-14', 'address' => 'حي الشفا، شارع العليا', 'city' => 'الرياض', 'is_active' => true],
        ];

        $clientIds = [];
        foreach ($clients as $client) {
            $clientModel = Client::firstOrCreate(['email' => $client['email']], $client);
            $clientIds[] = $clientModel->id;
        }

        // 8. Technicians (الفنيين)
        $technicians = [
            ['name' => 'ياسين علي الأحمد', 'email' => 'yassin.ahmad@example.com', 'phone' => '+966501111111', 'gender' => 'Male', 'service_id' => Service::where('category_id', $categoryIds[0])->first()->id, 'is_active' => true, 'bio' => 'فني كهرباء محترف بخبرة 10 سنوات', 'hourly_rate' => 80.00],
            ['name' => 'محمد حسن الصالح', 'email' => 'mohammed.saleh@example.com', 'phone' => '+966502222222', 'gender' => 'Male', 'service_id' => Service::where('category_id', $categoryIds[1])->first()->id, 'is_active' => true, 'bio' => 'فني سباكة متخصص في إصلاح التسريبات', 'hourly_rate' => 70.00],
            ['name' => 'علي أحمد المالكي', 'email' => 'ali.maliki@example.com', 'phone' => '+966503333333', 'gender' => 'Male', 'service_id' => Service::where('category_id', $categoryIds[2])->first()->id, 'is_active' => true, 'bio' => 'خبير في صيانة وتركيب أجهزة التكييف', 'hourly_rate' => 90.00],
            ['name' => 'سعد عبدالله النجار', 'email' => 'saad.najjar@example.com', 'phone' => '+966504444444', 'gender' => 'Male', 'service_id' => Service::where('category_id', $categoryIds[3])->first()->id, 'is_active' => true, 'bio' => 'نجار محترف في الديكورات الخشبية', 'hourly_rate' => 100.00],
            ['name' => 'حسن يوسف الرسام', 'email' => 'hassan.rasam@example.com', 'phone' => '+966505555555', 'gender' => 'Male', 'service_id' => Service::where('category_id', $categoryIds[4])->first()->id, 'is_active' => true, 'bio' => 'فني دهان متخصص في الديكورات', 'hourly_rate' => 85.00],
            ['name' => 'فهد محمد الكهربائي', 'email' => 'fahad.kahrabai@example.com', 'phone' => '+966506666666', 'gender' => 'Male', 'service_id' => Service::where('category_id', $categoryIds[0])->skip(1)->first()->id, 'is_active' => true, 'bio' => 'فني كهرباء متخصص في القواطع', 'hourly_rate' => 75.00],
        ];

        foreach ($technicians as $tech) {
            Technician::firstOrCreate(['email' => $tech['email']], $tech);
        }

        // 9. Subscriptions (الاشتراكات) + Property Types + Facilities
        // First, clear old subscription pivot data
        DB::table('subscription_properties')->truncate();
        DB::table('subscription_facilities')->truncate();

        $subscriptions = [
            // نشط - باقة ذهبية سنوية - فيلا مستقلة
            ['client_id' => $clientIds[0], 'package_id' => $goldPackage->id, 'start_date' => now()->subDays(30)->toDateString(), 'end_date' => now()->addDays(335)->toDateString(), 'status' => 'active', 'payment_method' => 'visa', 'payment_status' => 'paid', 'amount_paid' => 4188.00],
            // نشط - باقة فضية نصف سنوية - شقة
            ['client_id' => $clientIds[1], 'package_id' => $silverPackage->id, 'start_date' => now()->subDays(60)->toDateString(), 'end_date' => now()->addDays(120)->toDateString(), 'status' => 'active', 'payment_method' => 'mada', 'payment_status' => 'paid', 'amount_paid' => 1194.00],
            // نشط - باقة أساسية نصف سنوية - دوبلكس
            ['client_id' => $clientIds[2], 'package_id' => $basicPackage->id, 'start_date' => now()->subDays(90)->toDateString(), 'end_date' => now()->addDays(90)->toDateString(), 'status' => 'active', 'payment_method' => 'cash', 'payment_status' => 'paid', 'amount_paid' => 594.00],
            // نشط - باقة ذهبية سنوية - قصر
            ['client_id' => $clientIds[3], 'package_id' => $goldPackage->id, 'start_date' => now()->subDays(10)->toDateString(), 'end_date' => now()->addDays(355)->toDateString(), 'status' => 'active', 'payment_method' => 'transfer', 'payment_status' => 'paid', 'amount_paid' => 4188.00],
            // منتهي - باقة فضية نصف سنوية
            ['client_id' => $clientIds[4], 'package_id' => $silverPackage->id, 'start_date' => now()->subDays(200)->toDateString(), 'end_date' => now()->subDays(20)->toDateString(), 'status' => 'expired', 'payment_method' => 'visa', 'payment_status' => 'paid', 'amount_paid' => 1194.00],
            // منتهي - باقة أساسية نصف سنوية
            ['client_id' => $clientIds[5], 'package_id' => $basicPackage->id, 'start_date' => now()->subDays(210)->toDateString(), 'end_date' => now()->subDays(30)->toDateString(), 'status' => 'expired', 'payment_method' => 'cash', 'payment_status' => 'paid', 'amount_paid' => 594.00],
            // معلق - باقة فضية نصف سنوية
            ['client_id' => $clientIds[6], 'package_id' => $silverPackage->id, 'start_date' => now()->subDays(5)->toDateString(), 'end_date' => now()->addDays(175)->toDateString(), 'status' => 'suspended', 'payment_method' => 'visa', 'payment_status' => 'pending', 'amount_paid' => 0],
            // ملغي - باقة أساسية نصف سنوية
            ['client_id' => $clientIds[7], 'package_id' => $basicPackage->id, 'start_date' => now()->subDays(50)->toDateString(), 'end_date' => now()->addDays(130)->toDateString(), 'status' => 'cancelled', 'payment_method' => 'cash', 'payment_status' => 'refunded', 'amount_paid' => 594.00, 'cancelled_at' => now()->subDays(45)],
        ];

        $subscriptionModels = [];
        foreach ($subscriptions as $sub) {
            $model = Subscription::firstOrCreate(
                ['client_id' => $sub['client_id'], 'package_id' => $sub['package_id'], 'start_date' => $sub['start_date']],
                $sub
            );
            $subscriptionModels[] = $model;
        }

        // Attach property types and facilities to subscriptions
        // Sub 1: فيلا مستقلة - 6 غرف، 2 حمام، 1 مطبخ
        if (isset($subscriptionModels[0])) {
            $subscriptionModels[0]->propertyTypes()->syncWithoutDetaching([
                $propertyTypeModels[0]->id => ['quantity' => 1], // فيلا مستقلة
            ]);
            $subscriptionModels[0]->facilities()->syncWithoutDetaching([
                $facilityModels[0]->id => ['quantity' => 6, 'unit_price' => 20.00, 'total_price' => 120.00], // غرفة
                $facilityModels[1]->id => ['quantity' => 3, 'unit_price' => 20.00, 'total_price' => 60.00],  // حمام
                $facilityModels[2]->id => ['quantity' => 1, 'unit_price' => 20.00, 'total_price' => 20.00],  // مطبخ
                $facilityModels[4]->id => ['quantity' => 2, 'unit_price' => 25.00, 'total_price' => 50.00],  // صالة
                $facilityModels[5]->id => ['quantity' => 1, 'unit_price' => 25.00, 'total_price' => 25.00],  // مجلس
            ]);
        }

        // Sub 2: شقة - 3 غرف، 2 حمام، 1 مطبخ
        if (isset($subscriptionModels[1])) {
            $subscriptionModels[1]->propertyTypes()->syncWithoutDetaching([
                $propertyTypeModels[1]->id => ['quantity' => 1], // شقة
            ]);
            $subscriptionModels[1]->facilities()->syncWithoutDetaching([
                $facilityModels[0]->id => ['quantity' => 3, 'unit_price' => 20.00, 'total_price' => 60.00],  // غرفة
                $facilityModels[1]->id => ['quantity' => 2, 'unit_price' => 20.00, 'total_price' => 40.00],  // حمام
                $facilityModels[2]->id => ['quantity' => 1, 'unit_price' => 20.00, 'total_price' => 20.00],  // مطبخ
                $facilityModels[4]->id => ['quantity' => 1, 'unit_price' => 25.00, 'total_price' => 25.00],  // صالة
            ]);
        }

        // Sub 3: دوبلكس - 4 غرف، 3 حمامات، 1 مطبخ
        if (isset($subscriptionModels[2])) {
            $subscriptionModels[2]->propertyTypes()->syncWithoutDetaching([
                $propertyTypeModels[2]->id => ['quantity' => 1], // دوبلكس
            ]);
            $subscriptionModels[2]->facilities()->syncWithoutDetaching([
                $facilityModels[0]->id => ['quantity' => 4, 'unit_price' => 20.00, 'total_price' => 80.00],
                $facilityModels[1]->id => ['quantity' => 3, 'unit_price' => 20.00, 'total_price' => 60.00],
                $facilityModels[2]->id => ['quantity' => 1, 'unit_price' => 20.00, 'total_price' => 20.00],
                $facilityModels[4]->id => ['quantity' => 2, 'unit_price' => 25.00, 'total_price' => 50.00],
            ]);
        }

        // Sub 4: قصر - 10 غرف، 5 حمامات، 2 مطبخ، مسبح، حديقة
        if (isset($subscriptionModels[3])) {
            $subscriptionModels[3]->propertyTypes()->syncWithoutDetaching([
                $propertyTypeModels[3]->id => ['quantity' => 1], // قصر
            ]);
            $subscriptionModels[3]->facilities()->syncWithoutDetaching([
                $facilityModels[0]->id => ['quantity' => 10, 'unit_price' => 20.00, 'total_price' => 200.00], // غرفة
                $facilityModels[1]->id => ['quantity' => 5, 'unit_price' => 20.00, 'total_price' => 100.00],  // حمام
                $facilityModels[2]->id => ['quantity' => 2, 'unit_price' => 20.00, 'total_price' => 40.00],   // مطبخ
                $facilityModels[4]->id => ['quantity' => 3, 'unit_price' => 25.00, 'total_price' => 75.00],   // صالة
                $facilityModels[5]->id => ['quantity' => 2, 'unit_price' => 25.00, 'total_price' => 50.00],   // مجلس
                $facilityModels[6]->id => ['quantity' => 1, 'unit_price' => 50.00, 'total_price' => 50.00],   // مسبح
                $facilityModels[7]->id => ['quantity' => 1, 'unit_price' => 30.00, 'total_price' => 30.00],   // حديقة
                $facilityModels[8]->id => ['quantity' => 2, 'unit_price' => 15.00, 'total_price' => 30.00],   // جراج
            ]);
        }

        // Sub 5: شقة
        if (isset($subscriptionModels[4])) {
            $subscriptionModels[4]->propertyTypes()->syncWithoutDetaching([
                $propertyTypeModels[1]->id => ['quantity' => 1],
            ]);
            $subscriptionModels[4]->facilities()->syncWithoutDetaching([
                $facilityModels[0]->id => ['quantity' => 2, 'unit_price' => 20.00, 'total_price' => 40.00],
                $facilityModels[1]->id => ['quantity' => 1, 'unit_price' => 20.00, 'total_price' => 20.00],
                $facilityModels[2]->id => ['quantity' => 1, 'unit_price' => 20.00, 'total_price' => 20.00],
            ]);
        }

        // 10. Client Points (رصيد النقاط للعملاء)
        $pointsData = [
            ['client_id' => $clientIds[0], 'balance' => 500],
            ['client_id' => $clientIds[1], 'balance' => 300],
            ['client_id' => $clientIds[2], 'balance' => 200],
            ['client_id' => $clientIds[3], 'balance' => 800],
            ['client_id' => $clientIds[4], 'balance' => 0],
            ['client_id' => $clientIds[5], 'balance' => 150],
            ['client_id' => $clientIds[6], 'balance' => 100],
            ['client_id' => $clientIds[7], 'balance' => 0],
            ['client_id' => $clientIds[8], 'balance' => 250],
            ['client_id' => $clientIds[9], 'balance' => 400],
        ];

        foreach ($pointsData as $pointData) {
            $clientPoint = ClientPoint::firstOrCreate(
                ['client_id' => $pointData['client_id']],
                ['balance' => $pointData['balance']]
            );

            if ($pointData['balance'] > 0) {
                PointTransaction::firstOrCreate(
                    [
                        'client_id' => $pointData['client_id'],
                        'type' => 'earned',
                        'points' => $pointData['balance'],
                        'description' => 'نقاط ترحيبية أو من اشتراك',
                    ],
                    [
                        'balance_before' => 0,
                        'balance_after' => $pointData['balance'],
                    ]
                );
            }
        }
    }
}
