<?php

namespace Database\Seeders;

use App\Models\ChartOfAccount;
use App\Models\Customer;
use App\Models\Expense;
use Carbon\Carbon;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class ExpenseSeeder extends Seeder
{
    use WithoutModelEvents;

    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Get expense accounts (type = 'expense')
        $expenseAccountIds = ChartOfAccount::where('type', 'expense')->pluck('id')->toArray();

        if (empty($expenseAccountIds)) {
            $this->command->info('No expense accounts found. Please run ChartOfAccountSeeder first.');

            return;
        }

        // Get some customers to use as vendors
        $vendorIds = Customer::pluck('id')->toArray();

        $categories = [
            'Office Supplies', 'Travel', 'Utilities', 'Software', 'Marketing',
            'Professional Services', 'Equipment', 'Insurance', 'Rent', 'Maintenance',
            'Telecommunications', 'Training', 'Meals & Entertainment', 'Subscriptions', 'Miscellaneous',
        ];

        $paymentMethods = ['cash', 'bank_transfer', 'credit_card', 'debit_card', 'check'];
        $statuses = ['draft', 'approved', 'paid', 'rejected'];

        $expenseDescriptions = [
            'Office Supplies' => ['Paper and stationery', 'Printer ink cartridges', 'Desk accessories', 'Filing supplies'],
            'Travel' => ['Flight tickets - client meeting', 'Hotel accommodation', 'Car rental', 'Taxi/Uber expenses'],
            'Utilities' => ['Electricity bill', 'Water bill', 'Gas bill', 'Internet service'],
            'Software' => ['Adobe Creative Cloud subscription', 'Microsoft 365 license', 'Slack subscription', 'GitHub Enterprise'],
            'Marketing' => ['Google Ads campaign', 'Social media advertising', 'Print marketing materials', 'Trade show booth'],
            'Professional Services' => ['Legal consultation', 'Accounting services', 'Consulting fees', 'Audit services'],
            'Equipment' => ['Laptop purchase', 'Monitor screens', 'Office furniture', 'Server equipment'],
            'Insurance' => ['Business liability insurance', 'Health insurance premium', 'Property insurance', 'Vehicle insurance'],
            'Rent' => ['Office rent - monthly', 'Warehouse rent', 'Parking space rental', 'Storage unit'],
            'Maintenance' => ['AC repair and maintenance', 'Plumbing services', 'Electrical work', 'General maintenance'],
            'Telecommunications' => ['Phone bills', 'Mobile data plans', 'Conference call services', 'VoIP services'],
            'Training' => ['Employee training course', 'Professional certification', 'Workshop fees', 'Online course subscription'],
            'Meals & Entertainment' => ['Client lunch meeting', 'Team dinner', 'Coffee meetings', 'Event catering'],
            'Subscriptions' => ['Industry magazine subscription', 'News service subscription', 'Research database access', 'Cloud storage'],
            'Miscellaneous' => ['Bank fees', 'Courier services', 'Postage', 'Minor repairs'],
        ];

        for ($i = 1; $i <= 25; $i++) {
            $expenseDate = Carbon::now()->subDays(rand(1, 90));
            $category = $categories[array_rand($categories)];
            $descriptions = $expenseDescriptions[$category];
            $description = $descriptions[array_rand($descriptions)];
            $status = $statuses[array_rand($statuses)];

            $amount = match ($category) {
                'Rent' => rand(2000, 8000),
                'Equipment' => rand(500, 5000),
                'Insurance' => rand(300, 2000),
                'Travel' => rand(200, 3000),
                'Software' => rand(50, 500),
                'Professional Services' => rand(500, 5000),
                'Marketing' => rand(200, 3000),
                default => rand(20, 500),
            };

            $taxRate = [0, 5, 10, 18][array_rand([0, 5, 10, 18])];
            $taxAmount = $amount * ($taxRate / 100);
            $total = $amount + $taxAmount;

            $expenseNumber = 'EXP-'.str_pad($i, 6, '0', STR_PAD_LEFT);

            Expense::updateOrCreate(
                ['expense_number' => $expenseNumber],
                [
                    'expense_date' => $expenseDate,
                    'account_id' => $expenseAccountIds[array_rand($expenseAccountIds)],
                    'vendor_id' => ! empty($vendorIds) && rand(0, 1) ? $vendorIds[array_rand($vendorIds)] : null,
                    'category' => $category,
                    'payment_method' => $paymentMethods[array_rand($paymentMethods)],
                    'amount' => $amount,
                    'tax_amount' => $taxAmount,
                    'total' => $total,
                    'currency' => 'USD',
                    'description' => $description,
                    'notes' => rand(0, 1) ? 'Expense for '.strtolower($category).' - '.$expenseDate->format('F Y') : null,
                    'status' => $status,
                    'approved_at' => in_array($status, ['approved', 'paid']) ? $expenseDate->addDays(rand(1, 3)) : null,
                ]
            );
        }
    }
}
