<?php

namespace Database\Seeders;

use App\Models\Company;
use App\Models\Driver;
use App\Models\Load;
use App\Models\Package;
use App\Models\Payment;
use App\Models\PaymentMethod;
use App\Models\Subscription;
use App\Models\Truck;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class AdminDemoSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $stripe = PaymentMethod::firstWhere('provider', 'stripe');
        $basic = Package::firstWhere('name', 'Basic');
        $standard = Package::firstWhere('name', 'Standard');
        $premium = Package::firstWhere('name', 'Premium');

        $companies = [
            [
                'company' => [
                    'name' => 'Blue Horizon Freight',
                    'email' => 'ops@bluehorizonfreight.com',
                    'mc_number' => 'MC220011',
                    'dot_number' => 'DOT550011',
                    'address' => '1800 Logistics Pkwy, Dallas, TX 75247',
                    'phone' => '469-555-1101',
                    'plan' => 'growth',
                    'num_trucks' => 4,
                    'num_drivers' => 3,
                ],
                'owner' => [
                    'name' => 'Sarah Miles',
                    'email' => 'sarah@bluehorizonfreight.com',
                ],
                'package' => $standard,
                'billing_cycle' => 'monthly',
                'trucks' => [
                    ['number' => 'BHF-101', 'name' => 'Blue Horizon 101', 'equipment_number' => 'BHF-EQ-101', 'fuel_cost_per_mile' => 0.68],
                    ['number' => 'BHF-102', 'name' => 'Blue Horizon 102', 'equipment_number' => 'BHF-EQ-102', 'fuel_cost_per_mile' => 0.71],
                ],
                'drivers' => [
                    ['name' => 'Miles Carter', 'email' => 'miles.carter@bluehorizonfreight.com', 'phone' => '469-555-2001', 'truck_number' => 'BHF-101'],
                    ['name' => 'Janelle Ross', 'email' => 'janelle.ross@bluehorizonfreight.com', 'phone' => '469-555-2002', 'truck_number' => 'BHF-102'],
                    ['name' => 'Peter Long', 'email' => 'peter.long@bluehorizonfreight.com', 'phone' => '469-555-2003', 'truck_number' => null],
                ],
                'loads' => [
                    ['load_number' => 'BHF-LOAD-001', 'broker_company' => 'Western Brokers', 'pickup_location' => 'Dallas, TX', 'delivery_location' => 'Phoenix, AZ', 'pickup_date' => '2026-03-01', 'delivery_date' => '2026-03-03', 'weight' => 38500, 'gross_rate' => 4800, 'miles' => 1065, 'fuel_cost' => 724.20, 'driver_salary' => 1500, 'net_profit' => 2575.80, 'status' => 'completed', 'truck_number' => 'BHF-101', 'driver_email' => 'miles.carter@bluehorizonfreight.com'],
                    ['load_number' => 'BHF-LOAD-002', 'broker_company' => 'Cargo Union', 'pickup_location' => 'Houston, TX', 'delivery_location' => 'Atlanta, GA', 'pickup_date' => '2026-03-10', 'delivery_date' => '2026-03-13', 'weight' => 42000, 'gross_rate' => 5200, 'miles' => 794, 'fuel_cost' => 563.74, 'driver_salary' => 1680, 'net_profit' => 2956.26, 'status' => 'processed', 'truck_number' => 'BHF-102', 'driver_email' => 'janelle.ross@bluehorizonfreight.com'],
                ],
                'payments' => [
                    ['amount' => 185.00, 'status' => 'completed', 'created_at' => '2026-03-01 09:00:00', 'processed_at' => '2026-03-01 09:05:00'],
                    ['amount' => 185.00, 'status' => 'pending', 'created_at' => '2026-04-01 09:00:00', 'processed_at' => null],
                ],
            ],
            [
                'company' => [
                    'name' => 'Northline Cargo',
                    'email' => 'dispatch@northlinecargo.com',
                    'mc_number' => 'MC220022',
                    'dot_number' => 'DOT550022',
                    'address' => '4400 Northline Blvd, Chicago, IL 60632',
                    'phone' => '312-555-1401',
                    'plan' => 'starter',
                    'num_trucks' => 2,
                    'num_drivers' => 2,
                ],
                'owner' => [
                    'name' => 'Kevin Stone',
                    'email' => 'kevin@northlinecargo.com',
                ],
                'package' => $basic,
                'billing_cycle' => 'weekly',
                'trucks' => [
                    ['number' => 'NLC-201', 'name' => 'Northline 201', 'equipment_number' => 'NLC-EQ-201', 'fuel_cost_per_mile' => 0.64],
                ],
                'drivers' => [
                    ['name' => 'Carter Reed', 'email' => 'carter.reed@northlinecargo.com', 'phone' => '312-555-2401', 'truck_number' => 'NLC-201'],
                    ['name' => 'Ava Shaw', 'email' => 'ava.shaw@northlinecargo.com', 'phone' => '312-555-2402', 'truck_number' => null],
                ],
                'loads' => [
                    ['load_number' => 'NLC-LOAD-001', 'broker_company' => 'Midwest Freight', 'pickup_location' => 'Chicago, IL', 'delivery_location' => 'St. Louis, MO', 'pickup_date' => '2026-03-06', 'delivery_date' => '2026-03-07', 'weight' => 32000, 'gross_rate' => 2400, 'miles' => 297, 'fuel_cost' => 190.08, 'driver_salary' => 720, 'net_profit' => 1489.92, 'status' => 'completed', 'truck_number' => 'NLC-201', 'driver_email' => 'carter.reed@northlinecargo.com'],
                ],
                'payments' => [
                    ['amount' => 75.00, 'status' => 'completed', 'created_at' => '2026-03-20 08:00:00', 'processed_at' => '2026-03-20 08:05:00'],
                ],
            ],
            [
                'company' => [
                    'name' => 'Summit Fleet Group',
                    'email' => 'hello@summitfleetgroup.com',
                    'mc_number' => 'MC220033',
                    'dot_number' => 'DOT550033',
                    'address' => '980 Summit Park, Atlanta, GA 30318',
                    'phone' => '404-555-1601',
                    'plan' => 'enterprise',
                    'num_trucks' => 6,
                    'num_drivers' => 5,
                ],
                'owner' => [
                    'name' => 'Monica Price',
                    'email' => 'monica@summitfleetgroup.com',
                ],
                'package' => $premium,
                'billing_cycle' => 'monthly',
                'trucks' => [
                    ['number' => 'SFG-301', 'name' => 'Summit 301', 'equipment_number' => 'SFG-EQ-301', 'fuel_cost_per_mile' => 0.72],
                    ['number' => 'SFG-302', 'name' => 'Summit 302', 'equipment_number' => 'SFG-EQ-302', 'fuel_cost_per_mile' => 0.74],
                    ['number' => 'SFG-303', 'name' => 'Summit 303', 'equipment_number' => 'SFG-EQ-303', 'fuel_cost_per_mile' => 0.76],
                ],
                'drivers' => [
                    ['name' => 'Olivia Hart', 'email' => 'olivia.hart@summitfleetgroup.com', 'phone' => '404-555-2601', 'truck_number' => 'SFG-301'],
                    ['name' => 'Marcus Lee', 'email' => 'marcus.lee@summitfleetgroup.com', 'phone' => '404-555-2602', 'truck_number' => 'SFG-302'],
                    ['name' => 'Derek Young', 'email' => 'derek.young@summitfleetgroup.com', 'phone' => '404-555-2603', 'truck_number' => 'SFG-303'],
                ],
                'loads' => [
                    ['load_number' => 'SFG-LOAD-001', 'broker_company' => 'Atlantic Cargo', 'pickup_location' => 'Atlanta, GA', 'delivery_location' => 'Newark, NJ', 'pickup_date' => '2026-03-04', 'delivery_date' => '2026-03-06', 'weight' => 41000, 'gross_rate' => 6100, 'miles' => 872, 'fuel_cost' => 662.72, 'driver_salary' => 1820, 'net_profit' => 3617.28, 'status' => 'completed', 'truck_number' => 'SFG-301', 'driver_email' => 'olivia.hart@summitfleetgroup.com'],
                    ['load_number' => 'SFG-LOAD-002', 'broker_company' => 'Atlantic Cargo', 'pickup_location' => 'Nashville, TN', 'delivery_location' => 'Orlando, FL', 'pickup_date' => '2026-03-14', 'delivery_date' => '2026-03-16', 'weight' => 37000, 'gross_rate' => 5400, 'miles' => 690, 'fuel_cost' => 510.60, 'driver_salary' => 1605, 'net_profit' => 3284.40, 'status' => 'completed', 'truck_number' => 'SFG-302', 'driver_email' => 'marcus.lee@summitfleetgroup.com'],
                ],
                'payments' => [
                    ['amount' => 310.00, 'status' => 'completed', 'created_at' => '2026-03-03 10:30:00', 'processed_at' => '2026-03-03 10:35:00'],
                    ['amount' => 310.00, 'status' => 'completed', 'created_at' => '2026-04-01 10:30:00', 'processed_at' => '2026-04-01 10:35:00'],
                ],
            ],
        ];

        foreach ($companies as $data) {
            $owner = User::updateOrCreate(
                ['email' => $data['owner']['email']],
                [
                    'name' => $data['owner']['name'],
                    'password' => Hash::make('password'),
                    'role' => 'owner',
                ]
            );

            $company = Company::updateOrCreate(
                ['name' => $data['company']['name']],
                array_merge($data['company'], [
                    'created_by' => $owner->id,
                    'owner_id' => $owner->id,
                ])
            );

            $owner->update(['company_id' => $company->id]);

            foreach ($data['trucks'] as $truckData) {
                Truck::updateOrCreate(
                    ['number' => $truckData['number']],
                    array_merge($truckData, ['company_id' => $company->id])
                );
            }

            foreach ($data['drivers'] as $driverData) {
                $truckId = $driverData['truck_number']
                    ? Truck::where('number', $driverData['truck_number'])->value('id')
                    : null;

                Driver::updateOrCreate(
                    ['email' => $driverData['email']],
                    [
                        'company_id' => $company->id,
                        'name' => $driverData['name'],
                        'phone' => $driverData['phone'],
                        'truck_id' => $truckId,
                        'salary_per_mile' => 0.65,
                        'salary_percent' => 28.00,
                    ]
                );
            }

            foreach ($data['loads'] as $loadData) {
                $truckId = Truck::where('number', $loadData['truck_number'])->value('id');
                $driverId = Driver::where('email', $loadData['driver_email'])->value('id');

                Load::updateOrCreate(
                    ['load_number' => $loadData['load_number']],
                    [
                        'company_id' => $company->id,
                        'truck_id' => $truckId,
                        'driver_id' => $driverId,
                        'broker_company' => $loadData['broker_company'],
                        'pickup_location' => $loadData['pickup_location'],
                        'delivery_location' => $loadData['delivery_location'],
                        'pickup_date' => $loadData['pickup_date'],
                        'delivery_date' => $loadData['delivery_date'],
                        'weight' => $loadData['weight'],
                        'gross_rate' => $loadData['gross_rate'],
                        'miles' => $loadData['miles'],
                        'fuel_cost' => $loadData['fuel_cost'],
                        'driver_salary' => $loadData['driver_salary'],
                        'net_profit' => $loadData['net_profit'],
                        'rate_confirmation_path' => 'storage/'.$loadData['load_number'].'_RC.pdf',
                        'status' => $loadData['status'],
                        'extracted_at' => now(),
                    ]
                );
            }

            $driverCount = Driver::where('company_id', $company->id)->count();
            $package = $data['package'] ?? $basic;

            $subscription = Subscription::updateOrCreate(
                ['user_id' => $owner->id, 'package_id' => $package->id],
                [
                    'status' => 'active',
                    'started_at' => now()->subMonth(),
                    'ends_at' => now()->addMonth(),
                    'payment_status' => 'completed',
                    'amount_paid' => collect($data['payments'])->where('status', 'completed')->sum('amount'),
                    'billing_cycle' => $data['billing_cycle'],
                    'next_billing_date' => $data['billing_cycle'] === 'weekly' ? now()->addWeek() : now()->addMonth(),
                    'last_driver_count' => $driverCount,
                    'stripe_customer_id' => 'cus_demo_'.$company->id,
                    'stripe_subscription_id' => 'sub_demo_'.$company->id,
                ]
            );

            foreach ($data['payments'] as $index => $paymentData) {
                Payment::updateOrCreate(
                    ['transaction_id' => 'txn_demo_'.$company->id.'_'.$index],
                    [
                        'subscription_id' => $subscription->id,
                        'payment_method_id' => $stripe?->id,
                        'amount' => $paymentData['amount'],
                        'invoice_amount' => $paymentData['amount'],
                        'driver_count' => $driverCount,
                        'status' => $paymentData['status'],
                        'failure_reason' => $paymentData['status'] === 'failed' ? 'Demo card declined' : null,
                        'processed_at' => $paymentData['processed_at'],
                        'billing_period_start' => now()->subMonth()->startOfMonth(),
                        'billing_period_end' => now()->subMonth()->endOfMonth(),
                        'metadata' => [
                            'company' => $company->name,
                            'seeded' => true,
                        ],
                        'created_at' => $paymentData['created_at'],
                        'updated_at' => $paymentData['processed_at'] ?? $paymentData['created_at'],
                    ]
                );
            }
        }
    }
}
