<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\MoneyMarketAccount;
use Carbon\Carbon;

class UpdateMoneyMarketInterest extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'money-market:update-interest {--frequency= : Update only specific frequency (monthly/quarterly/annually)}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update interest for money market accounts with compound interest';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $frequency = $this->option('frequency');

        $this->info('Starting money market interest update...');

        // Get compound interest accounts that need updating
        $query = MoneyMarketAccount::where('interest_type', 'compound')
            ->where('status', 'active');

        if ($frequency) {
            $query->where('compounding_frequency', $frequency);
        }

        $accounts = $query->get();

        $this->info("Found {$accounts->count()} compound interest accounts to process");

        $updated = 0;
        $totalInterest = 0;

        foreach ($accounts as $account) {
            try {
                $oldInterest = $account->interest_earned;

                // Update periodic interest
                $account->updatePeriodicInterest();

                $newInterest = $account->interest_earned;
                $interestAdded = $newInterest - $oldInterest;

                if ($interestAdded > 0) {
                    $updated++;
                    $totalInterest += $interestAdded;

                    $this->line("Updated {$account->account_number}: +{$interestAdded} interest");
                }
            } catch (\Exception $e) {
                $this->error("Error updating account {$account->account_number}: {$e->getMessage()}");
            }
        }

        $this->info("Interest update completed!");
        $this->info("Accounts updated: {$updated}");
        $this->info("Total interest added: " . number_format($totalInterest, 2));

        // Also update simple interest accounts (real-time calculation)
        $simpleAccounts = MoneyMarketAccount::where('interest_type', 'simple')
            ->where('status', 'active')
            ->get();

        $this->info("Updating {$simpleAccounts->count()} simple interest accounts...");

        foreach ($simpleAccounts as $account) {
            try {
                $account->updateInterestEarned();
            } catch (\Exception $e) {
                $this->error("Error updating simple interest account {$account->account_number}: {$e->getMessage()}");
            }
        }

        $this->info('All interest updates completed successfully!');
    }
}
