<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\User;
use App\Models\Order;
use App\Models\OrderStatusHistory;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\AuctionVehicle;
use App\Models\Bid;
use Carbon\Carbon;
use Illuminate\Support\Str;

class OrderSeeder extends Seeder
{
    public function run(): void
    {
        $admin = User::where('role', 'super_admin')->first();
        $wonBids = Bid::where('status', 'won')->with('user', 'auctionVehicle')->get();

        $orderTemplates = [
            [
                'status' => 'auction_won',
                'order_type' => 'auction_preorder',
                'total_bdt' => 5450000.00,
                'paid_bdt' => 0.00,
                'vessel' => null,
                'bl' => null,
                'eta' => null,
                'step_history' => [
                    ['status' => 'auction_won', 'title' => 'Won at USS Tokyo Auction', 'desc' => 'Vehicle successfully secured at ¥2,650,000 hammer price.', 'loc' => 'Noda, Chiba, Japan'],
                ],
            ],
            [
                'status' => 'preparing_shipment',
                'order_type' => 'auction_preorder',
                'total_bdt' => 6750000.00,
                'paid_bdt' => 2000000.00,
                'vessel' => 'TRANS HARMONY 1 V.045',
                'bl' => 'ECL-TYO-CTG-98412',
                'eta' => Carbon::now()->addDays(22)->toDateString(),
                'step_history' => [
                    ['status' => 'auction_won', 'title' => 'Won at Japan Auction', 'desc' => 'Lot won at HAA Kobe auction floor.', 'loc' => 'Kobe, Japan'],
                    ['status' => 'payment_received', 'title' => 'Booking Deposit Verified', 'desc' => 'Initial 20% booking deposit confirmed by accounts.', 'loc' => 'Gulshan, Dhaka'],
                    ['status' => 'japan_processing', 'title' => 'Export Certificate Issued', 'desc' => 'Japanese de-registration completed and certified for export.', 'loc' => 'Yokohama Yard'],
                    ['status' => 'preparing_shipment', 'title' => 'Positioned for Vessel Loading', 'desc' => 'Vehicle berthed at Yokohama Honmoku terminal.', 'loc' => 'Yokohama Port'],
                ],
            ],
            [
                'status' => 'shipped',
                'order_type' => 'auction_preorder',
                'total_bdt' => 5200000.00,
                'paid_bdt' => 3500000.00,
                'vessel' => 'MALAYSIA STAR V.112',
                'bl' => 'ECL-YKH-CTG-87291',
                'eta' => Carbon::now()->addDays(12)->toDateString(),
                'step_history' => [
                    ['status' => 'auction_won', 'title' => 'Secured at Auction', 'desc' => 'Vehicle won at USS Tokyo.', 'loc' => 'Tokyo, Japan'],
                    ['status' => 'payment_received', 'title' => 'Deposit & Export Payment Cleared', 'desc' => 'LC documentation finalized with Prime Bank.', 'loc' => 'Dhaka'],
                    ['status' => 'japan_processing', 'title' => 'Pre-Shipment Inspection (JAAI)', 'desc' => 'JAAI roadworthiness inspection passed.', 'loc' => 'Yokohama'],
                    ['status' => 'shipped', 'title' => 'Vessel Departed Japan', 'desc' => 'Sailing en route to Chittagong Port via Singapore.', 'loc' => 'Pacific Ocean'],
                ],
            ],
            [
                'status' => 'arrived_chittagong',
                'order_type' => 'auction_preorder',
                'total_bdt' => 6850000.00,
                'paid_bdt' => 4500000.00,
                'vessel' => 'ASIATIC SUN V.098',
                'bl' => 'TOYO-KOB-CTG-71920',
                'eta' => Carbon::now()->subDays(2)->toDateString(),
                'step_history' => [
                    ['status' => 'auction_won', 'title' => 'Secured at Auction', 'desc' => 'Secured at CAA Chubu.', 'loc' => 'Nagoya'],
                    ['status' => 'shipped', 'title' => 'Car Carrier Voyage Completed', 'desc' => 'Direct liner vessel arrived at Chittagong outer anchorage.', 'loc' => 'Bay of Bengal'],
                    ['status' => 'arrived_chittagong', 'title' => 'Unloaded at Port Yard', 'desc' => 'Vehicle discharged safely at Chittagong Port Yard 4.', 'loc' => 'Chittagong Port, Bangladesh'],
                ],
            ],
            [
                'status' => 'customs_cleared',
                'order_type' => 'auction_preorder',
                'total_bdt' => 4500000.00,
                'paid_bdt' => 4000000.00,
                'vessel' => 'TRANS HARMONY 2 V.021',
                'bl' => 'ECL-YKH-CTG-65109',
                'eta' => Carbon::now()->subDays(10)->toDateString(),
                'step_history' => [
                    ['status' => 'auction_won', 'title' => 'Auction Won', 'desc' => 'Lot secured at TAA Yokohama.', 'loc' => 'Yokohama'],
                    ['status' => 'arrived_chittagong', 'title' => 'Arrived Chittagong Port', 'desc' => 'Container released and stripped.', 'loc' => 'Chittagong Port'],
                    ['status' => 'customs_processing', 'title' => 'Customs Assessment Completed', 'desc' => 'NBR Chittagong custom house bill of entry filed.', 'loc' => 'Custom House Chittagong'],
                    ['status' => 'customs_cleared', 'title' => 'Port Release Gate Pass Issued', 'desc' => 'Customs duty paid in full. Released from port yard.', 'loc' => 'Chittagong Gate'],
                ],
            ],
            [
                'status' => 'delivered',
                'order_type' => 'ready_stock',
                'total_bdt' => 14600000.00,
                'paid_bdt' => 14600000.00,
                'vessel' => 'GOLDEN STAR V.034',
                'bl' => 'ECL-TYO-CTG-54129',
                'eta' => Carbon::now()->subDays(45)->toDateString(),
                'step_history' => [
                    ['status' => 'auction_won', 'title' => 'Import Purchase Completed', 'desc' => 'Direct Japan auction acquisition.', 'loc' => 'Tokyo'],
                    ['status' => 'customs_cleared', 'title' => 'Customs Release', 'desc' => 'Complete duty clearance.', 'loc' => 'Chittagong'],
                    ['status' => 'registration', 'title' => 'BRTA Registration Complete', 'desc' => 'Dhaka Metro Gha-24-9182 registration plate assigned.', 'loc' => 'BRTA Mirpur'],
                    ['status' => 'ready_for_delivery', 'title' => 'Detailing & Showroom Arrival', 'desc' => '3M ceramic coating and PDI completed.', 'loc' => 'Niketan Gulshan Showroom'],
                    ['status' => 'delivered', 'title' => 'Handed Over to Owner', 'desc' => 'Vehicle delivered to client with keys and BRTA documents.', 'loc' => 'Gulshan, Dhaka'],
                ],
            ],
        ];

        $customers = User::where('role', 'customer')->get();

        foreach ($orderTemplates as $index => $tmpl) {
            $customer = $customers[$index % $customers->count()];
            $bid = $wonBids->get($index % max(1, $wonBids->count()));
            $vehicle = $bid?->auctionVehicle;

            $orderNumber = 'MS-ORD-' . date('Y') . '-' . str_pad($index + 10, 4, '0', STR_PAD_LEFT);
            $dueBdt = max(0, $tmpl['total_bdt'] - $tmpl['paid_bdt']);

            $order = Order::updateOrCreate(
                ['order_number' => $orderNumber],
                [
                    'user_id' => $customer->id,
                    'auction_vehicle_id' => $vehicle?->id,
                    'bid_id' => $bid?->id,
                    'order_type' => $tmpl['order_type'],
                    'total_amount_bdt' => $tmpl['total_bdt'],
                    'paid_amount_bdt' => $tmpl['paid_bdt'],
                    'due_amount_bdt' => $dueBdt,
                    'hammer_price_jpy' => $bid?->won_hammer_price_jpy ?? 2500000,
                    'status' => $tmpl['status'],
                    'vessel_name' => $tmpl['vessel'],
                    'bl_number' => $tmpl['bl'],
                    'port_of_loading' => 'Yokohama, Japan',
                    'port_of_discharge' => 'Chittagong Port, Bangladesh',
                    'eta_chittagong' => $tmpl['eta'],
                    'assigned_reg_number' => $tmpl['status'] === 'delivered' ? 'Dhaka Metro-Gha-24-9182' : null,
                    'delivery_address' => $customer->customer?->address ?? 'Niketan, Gulshan-1, Dhaka',
                    'internal_notes' => 'Priority import client managed by MotoSolution executive team.',
                ]
            );

            // Step history
            foreach ($tmpl['step_history'] as $step) {
                OrderStatusHistory::firstOrCreate(
                    [
                        'order_id' => $order->id,
                        'status' => $step['status'],
                    ],
                    [
                        'title' => $step['title'],
                        'description' => $step['desc'],
                        'location' => $step['loc'],
                        'updated_by' => $admin?->id,
                        'occurred_at' => now()->subDays(rand(1, 30)),
                    ]
                );
            }

            // Invoices & Payments
            $invoice = Invoice::updateOrCreate(
                ['invoice_number' => 'MS-INV-' . date('Y') . '-' . str_pad($index + 1, 4, '0', STR_PAD_LEFT)],
                [
                    'order_id' => $order->id,
                    'user_id' => $customer->id,
                    'title' => 'Import Milestone Invoice #' . ($index + 1),
                    'amount_bdt' => $tmpl['total_bdt'],
                    'paid_bdt' => $tmpl['paid_bdt'],
                    'due_bdt' => $dueBdt,
                    'due_date' => Carbon::now()->addDays(7),
                    'status' => $dueBdt <= 0 ? 'paid' : ($tmpl['paid_bdt'] > 0 ? 'partially_paid' : 'unpaid'),
                    'notes' => 'Import landed cost invoice issued per purchase contract.',
                ]
            );

            if ($tmpl['paid_bdt'] > 0) {
                Payment::updateOrCreate(
                    ['payment_reference' => 'MS-PAY-' . date('Y') . '-' . str_pad($index + 1, 4, '0', STR_PAD_LEFT)],
                    [
                        'invoice_id' => $invoice->id,
                        'order_id' => $order->id,
                        'user_id' => $customer->id,
                        'amount_bdt' => $tmpl['paid_bdt'],
                        'payment_method' => 'bank_transfer',
                        'transaction_id' => 'TXN-PRIME-' . rand(1000000, 9999999),
                        'bank_name' => 'Prime Bank Limited',
                        'bank_branch' => 'Gulshan Branch, Dhaka',
                        'sender_phone_or_account' => 'AC-102938471',
                        'status' => 'verified',
                        'verified_by' => $admin?->id,
                        'verified_at' => now()->subDays(rand(2, 20)),
                        'admin_notes' => 'Remittance cleared into MotoSolution LC account.',
                    ]
                );
            }
        }
    }
}
