<?php

namespace Database\Seeders;

use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
use Carbon\Carbon;

class OrderSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $products = Product::all();
        if ($products->isEmpty()) {
            return;
        }

        $customers = User::where('role', 'customer')->get();
        if ($customers->isEmpty()) {
            // Seed multiple diverse dummy customers
            $dummyCustomers = [
                [
                    'name' => 'Alice Johnson',
                    'email' => 'alice@example.com',
                    'phone' => '+85512345678',
                    'gender' => 'female',
                    'dob' => '1995-04-12',
                    'customer_group' => 'VIP',
                    'status' => 'active',
                ],
                [
                    'name' => 'Bob Smith',
                    'email' => 'bob@example.com',
                    'phone' => '+85587654321',
                    'gender' => 'male',
                    'dob' => '1990-08-25',
                    'customer_group' => 'General',
                    'status' => 'active',
                ],
                [
                    'name' => 'Charlie Brown',
                    'email' => 'charlie@example.com',
                    'phone' => '+85599887766',
                    'gender' => 'male',
                    'dob' => '1988-11-30',
                    'customer_group' => 'Wholesale',
                    'status' => 'suspended',
                ],
                [
                    'name' => 'Diana Prince',
                    'email' => 'diana@example.com',
                    'phone' => '+85555443322',
                    'gender' => 'female',
                    'dob' => '1993-02-14',
                    'customer_group' => 'VIP',
                    'status' => 'active',
                ]
            ];

            $customers = collect();
            foreach ($dummyCustomers as $cData) {
                $c = User::create([
                    'name' => $cData['name'],
                    'email' => $cData['email'],
                    'phone' => $cData['phone'],
                    'password' => bcrypt('password'),
                    'role' => 'customer',
                    'gender' => $cData['gender'],
                    'dob' => $cData['dob'],
                    'customer_group' => $cData['customer_group'],
                    'status' => $cData['status'],
                    'email_verified_at' => now(),
                    'phone_verified_at' => now(),
                    'last_login_at' => now()->subHours(rand(1, 48)),
                ]);

                // Seed saved addresses for each
                $c->addresses()->createMany([
                    [
                        'label' => 'Home',
                        'recipient_name' => $c->name,
                        'phone' => $c->phone,
                        'country' => 'Cambodia',
                        'province' => 'Phnom Penh',
                        'city' => 'Phnom Penh',
                        'district' => 'Chamkar Mon',
                        'commune' => 'Boeung Keng Kang I',
                        'village' => 'Village 1',
                        'street_address' => 'St. 360, No. ' . rand(1, 100),
                        'latitude' => 11.5564,
                        'longitude' => 104.9282,
                        'is_default_shipping' => true,
                        'is_default_billing' => true,
                    ],
                    [
                        'label' => 'Office',
                        'recipient_name' => $c->name,
                        'phone' => $c->phone,
                        'country' => 'Cambodia',
                        'province' => 'Phnom Penh',
                        'city' => 'Phnom Penh',
                        'district' => 'Daun Penh',
                        'commune' => 'Phsar Thmey III',
                        'village' => 'Village 3',
                        'street_address' => 'St. 130, Office Tower A',
                        'latitude' => 11.5712,
                        'longitude' => 104.9215,
                        'is_default_shipping' => false,
                        'is_default_billing' => false,
                    ]
                ]);

                $customers->push($c);
            }
        }

        $paymentMethods = ['aba', 'cod'];
        $statuses = [
            // [payment_status, order_status, status (legacy)]
            ['paid', 'completed', 'paid'],
            ['paid', 'processing', 'paid'],
            ['paid', 'delivering', 'paid'],
            ['pending', 'pending', 'pending'],
            ['failed', 'cancelled', 'cancelled'],
            ['cancelled', 'cancelled', 'cancelled'],
        ];

        $names = ['Sokha', 'Borith', 'Chan', 'Devi', 'Phally', 'Sothy', 'Veasna', 'Piseth', 'Leakhena', 'Narith'];
        $surnames = ['Lim', 'Seng', 'Chhay', 'Chea', 'Keo', 'Meas', 'Sam', 'Ros', 'Vong', 'Khim'];

        // Seed 40 orders over the past 30 days
        for ($i = 0; $i < 40; $i++) {
            $customer = $customers->random();
            $date = Carbon::now()->subDays(rand(0, 30))->subHours(rand(0, 23))->subMinutes(rand(0, 59));
            
            $method = $paymentMethods[rand(0, 1)];
            
            // Adjust status logic
            if ($method === 'cod') {
                // COD is usually pending payment until delivery
                $statusOption = rand(0, 1) === 0 
                    ? ['pending', 'pending', 'pending'] 
                    : ['paid', 'completed', 'paid'];
            } else {
                $statusOption = $statuses[array_rand($statuses)];
            }
            
            [$paymentStatus, $orderStatus, $legacyStatus] = $statusOption;
            
            // Selected products for this order
            $orderProducts = $products->random(rand(1, 3));
            $subtotal = 0;
            $itemsData = [];

            foreach ($orderProducts as $product) {
                $qty = rand(1, 2);
                $lineSubtotal = $product->price * $qty;
                $subtotal += $lineSubtotal;

                $itemsData[] = [
                    'product_id' => $product->id,
                    'quantity' => $qty,
                    'price' => $product->price,
                    'line_subtotal' => $lineSubtotal,
                ];
            }

            $discount = rand(0, 1) === 1 ? rand(5, 15) : 0;
            $shippingFee = 2.00;
            $total = max(0, $subtotal - $discount + $shippingFee);
            
            $firstName = $names[array_rand($names)];
            $lastName = $surnames[array_rand($surnames)];
            $customerName = "{$lastName} {$firstName}";

            $order = Order::create([
                'user_id' => $customer->id,
                'order_number' => 'ORD-' . strtoupper(Str::random(10)),
                'status' => $legacyStatus,
                'payment_status' => $paymentStatus,
                'order_status' => $orderStatus,
                'subtotal' => $subtotal,
                'discount' => $discount,
                'shipping_fee' => $shippingFee,
                'total' => $total,
                'currency' => 'USD',
                'payment_method' => $method,
                'shipping_detail' => 'https://maps.google.com/?q=' . rand(11, 12) . '.' . rand(1000, 9000) . ',' . rand(104, 105) . '.' . rand(1000, 9000),
                'customer_name' => $customerName,
                'customer_phone' => '+855' . rand(10, 99) . rand(100, 999) . rand(100, 999),
                'customer_email' => strtolower($firstName . '.' . $lastName . '@example.com'),
                'note' => rand(0, 3) === 0 ? 'Delivery in afternoon please' : null,
                'transaction_id' => $method === 'aba' && $paymentStatus === 'paid' ? 'APW-' . rand(10000000, 99999999) : null,
                'approval_code' => $method === 'aba' && $paymentStatus === 'paid' ? (string) rand(100000, 999999) : null,
                'paid_at' => $paymentStatus === 'paid' ? $date : null,
                'cancelled_at' => $paymentStatus === 'cancelled' || $paymentStatus === 'failed' ? $date : null,
                'completed_at' => $orderStatus === 'completed' ? $date : null,
                'created_at' => $date,
                'updated_at' => $date,
            ]);

            foreach ($itemsData as $item) {
                $order->items()->create($item);
            }
        }
    }
}
