<?php
namespace App\Commands;

use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use App\Models\TransactionModel;
use App\Libraries\TransactionService;

class RejectExpiredTransactions extends BaseCommand
{
    /**
     * The Command's Group
     *
     * @var string
     */
    protected $group = 'Transactions';

    /**
     * The Command's Name
     *
     * @var string
     */
    protected $name = 'transactions:reject-expired';

    /**
     * The Command's Description
     *
     * @var string
     */
    protected $description = 'Finds and rejects pending VA transactions older than 24 hours.';

    /**
     * The Command's Usage
     *
     * @var string
     */
    protected $usage = 'transactions:reject-expired';

    /**
     * The Command's Arguments
     *
     * @var array
     */
    protected $arguments = [];

    /**
     * The Command's Options
     *
     * @var array
     */
    protected $options = [];

    /**
     * Actually execute a command.
     *
     * @param array $params
     */
    public function run(array $params)
    {
        CLI::write('Starting process to reject expired VA transactions...', 'cyan');

        $transactionModel = new TransactionModel();

        $twentyFourHoursAgo = date('Y-m-d H:i:s', strtotime('-24 hours'));

        $expiredTransactions = $transactionModel
            ->where('payment_type', 'va')
            ->where('payment_status', 'pending')
            ->where('created_at <', $twentyFourHoursAgo)
            ->findAll();

        if (empty($expiredTransactions)) {
            CLI::write('No expired transactions found.', 'yellow');
            return;
        }

        $count = count($expiredTransactions);
        CLI::write("Found {$count} expired transaction(s) to reject.", 'white');

        $transactionService = new TransactionService();
        $rejectedCount = 0;

        foreach ($expiredTransactions as $transaction) {
            CLI::write("Processing invoice: {$transaction->invoice_number}...", 'light_gray');

            $success = $transactionService->changeStatus(
                $transaction->id, 
                'rejected', 
                0, // ID 0 untuk menandakan ini adalah aksi sistem/otomatis
                true, 
                'Transaction expired automatically after 24 hours.'
            );

            if ($success) {
                CLI::write(" -> Status changed to REJECTED.", 'green');
                $rejectedCount++;
            } else {
                CLI::write(" -> FAILED to change status.", 'red');
            }
        }

        CLI::write("Successfully rejected {$rejectedCount} of {$count} transaction(s).", 'cyan');
    }
}