<?php

namespace Database\Seeders;

use App\Models\Bill;
use App\Models\FreightCompany;
use App\Models\Load;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Morilog\Jalali\Jalalian;

class RMTOTestDataSeeder extends Seeder
{
    public function run(): void
    {
        // Keep admin users, clear test data
        try {
            User::where('role', '!=', 'admin')->delete();
            FreightCompany::truncate();
            Load::truncate();
            Bill::truncate();
        } catch (\Exception $e) {
            // Handle database connection issues silently
        }

        // Create admin user
        User::updateOrCreate(
            ['email' => 'admin@sabokbaar.ir'],
            [
                'name' => 'Admin',
                'email' => 'admin@sabokbaar.ir',
                'phone' => '09100000000',
                'national_code' => '0000000000',
                'role' => 'admin',
                'password' => Hash::make('admin123'),
                'is_active' => true,
            ]
        );

        // Create test driver (from RMTO)
        $driver = User::updateOrCreate(
            ['email' => 'driver.rmto@test.ir'],
            [
                'name' => 'رضا',
                'email' => 'driver.rmto@test.ir',
                'phone' => '09121234567',
                'national_code' => '0012345678',
                'smart_card_number' => '1234567',
                'role' => 'driver',
                'password' => Hash::make('123456'),
                'is_active' => true,
                'vehicle_type' => 'truck',
                'vehicle_plate' => '12 ب 345 ایران 67',
                'vehicle_capacity' => 25000,
                'driver_status' => 'online',
                'rating' => 4.80,
                'last_activity' => Carbon::now(),
            ]
        );

        // Create freight company (from RMTO test data)
        $freightCompany = FreightCompany::create([
            'company_name' => 'فولاد بوتیای ایرانیان',
            'postal_code' => '8697451230',
            'phone' => '05133000000',
            'address' => 'فارس لارستان لار کوچه علی‌ها بن بست خوم',
            'city' => 'لار',
            'province' => 'فارس',
            'entity_type' => 'legal',
            'status' => 'approved',
            'company_description' => 'شرکت صنعتی تولید فولاد',
        ]);

        // Create sender company (from RMTO test data)
        $senderCompany = FreightCompany::create([
            'company_name' => 'احیا استیل فولاد',
            'postal_code' => '7638175152',
            'phone' => '03436000000',
            'address' => 'کرمان بافت دشتاب شرکت حمل و نقل پرچم بار',
            'city' => 'بافت',
            'province' => 'کرمان',
            'entity_type' => 'legal',
            'status' => 'approved',
            'company_description' => 'شرکت حمل و نقل و صادرات',
        ]);

        // Create test requester
        $requester = User::updateOrCreate(
            ['email' => 'requester.rmto@test.ir'],
            [
                'name' => $freightCompany->company_name,
                'email' => 'requester.rmto@test.ir',
                'phone' => $freightCompany->phone,
                'national_code' => '10320685829',
                'role' => 'requester',
                'password' => Hash::make('123456'),
                'is_active' => true,
            ]
        );

        // Create load (bill of lading)
        $load = Load::create([
            'requester_id' => $requester->id,
            'driver_id' => $driver->id,
            'title' => 'بار آزمایشی RMTO',
            'origin_address' => 'تهران',
            'origin_city' => 'تهران',
            'origin_lat' => 35.6892,
            'origin_lng' => 51.3890,
            'destination_address' => 'فارس لارستان',
            'destination_city' => 'لار',
            'destination_lat' => 27.6694,
            'destination_lng' => 53.9387,
            'weight' => 22000,
            'cargo_type' => 'پمپ دستی تجهیزات کارگاهی',
            'cargo_value' => 100000000,
            'distance_km' => 456.78,
            'price' => 19570000,
            'status' => 'pending',
        ]);

        // Create bill of lading
        $now = Carbon::now();
        $trackingCode = 'TRK-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -8));
        $rmtoTraceCode = sprintf('%021d', uniqid());

        // Required fields from initial migration
        $senderInfo = json_encode([
            'name' => $senderCompany->company_name,
            'national_code' => '10320489932',
            'phone' => $senderCompany->phone,
            'address' => $senderCompany->address,
        ]);

        $receiverInfo = json_encode([
            'name' => $freightCompany->company_name,
            'national_code' => '10320685829',
            'phone' => $freightCompany->phone,
            'address' => $freightCompany->address,
        ]);

        $bill = Bill::create([
            'load_id' => $load->id,
            'bill_number' => '1010',
            'transport_license_plate' => $driver->vehicle_plate,
            'driver_license_number' => 'DL-0012345678',
            'issue_date' => $now,
            'sender_info' => $senderInfo,
            'receiver_info' => $receiverInfo,
            'cargo_details' => 'پمپ دستی تجهیزات کارگاهی',
            'declared_value' => 100000000,
            'notes' => 'Test data from RMTO seeder',
            'status' => 'issued',
            'signature_image' => null,
            'delivery_confirmation_at' => null,
            // Additional fields
            'internal_serial' => 'الف/۱۰۴',
            'tracking_code' => $trackingCode,
            'qr_code_content' => sprintf('1010|الف/۱۰۴|%s', $rmtoTraceCode),
            'dispatch_order_number' => 'DISP-20260425-001',
            'issue_time' => $now->format('H:i:s'),
            'transport_start_date' => $now->addMinutes(10),
            'delivery_date' => $now->addHours(10),
            'transport_type' => 'domestic',
            'cargo_kind' => 'general',
            'service_type' => 'full_truck',
            'freight_company_id' => $freightCompany->id,
            'company_name' => $freightCompany->company_name,
            'company_national_id' => '10320685829',
            'company_economic_code' => '10320685829',
            'company_phone' => $freightCompany->phone,
            'company_ceo_name' => null,
            'first_driver_name' => $driver->name,
            'first_driver_national_code' => $driver->national_code,
            'first_driver_mobile' => $driver->phone,
            'first_driver_account_number' => null,
            'vehicle_type' => $driver->vehicle_type ?? 'truck',
            'vehicle_smart_card_no' => $driver->smart_card_number,
            'vehicle_allowed_capacity' => $driver->vehicle_capacity ?? 25000,
            'vehicle_gross_weight_limit' => 30000,
            'vehicle_owner_national_code' => $driver->national_code,
            'origin_postal_code' => null,
            'destination_postal_code' => null,
            'distance_km' => 456.78,
            'sender_name' => $senderCompany->company_name,
            'sender_national_id' => '10320489932',
            'sender_phone' => $senderCompany->phone,
            'sender_address' => $senderCompany->address,
            'sender_postal_code' => $senderCompany->postal_code,
            'receiver_name_full' => $freightCompany->company_name,
            'receiver_national_id' => '10320685829',
            'receiver_mobile' => $freightCompany->phone,
            'receiver_address_full' => $freightCompany->address,
            'receiver_postal_code' => $freightCompany->postal_code,
            'freight_amount' => 16000000,
            'insurance_amount' => 1500000,
            'tax_amount' => 1600000,
            'toll_amount' => 150000,
            'total_amount' => 19250000,
            'payment_terms' => 'prepaid',
            // RMTO fields
            'rmto_trace_code' => $rmtoTraceCode,
            'rmto_bill_number' => 1010,
            'rmto_serial' => 'الف/۱۰۴',
            'rmto_registered_at' => $now,
            'rmto_status' => 'registered',
        ]);

        // Add cargo items to bill
        $bill->cargoItems()->create([
            'cargo_name' => 'پمپ دستی تجهیزات کارگاهی',
            'cargo_code' => '4700000',
            'packaging_type' => 'جعبه',
            'quantity' => 1,
            'weight' => 22000,
            'value' => 100000000,
        ]);

        echo "✓ RMTO test data seeded successfully\n";
        echo "  Admin: admin@sabokbaar.ir / admin123\n";
        echo "  Driver: {$driver->name} ({$driver->national_code})\n";
        echo "  Freight Company: {$freightCompany->company_name}\n";
        echo "  Bill: #{$bill->bill_number} - {$bill->internal_serial}\n";
    }

    private function getPersianDate(Carbon $date): array
    {
        $jd = Jalalian::fromCarbon($date);
        return [
            'year' => $jd->getYear(),
            'month' => $jd->getMonth(),
            'day' => $jd->getDay(),
        ];
    }
}
