<?php

namespace Modules\SystemCore\Database\Seeders;

use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Modules\SystemCore\App\Enums\OrderStatus;
use Modules\SystemCore\App\Models\CorePurchaseOrder;
use Modules\SystemCore\App\Models\CoreSupplier;

class PurchaseOrderSeeder extends Seeder
{
    public function run(): void
    {
        // Disable foreign key checks
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');

        // Truncate tables (including line items)
        DB::table('core_purchase_order_lines')->truncate();
        DB::table('core_purchase_orders')->truncate();

        // Re-enable foreign key checks
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');

        $suppliers = CoreSupplier::all();
        $users = User::limit(5)->get();

        if ($suppliers->isEmpty()) {
            $this->command->warn('No suppliers found. Please run SupplierSeeder first.');

            return;
        }

        if ($users->isEmpty()) {
            $this->command->warn('No users found. Cannot create purchase orders without users.');

            return;
        }

        $statuses = [
            OrderStatus::Draft,
            OrderStatus::Pending,
            OrderStatus::Confirmed,
            OrderStatus::Processing,
            OrderStatus::Shipped,
            OrderStatus::Delivered,
            OrderStatus::Completed,
        ];

        $paymentStatuses = ['pending', 'partial', 'paid'];
        $paymentMethods = ['bank_transfer', 'check', 'credit_card', 'wire_transfer'];

        $orders = [];

        for ($i = 1; $i <= 10; $i++) {
            $supplier = $suppliers->random();
            $user = $users->random();
            $status = $statuses[array_rand($statuses)];
            $paymentStatus = $paymentStatuses[array_rand($paymentStatuses)];

            // Random date within past 3 months
            $orderDate = now()->subDays(rand(1, 90));
            $expectedDeliveryDate = (clone $orderDate)->addDays(rand(7, 30));

            // Generate realistic amounts
            $subtotal = rand(1000, 75000) + (rand(0, 99) / 100);
            $taxAmount = $subtotal * 0.15; // 15% tax
            $discountAmount = rand(0, 1) ? 0 : ($subtotal * rand(2, 10) / 100);
            $shippingCost = rand(0, 1) ? 0 : rand(50, 500);
            $totalAmount = $subtotal + $taxAmount - $discountAmount + $shippingCost;

            $orders[] = [
                'supplier_id' => $supplier->id,
                'user_id' => $user->id,
                'order_date' => $orderDate,
                'expected_delivery_date' => $expectedDeliveryDate,
                'status' => $status,
                'subtotal' => $subtotal,
                'tax_amount' => $taxAmount,
                'discount_amount' => $discountAmount,
                'shipping_cost' => $shippingCost,
                'total_amount' => $totalAmount,
                'payment_status' => $paymentStatus,
                'payment_method' => $paymentMethods[array_rand($paymentMethods)],
                'notes' => "Sample purchase order #{$i} for testing purposes",
                'created_at' => $orderDate,
                'updated_at' => $orderDate,
            ];
        }

        foreach ($orders as $orderData) {
            CorePurchaseOrder::create($orderData);
        }

        $this->command->info('Sample purchase orders created successfully.');
    }
}
