<?php

namespace Database\Seeders;

use App\Models\Client;
use App\Models\Expense;
use App\Models\Invoice;
use App\Models\InvoiceItem;
use App\Models\Payment;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        // ─────────────────────────────────────────
        // DEMO USER
        // ─────────────────────────────────────────
        $user = User::create([
            'name'                    => 'Chukwuemeka Obi',
            'email'                   => 'demo@invotrack.ng',
            'password'                => Hash::make('password'),
            'business_name'           => 'Obi Creative Agency',
            'business_type'           => 'sole_proprietor',
            'phone'                   => '08012345678',
            'address'                 => '14 Admiralty Way, Lekki Phase 1, Lagos',
            'bank_name'               => 'Guaranty Trust Bank',
            'account_number'          => '0123456789',
            'account_name'            => 'OBI CREATIVE AGENCY',
            'invoice_prefix'          => 'INV',
            'invoice_counter'         => 0,
            'payment_terms'           => 14,
            'default_invoice_notes'   => 'Payment is due within 14 days. Thank you for your business!',
            'plan'                    => 'pro',
            'onboarding_complete'     => true,
        ]);

        // ─────────────────────────────────────────
        // CLIENTS
        // ─────────────────────────────────────────
        $clients = [
            [
                'name'          => 'Amara Nwosu',
                'email'         => 'amara@nexgentechng.com',
                'phone'         => '07023456789',
                'business_name' => 'NexGen Tech Nigeria',
                'address'       => '3 Ozumba Mbadiwe Ave, Victoria Island, Lagos',
            ],
            [
                'name'          => 'Tunde Fashola',
                'email'         => 'tunde@bluechipconsult.ng',
                'phone'         => '08034567890',
                'business_name' => 'BlueChip Consulting Ltd',
                'address'       => '22 Adeola Odeku Street, VI, Lagos',
            ],
            [
                'name'          => 'Ngozi Eze',
                'email'         => 'ngozi@deltalogistics.com',
                'phone'         => '09045678901',
                'business_name' => 'Delta Logistics & Haulage',
                'address'       => 'Plot 7, Trans-Amadi Layout, Port Harcourt',
            ],
            [
                'name'          => 'Biodun Alabi',
                'email'         => 'biodun@sunriseproperties.ng',
                'phone'         => '08156789012',
                'business_name' => 'Sunrise Properties',
                'address'       => '5 Ring Road, Ibadan, Oyo State',
            ],
            [
                'name'          => 'Kemi Adeyemi',
                'email'         => 'kemi.adeyemi@gmail.com',
                'phone'         => '07067890123',
                'business_name' => null,
                'address'       => 'Abuja FCT',
            ],
        ];

        $clientModels = [];
        foreach ($clients as $clientData) {
            $clientModels[] = $user->clients()->create($clientData);
        }

        // ─────────────────────────────────────────
        // INVOICES (mix of statuses across 6 months)
        // ─────────────────────────────────────────
        $invoiceData = [
            // Paid invoices (past months)
            [
                'client'     => 0,
                'status'     => 'paid',
                'issue_date' => Carbon::now()->subMonths(5)->startOfMonth()->addDays(2),
                'items'      => [
                    ['description' => 'Brand Identity Design', 'quantity' => 1, 'unit_price' => 180000],
                    ['description' => 'Logo Variations (5)', 'quantity' => 1, 'unit_price' => 45000],
                ],
            ],
            [
                'client'     => 1,
                'status'     => 'paid',
                'issue_date' => Carbon::now()->subMonths(4)->startOfMonth()->addDays(5),
                'items'      => [
                    ['description' => 'Website Redesign — 10 pages', 'quantity' => 1, 'unit_price' => 350000],
                    ['description' => 'CMS Integration', 'quantity' => 1, 'unit_price' => 75000],
                    ['description' => 'Hosting Setup (1 year)', 'quantity' => 1, 'unit_price' => 30000],
                ],
            ],
            [
                'client'     => 2,
                'status'     => 'paid',
                'issue_date' => Carbon::now()->subMonths(3)->startOfMonth()->addDays(8),
                'items'      => [
                    ['description' => 'Social Media Management (3 months)', 'quantity' => 3, 'unit_price' => 80000],
                ],
            ],
            [
                'client'     => 0,
                'status'     => 'paid',
                'issue_date' => Carbon::now()->subMonths(2)->startOfMonth()->addDays(3),
                'items'      => [
                    ['description' => 'Annual Report Design', 'quantity' => 1, 'unit_price' => 120000],
                    ['description' => 'Print-Ready Files', 'quantity' => 1, 'unit_price' => 15000],
                ],
            ],
            // Sent/Viewed invoices
            [
                'client'     => 1,
                'status'     => 'viewed',
                'issue_date' => Carbon::now()->subMonths(1)->startOfMonth()->addDays(10),
                'items'      => [
                    ['description' => 'UI/UX Design — Mobile App', 'quantity' => 1, 'unit_price' => 280000],
                    ['description' => 'Prototype & User Testing', 'quantity' => 1, 'unit_price' => 60000],
                ],
            ],
            [
                'client'     => 3,
                'status'     => 'sent',
                'issue_date' => Carbon::now()->subDays(10),
                'items'      => [
                    ['description' => 'Marketing Collateral Design', 'quantity' => 1, 'unit_price' => 95000],
                    ['description' => 'Brochure (10 pages)', 'quantity' => 1, 'unit_price' => 45000],
                ],
            ],
            // Overdue
            [
                'client'     => 2,
                'status'     => 'overdue',
                'issue_date' => Carbon::now()->subDays(45),
                'items'      => [
                    ['description' => 'Digital Marketing Strategy', 'quantity' => 1, 'unit_price' => 150000],
                ],
            ],
            // Draft
            [
                'client'     => 4,
                'status'     => 'draft',
                'issue_date' => Carbon::now(),
                'items'      => [
                    ['description' => 'Photography Session (half day)', 'quantity' => 1, 'unit_price' => 60000],
                    ['description' => 'Photo Editing (30 images)', 'quantity' => 30, 'unit_price' => 1500],
                ],
            ],
            // This month paid
            [
                'client'     => 1,
                'status'     => 'paid',
                'issue_date' => Carbon::now()->startOfMonth()->addDays(1),
                'items'      => [
                    ['description' => 'Content Writing — 8 Articles', 'quantity' => 8, 'unit_price' => 18000],
                ],
            ],
        ];

        foreach ($invoiceData as $data) {
            $invoiceNumber = $user->generateInvoiceNumber();
            $client        = $clientModels[$data['client']];
            $issueDate     = $data['issue_date'];
            $dueDate       = $issueDate->copy()->addDays($user->payment_terms);

            $invoice = $user->invoices()->create([
                'client_id'      => $client->id,
                'invoice_number' => $invoiceNumber,
                'status'         => $data['status'],
                'issue_date'     => $issueDate,
                'due_date'       => $dueDate,
                'vat_rate'       => 7.50,
                'discount'       => 0,
                'notes'          => $user->default_invoice_notes,
                'sent_at'        => in_array($data['status'], ['sent', 'viewed', 'paid', 'overdue'])
                                        ? $issueDate->copy()->addHours(2) : null,
                'viewed_at'      => in_array($data['status'], ['viewed', 'paid'])
                                        ? $issueDate->copy()->addHours(5) : null,
                'paid_at'        => $data['status'] === 'paid'
                                        ? $dueDate->copy()->subDays(2) : null,
            ]);

            // Create line items
            foreach ($data['items'] as $i => $item) {
                $invoice->items()->create([
                    'description' => $item['description'],
                    'quantity'    => $item['quantity'],
                    'unit_price'  => $item['unit_price'],
                    'total'       => $item['quantity'] * $item['unit_price'],
                    'sort_order'  => $i,
                ]);
            }

            // Calculate totals
            $subtotal  = collect($data['items'])->sum(fn ($i) => $i['quantity'] * $i['unit_price']);
            $vatAmount = round($subtotal * 0.075, 2);
            $total     = $subtotal + $vatAmount;

            $invoice->update([
                'subtotal'   => $subtotal,
                'vat_amount' => $vatAmount,
                'total'      => $total,
            ]);

            // Create payment record for paid invoices
            if ($data['status'] === 'paid') {
                Payment::create([
                    'invoice_id'         => $invoice->id,
                    'amount'             => $total,
                    'payment_method'     => 'paystack',
                    'paystack_reference' => 'DEMO_' . strtoupper(Str::random(12)),
                    'paystack_status'    => 'success',
                    'channel'            => 'card',
                    'currency'           => 'NGN',
                    'paid_at'            => $invoice->paid_at,
                ]);
            }
        }

        // Recalculate client totals
        foreach ($clientModels as $client) {
            $client->recalculateTotals();
        }

        // ─────────────────────────────────────────
        // EXPENSES (last 3 months)
        // ─────────────────────────────────────────
        $expenses = [
            ['date' => Carbon::now()->subMonths(2)->setDay(3),  'category' => 'rent',              'amount' => 150000, 'description' => 'Office rent — May'],
            ['date' => Carbon::now()->subMonths(2)->setDay(5),  'category' => 'utilities',         'amount' => 18500,  'description' => 'Electricity and internet'],
            ['date' => Carbon::now()->subMonths(2)->setDay(12), 'category' => 'software',          'amount' => 25000,  'description' => 'Adobe Creative Cloud subscription'],
            ['date' => Carbon::now()->subMonths(2)->setDay(18), 'category' => 'transport',         'amount' => 12000,  'description' => 'Client visits — Uber'],
            ['date' => Carbon::now()->subMonths(2)->setDay(22), 'category' => 'office_supplies',   'amount' => 8500,   'description' => 'Printer ink and stationery'],
            ['date' => Carbon::now()->subMonths(1)->setDay(3),  'category' => 'rent',              'amount' => 150000, 'description' => 'Office rent — June'],
            ['date' => Carbon::now()->subMonths(1)->setDay(6),  'category' => 'utilities',         'amount' => 21000,  'description' => 'Electricity and internet'],
            ['date' => Carbon::now()->subMonths(1)->setDay(9),  'category' => 'marketing',         'amount' => 45000,  'description' => 'Instagram ads — June campaign'],
            ['date' => Carbon::now()->subMonths(1)->setDay(14), 'category' => 'professional_fees', 'amount' => 30000,  'description' => 'Accountant retainer'],
            ['date' => Carbon::now()->subMonths(1)->setDay(20), 'category' => 'equipment',         'amount' => 85000,  'description' => 'External SSD — 2TB'],
            ['date' => Carbon::now()->setDay(3),                'category' => 'rent',              'amount' => 150000, 'description' => 'Office rent — July'],
            ['date' => Carbon::now()->setDay(5),                'category' => 'utilities',         'amount' => 19500,  'description' => 'Electricity and internet'],
            ['date' => Carbon::now()->setDay(8),                'category' => 'software',          'amount' => 12000,  'description' => 'Figma — annual plan'],
            ['date' => Carbon::now()->setDay(11),               'category' => 'transport',         'amount' => 8500,   'description' => 'Client meeting transport'],
        ];

        foreach ($expenses as $expenseData) {
            $user->expenses()->create($expenseData);
        }
    }
}
