<?php

namespace Database\Seeders;

use App\Models\Customer;
use App\Models\Estimate;
use App\Models\EstimateItem;
use Carbon\Carbon;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class EstimateSeeder extends Seeder
{
    use WithoutModelEvents;

    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $customerIds = Customer::pluck('id')->toArray();

        if (empty($customerIds)) {
            $this->command->info('No customers found. Please run CustomerSeeder first.');

            return;
        }

        $statuses = ['draft', 'sent', 'viewed', 'accepted', 'rejected', 'expired'];
        $products = [
            ['description' => 'Website Redesign Project', 'unit_price' => 8500.00],
            ['description' => 'E-commerce Platform Development', 'unit_price' => 15000.00],
            ['description' => 'Mobile App (iOS & Android)', 'unit_price' => 25000.00],
            ['description' => 'Brand Identity Package', 'unit_price' => 3500.00],
            ['description' => 'Social Media Marketing (3 months)', 'unit_price' => 4500.00],
            ['description' => 'CRM Implementation', 'unit_price' => 12000.00],
            ['description' => 'Data Migration Services', 'unit_price' => 5500.00],
            ['description' => 'Security Assessment', 'unit_price' => 3000.00],
            ['description' => 'Cloud Infrastructure Setup', 'unit_price' => 7500.00],
            ['description' => 'Custom Integration Development', 'unit_price' => 6000.00],
            ['description' => 'Performance Optimization', 'unit_price' => 2500.00],
            ['description' => 'Training Program (5 days)', 'unit_price' => 2000.00],
            ['description' => 'Annual Support Contract', 'unit_price' => 8000.00],
            ['description' => 'Video Production Package', 'unit_price' => 4000.00],
            ['description' => 'AI/ML Solution Development', 'unit_price' => 35000.00],
        ];

        for ($i = 1; $i <= 25; $i++) {
            $issueDate = Carbon::now()->subDays(rand(1, 60));
            $expiryDate = (clone $issueDate)->addDays(rand(14, 30));
            $status = $statuses[array_rand($statuses)];

            // Calculate amounts
            $numItems = rand(1, 5);
            $items = [];
            $subtotal = 0;

            for ($j = 0; $j < $numItems; $j++) {
                $product = $products[array_rand($products)];
                $quantity = rand(1, 3);
                $taxRate = [0, 5, 10, 18, 20][array_rand([0, 5, 10, 18, 20])];
                $itemTotal = $product['unit_price'] * $quantity;
                $taxAmount = $itemTotal * ($taxRate / 100);

                $items[] = [
                    'description' => $product['description'],
                    'quantity' => $quantity,
                    'unit_price' => $product['unit_price'],
                    'tax_rate' => $taxRate,
                    'tax_amount' => $taxAmount,
                    'total' => $itemTotal + $taxAmount,
                    'sort_order' => $j,
                ];

                $subtotal += $itemTotal;
            }

            $totalTax = array_sum(array_column($items, 'tax_amount'));
            $discountType = rand(0, 1) ? 'percentage' : 'fixed';
            $discountAmount = $discountType === 'percentage'
                ? $subtotal * (rand(0, 10) / 100)
                : rand(0, 1000);
            $total = $subtotal + $totalTax - $discountAmount;

            $estimateNumber = 'QUO-'.str_pad($i, 6, '0', STR_PAD_LEFT);

            $estimate = Estimate::updateOrCreate(
                ['estimate_number' => $estimateNumber],
                [
                    'customer_id' => $customerIds[array_rand($customerIds)],
                    'issue_date' => $issueDate,
                    'expiry_date' => $expiryDate,
                    'status' => $status,
                    'subtotal' => $subtotal,
                    'tax_amount' => $totalTax,
                    'discount_amount' => $discountAmount,
                    'discount_type' => $discountType,
                    'total' => $total,
                    'currency' => 'USD',
                    'notes' => 'This quotation is valid for 30 days from the issue date.',
                    'terms' => 'Payment terms: 50% upfront, 50% upon completion. Prices are subject to change after validity period.',
                    'sent_at' => in_array($status, ['sent', 'viewed', 'accepted', 'rejected', 'expired']) ? $issueDate->addHours(rand(1, 24)) : null,
                    'viewed_at' => in_array($status, ['viewed', 'accepted', 'rejected']) ? $issueDate->addDays(rand(1, 5)) : null,
                    'accepted_at' => $status === 'accepted' ? $issueDate->addDays(rand(3, 10)) : null,
                ]
            );

            // Delete existing items and create new ones
            EstimateItem::where('estimate_id', $estimate->id)->delete();

            // Create estimate items using bulk insert
            $itemsToInsert = array_map(function ($item) use ($estimate) {
                return array_merge($item, [
                    'estimate_id' => $estimate->id,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }, $items);

            EstimateItem::insert($itemsToInsert);
        }
    }
}
