<?php

namespace Database\Seeders;

use App\Models\DayLedger;
use App\Models\LedgerEntry;
use App\Models\User;
use Illuminate\Database\Seeder;

class DayLedgerSeeder extends Seeder
{
    public function run(): void
    {
        $admin = User::query()->where('user_type', 'admin')->first();
        if (!$admin) {
            return;
        }

        $openDate = now()->subDay()->toDateString();
        $closedDate = now()->subDays(2)->toDateString();

        DayLedger::query()->updateOrCreate(
            ['date' => $closedDate],
            [
                'opening_balance' => 5000,
                'total_sales' => 22000,
                'total_collection' => 22500,
                'total_expense' => 2000,
                'total_refund' => 500,
                'closing_balance' => 25000,
                'status' => DayLedger::STATUS_CLOSED,
                'closed_by' => $admin->id,
                'closed_at' => now()->subDays(2)->endOfDay(),
            ]
        );

        DayLedger::query()->updateOrCreate(
            ['date' => $openDate],
            [
                'opening_balance' => 25000,
                'total_sales' => 0,
                'total_collection' => 0,
                'total_expense' => 0,
                'total_refund' => 0,
                'closing_balance' => 25000,
                'status' => DayLedger::STATUS_OPEN,
            ]
        );

        LedgerEntry::query()->updateOrCreate(
            [
                'ledger_date' => $openDate,
                'entry_type' => LedgerEntry::TYPE_EXPENSE,
                'payment_mode' => 'cash',
                'remarks' => 'Sample packing expense',
            ],
            [
                'reference_type' => LedgerEntry::REFERENCE_MANUAL,
                'reference_id' => null,
                'amount' => 450,
                'created_by' => $admin->id,
            ]
        );

        LedgerEntry::query()->updateOrCreate(
            [
                'ledger_date' => $openDate,
                'entry_type' => LedgerEntry::TYPE_ADVANCE,
                'payment_mode' => 'card_upi',
                'remarks' => 'Sample advance received',
            ],
            [
                'reference_type' => LedgerEntry::REFERENCE_MANUAL,
                'reference_id' => null,
                'amount' => 1500,
                'created_by' => $admin->id,
            ]
        );
    }
}
