<?php

namespace App\Console\Commands;

use App\Models\Expense;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class ProcessExpenseDates extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'expenses:process-dates';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Process and update expense dates';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('Starting expense date processing...');

        try {
            // Process current month expenses
            $currentMonthExpenses = Expense::whereMonth('expense_date', Carbon::now()->month)
                ->whereYear('expense_date', Carbon::now()->year)
                ->get();

            $this->info("Found {$currentMonthExpenses->count()} expenses for current month");

            // Process any expenses without dates
            $undatedExpenses = Expense::whereNull('expense_date')->get();

            foreach ($undatedExpenses as $expense) {
                $expense->expense_date = Carbon::now();
                $expense->save();
                $this->info("Updated missing date for expense ID: {$expense->id}");
            }

            // Log summary for reporting
            Log::info("Expense date processing completed. Processed {$currentMonthExpenses->count()} current month expenses and {$undatedExpenses->count()} undated expenses.");

            $this->info('Expense date processing completed successfully');
            return Command::SUCCESS;
        } catch (\Exception $e) {
            $this->error("Error processing expense dates: {$e->getMessage()}");
            Log::error("Expense date processing failed: {$e->getMessage()}");
            return Command::FAILURE;
        }
    }
}
