<?php

namespace Database\Seeders;

use App\Models\ClientRequest;
use App\Models\AboutSection;
use App\Models\ClientSubscription;
use App\Models\Payment;
use App\Models\PaymentMethod;
use App\Models\GtsOrder;
use App\Models\GtsProvider;
use App\Models\GtsService;
use App\Models\GtsWallet;
use App\Models\AgencyNotification;
use App\Models\BrandSetting;
use App\Models\NotificationSetting;
use App\Models\Plan;
use App\Models\PortfolioProject;
use App\Models\RolePermission;
use App\Models\Service;
use App\Models\Setting;
use App\Models\Task;
use App\Models\TeamMember;
use App\Models\User;
use App\Models\WebsiteSetting;
use App\Models\SystemSetting;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        $admin = User::updateOrCreate(
            ['email' => 'admin@mgg.test'],
            ['name' => 'Admin Demo', 'password' => Hash::make('password'), 'role' => 'admin', 'phone' => '+92 300 0000000', 'status' => 'active']
        );

        $client = User::updateOrCreate(
            ['email' => 'client@mgg.test'],
            ['name' => 'Client Demo', 'password' => Hash::make('password'), 'role' => 'client', 'client_type' => 'plan', 'phone' => '+92 301 0000000', 'status' => 'active']
        );

        $designer = User::updateOrCreate(
            ['email' => 'designer@mgg.test'],
            ['name' => 'Designer Demo', 'password' => Hash::make('password'), 'role' => 'designer', 'phone' => '+92 302 0000000', 'status' => 'active']
        );

        $gtsClient = User::updateOrCreate(
            ['email' => 'gts-client@mgg.test'],
            ['name' => 'GTS Client Demo', 'business_name' => 'Trusted Seller Buyer', 'password' => Hash::make('password'), 'role' => 'gts_client', 'phone' => '+92 303 0000000', 'status' => 'active']
        );

        $services = collect([
            ['name' => 'Social Media Post Design', 'slug' => 'social-media-post-design', 'description' => 'Monthly social post systems for campaigns and launches.', 'icon' => 'palette'],
            ['name' => 'Advertisement Poster Design', 'slug' => 'advertisement-poster-design', 'description' => 'Sales posters, event offers, and high-conversion ads.', 'icon' => 'poster'],
            ['name' => 'Logo Design', 'slug' => 'logo-design', 'description' => 'Memorable identity marks and presentation versions.', 'icon' => 'badge'],
            ['name' => 'Banner Design', 'slug' => 'banner-design', 'description' => 'Web, print, and social channel banners.', 'icon' => 'banner'],
            ['name' => 'Brand Identity', 'slug' => 'brand-identity', 'description' => 'Logo, colors, stationery, and brand design kits.', 'icon' => 'spark'],
            ['name' => 'Meta Ads', 'slug' => 'meta-ads', 'description' => 'Meta ad creative and campaign optimization.', 'icon' => 'target'],
            ['name' => 'Video Editing', 'slug' => 'video-editing', 'description' => 'Reels, promos, captions, and short videos.', 'icon' => 'video'],
            ['name' => 'Reel Cover Design', 'slug' => 'reel-cover-design', 'description' => 'Scroll-stopping covers for video libraries.', 'icon' => 'reel'],
            ['name' => 'Website Development', 'slug' => 'website-development', 'description' => 'Business sites and Laravel systems.', 'icon' => 'code'],
            ['name' => 'Real Estate Marketing Design', 'slug' => 'real-estate-marketing-design', 'description' => 'Listings, project launches, and lead visuals.', 'icon' => 'home'],
        ])->map(fn ($service) => Service::updateOrCreate(['slug' => $service['slug']], $service));

        $plans = collect([
            ['name' => 'Starter', 'price' => 15000, 'billing_cycle' => 'monthly', 'duration_days' => 30, 'total_posts' => 12, 'reels' => 2, 'stories' => 8, 'designs' => 12, 'ads_included' => false, 'work_limit' => 12, 'features' => ['12 monthly designs', 'Basic support', 'Monthly report'], 'status' => 'active'],
            ['name' => 'Growth', 'price' => 30000, 'billing_cycle' => 'monthly', 'duration_days' => 30, 'total_posts' => 24, 'reels' => 6, 'stories' => 16, 'designs' => 28, 'ads_included' => true, 'work_limit' => 28, 'features' => ['Ad creatives', 'Priority support', 'Monthly strategy'], 'status' => 'active'],
            ['name' => 'Custom', 'price' => 0, 'billing_cycle' => 'custom', 'duration_days' => 30, 'total_posts' => 0, 'reels' => 0, 'stories' => 0, 'designs' => 0, 'ads_included' => true, 'work_limit' => 0, 'features' => ['Custom work limit', 'Dedicated manager', 'Flexible services'], 'status' => 'active'],
        ])->map(fn ($plan) => Plan::updateOrCreate(['name' => $plan['name']], $plan));

        ClientSubscription::updateOrCreate(
            ['user_id' => $client->id],
            ['plan_id' => $plans[1]->id, 'starts_at' => now()->startOfMonth(), 'ends_at' => now()->endOfMonth(), 'status' => 'active', 'usage_count' => 7]
        );

        $request = ClientRequest::updateOrCreate(
            ['user_id' => $client->id, 'title' => 'Eid campaign post set'],
            ['service_id' => $services[0]->id, 'request_type' => 'social_post', 'details' => 'Create five social posts with the sky blue agency brand theme.', 'deadline' => now()->addDays(5), 'status' => 'approved']
        );

        Task::updateOrCreate(
            ['title' => 'Design Eid campaign post set'],
            ['client_request_id' => $request->id, 'client_id' => $client->id, 'designer_id' => $designer->id, 'details' => 'Prepare editable source files and export PNG files.', 'priority' => 'high', 'deadline' => now()->addDays(3), 'status' => 'assigned']
        );

        Payment::updateOrCreate(
            ['user_id' => $client->id, 'transaction_reference' => 'DEMO-001'],
            ['plan_id' => $plans[1]->id, 'amount' => 30000, 'method' => 'Bank Transfer', 'status' => 'pending']
        );

        foreach ([
            ['title' => 'Restaurant Social Kit', 'category' => 'Social Media Designs', 'description' => 'Bold food campaign visuals for a launch month.'],
            ['title' => 'Real Estate Campaign', 'category' => 'Real Estate Designs', 'description' => 'Lead generation posts and listing creatives.'],
            ['title' => 'Brand Identity System', 'category' => 'Branding', 'description' => 'Logo, typography, colors, and business stationery.'],
        ] as $project) {
            PortfolioProject::updateOrCreate(['title' => $project['title']], $project + ['status' => 'published']);
        }

        foreach ([
            ['section_key' => 'story', 'title' => 'Creative work organized from request to delivery', 'subtitle' => 'Our Story', 'body' => 'M Ghaffar Graphics helps brands manage social media designs, branding, ads, websites, video work, and seller services through a clear production system.', 'icon' => 'MGG', 'sort_order' => 1],
            ['section_key' => 'mission', 'title' => 'Mission & Vision', 'subtitle' => 'What we believe', 'body' => 'Give every client a transparent plan, every designer a clean task list, and every admin a reliable operating dashboard for approvals, payments, files, and delivery.', 'icon' => 'MV', 'sort_order' => 2],
            ['section_key' => 'skills', 'title' => 'Core Skills', 'subtitle' => 'What we do best', 'body' => "Social media post design\nBrand identity systems\nMeta ads creative\nVideo editing and reel covers\nWebsite and landing page design\nReal estate and restaurant campaigns", 'icon' => 'SK', 'sort_order' => 3],
            ['section_key' => 'education', 'title' => 'Learning & Process', 'subtitle' => 'How quality improves', 'body' => 'We combine design practice, campaign research, client feedback, and delivery reports to improve every brief, visual style, and production handoff.', 'icon' => 'ED', 'sort_order' => 4],
            ['section_key' => 'values', 'title' => 'Values', 'subtitle' => 'How we work', 'body' => 'Fast communication, organized files, clear approvals, honest pricing, and consistent brand quality.', 'icon' => 'VL', 'sort_order' => 5],
        ] as $section) {
            AboutSection::updateOrCreate(['section_key' => $section['section_key']], $section + ['status' => 'active']);
        }

        foreach ([
            ['name' => 'Admin Demo', 'role_title' => 'Agency Operations Lead', 'bio' => 'Manages clients, plans, payments, requests, reports, and delivery approvals.', 'skills' => ['Client management', 'Reports', 'Payment review'], 'education' => 'Agency systems and client operations', 'experience' => 'Digital workflow management', 'sort_order' => 1],
            ['name' => 'Designer Demo', 'role_title' => 'Creative Designer', 'bio' => 'Creates social posts, campaign visuals, brand kits, and revision-ready design files.', 'skills' => ['Social design', 'Branding', 'Real estate creatives'], 'education' => 'Graphic design and campaign practice', 'experience' => 'Social media and branding projects', 'sort_order' => 2],
            ['name' => 'GTS Support', 'role_title' => 'Seller Service Coordinator', 'bio' => 'Supports GTS service selection, wallet deposits, provider order tracking, and delivery updates.', 'skills' => ['SMM services', 'Order tracking', 'Support'], 'education' => 'Seller service operations', 'experience' => 'Social media service delivery', 'sort_order' => 3],
        ] as $member) {
            TeamMember::updateOrCreate(['name' => $member['name']], $member + ['status' => 'active']);
        }

        foreach (['JazzCash', 'EasyPaisa', 'Meezan Bank', 'Bank Transfer'] as $method) {
            PaymentMethod::updateOrCreate(['name' => $method], ['method_name' => $method, 'status' => 'active', 'instructions' => 'Upload transaction ID and screenshot for admin approval.']);
        }

        $demoProvider = GtsProvider::updateOrCreate(
            ['name' => 'Demo SMM Provider'],
            ['api_url' => 'https://example-smm-provider.test/api/v2', 'api_key' => 'demo-api-key', 'status' => 'inactive', 'balance' => 0]
        );
        $fastSmmApiKey = env('FASTSMMSTORE_API_KEY');
        $fastSmmProvider = GtsProvider::updateOrCreate(
            ['name' => 'FastSMMStore'],
            ['api_url' => env('FASTSMMSTORE_API_URL', 'https://fastsmmstore.com/api/v2'), 'api_key' => $fastSmmApiKey ?: 'set FASTSMMSTORE_API_KEY in .env', 'status' => $fastSmmApiKey ? 'active' : 'inactive', 'balance' => 0]
        );

        $gtsServices = collect([
            ['category' => 'TikTok', 'name' => 'TikTok Likes', 'description' => 'Post like delivery points.', 'min_quantity' => 500, 'max_quantity' => 20000, 'rate_per_1000' => 180],
            ['category' => 'TikTok', 'name' => 'TikTok Followers', 'description' => 'Follower boost packages.', 'min_quantity' => 100, 'max_quantity' => 5000, 'rate_per_1000' => 850],
            ['category' => 'TikTok', 'name' => 'TikTok Views', 'description' => 'High retention view packages.', 'min_quantity' => 1000, 'max_quantity' => 500000, 'rate_per_1000' => 35],
            ['category' => 'TikTok', 'name' => 'TikTok Comments', 'description' => 'Real comment engagement packages.', 'min_quantity' => 100, 'max_quantity' => 1500, 'rate_per_1000' => 1920],
            ['category' => 'Instagram', 'name' => 'Instagram Followers', 'description' => 'Profile growth packs.', 'min_quantity' => 1000, 'max_quantity' => 10000, 'rate_per_1000' => 1299],
            ['category' => 'Instagram', 'name' => 'Instagram Post Likes', 'description' => 'Post likes delivery packs.', 'min_quantity' => 1000, 'max_quantity' => 50000, 'rate_per_1000' => 180],
            ['category' => 'Instagram', 'name' => 'Instagram Comments', 'description' => 'Comment engagement packs.', 'min_quantity' => 1000, 'max_quantity' => 10000, 'rate_per_1000' => 390],
            ['category' => 'Facebook', 'name' => 'Facebook Reactions', 'description' => 'Engagement for posts.', 'min_quantity' => 1000, 'max_quantity' => 50000, 'rate_per_1000' => 240],
            ['category' => 'Facebook', 'name' => 'Facebook Page Followers', 'description' => 'Page and profile follower packs.', 'min_quantity' => 1000, 'max_quantity' => 50000, 'rate_per_1000' => 410],
            ['category' => 'WhatsApp', 'name' => 'WhatsApp Poll Votes', 'description' => 'Poll vote service.', 'min_quantity' => 100, 'max_quantity' => 10000, 'rate_per_1000' => 2500],
            ['category' => 'Premium Account', 'name' => 'UK Account', 'description' => 'Premium verified account sourcing.', 'min_quantity' => 1, 'max_quantity' => 10, 'rate_per_1000' => 999000],
        ])->map(fn ($service) => GtsService::updateOrCreate(['category' => $service['category'], 'name' => $service['name']], $service + ['gts_provider_id' => $demoProvider->id, 'provider_service_id' => null, 'provider_rate_per_1000' => 0, 'profit_percent' => 0, 'auto_submit' => false, 'status' => 'active']));
        foreach ([
            ['provider_service_id' => '8219', 'category' => 'WhatsApp', 'name' => 'WhatsApp Channel Members', 'description' => 'Real high quality members. Provider sample mapped for auto API orders.', 'min_quantity' => 10, 'max_quantity' => 10000, 'provider_rate_per_1000' => 2.22],
            ['provider_service_id' => '9808', 'category' => 'WhatsApp', 'name' => 'WhatsApp Poll Votes Option A', 'description' => 'Ultra fast poll vote sample service.', 'min_quantity' => 10, 'max_quantity' => 2000, 'provider_rate_per_1000' => 5.52],
            ['provider_service_id' => '9263', 'category' => 'Telegram', 'name' => 'Telegram Post Views', 'description' => 'Fast Telegram post views sample service.', 'min_quantity' => 10, 'max_quantity' => 1000000, 'provider_rate_per_1000' => 0.0108],
            ['provider_service_id' => '8739', 'category' => 'LinkedIn', 'name' => 'LinkedIn Followers USA', 'description' => 'LinkedIn follower sample service with refill support.', 'min_quantity' => 10, 'max_quantity' => 1000000, 'provider_rate_per_1000' => 14.30, 'refill_enabled' => true],
        ] as $service) {
            $profit = 30;
            GtsService::updateOrCreate(
                ['gts_provider_id' => $fastSmmProvider->id, 'provider_service_id' => $service['provider_service_id']],
                $service + [
                    'gts_provider_id' => $fastSmmProvider->id,
                    'profit_percent' => $profit,
                    'rate_per_1000' => round($service['provider_rate_per_1000'] + (($service['provider_rate_per_1000'] * $profit) / 100), 4),
                    'auto_submit' => true,
                    'dripfeed_enabled' => false,
                    'status' => 'active',
                ]
            );
        }
        $gtsWallet = GtsWallet::updateOrCreate(['user_id' => $gtsClient->id], ['balance' => 5000, 'currency' => 'PKR', 'status' => 'active']);
        $gtsWallet->transactions()->updateOrCreate(['reference' => 'GTS-SEED-CREDIT'], ['type' => 'credit', 'amount' => 5000, 'note' => 'Demo wallet credit', 'status' => 'completed', 'applied_at' => now()]);
        GtsOrder::updateOrCreate(
            ['order_number' => 'GTS-DEMO-01'],
            ['user_id' => $gtsClient->id, 'gts_service_id' => $gtsServices[2]->id, 'target_link' => 'https://social.example/demo-video', 'quantity' => 10000, 'charge' => 350, 'progress' => 65, 'status' => 'processing']
        );

        AgencyNotification::updateOrCreate(['title' => 'Pending payment review'], ['body' => 'A client payment proof is ready for admin review.', 'audience' => 'admin', 'status' => 'unread']);
        WebsiteSetting::current()->update(['contact_number' => '03068665907', 'whatsapp_number' => '03068665907', 'email' => 'hello@mghaffargraphics.com', 'address' => 'Pakistan']);
        BrandSetting::current();
        SystemSetting::current();
        foreach (array_keys(\App\Http\Controllers\SettingsController::NOTIFICATIONS) as $type) {
            NotificationSetting::firstOrCreate(['notification_type' => $type]);
        }

        foreach ([
            'brand_name' => 'M Ghaffar Graphics',
            'office_hours' => 'Mon - Sat, 10:00 AM - 7:00 PM',
            'phone' => '03068665907',
            'email' => 'hello@mghaffargraphics.com',
            'address' => 'Pakistan',
            'demo_login_enabled' => '1',
            'client_registration_enabled' => '0',
            'client_portal_enabled' => '1',
            'gts_landing_enabled' => '1',
            'gts_portal_enabled' => '1',
            'gts_order_create_enabled' => '1',
            'gts_deposit_enabled' => '1',
            'theme_preset' => 'sky-sun',
            'card_finish' => 'gloss',
            'font_preset' => 'studio',
        ] as $key => $value) {
            Setting::updateOrCreate(['key' => $key], ['value' => $value]);
        }

        foreach (['view_dashboard', 'submit_requests'] as $permission) {
            RolePermission::updateOrCreate(
                ['role' => 'gts_client', 'permission_name' => $permission],
                ['allowed' => true]
            );
        }
    }
}
