<?php

namespace PortalPeople\invoicing\commands;

use PortalPeople\invoicing\services\InvoiceGenerationService;
use Yii;
use yii\console\Controller;
use yii\console\ExitCode;
use yii\helpers\Console;
/**
 * Invoice Generation Console Command
 *
 * Usage:
 *   php yii surf-invoicing/generate
 *   php yii surf-invoicing/generate --date=2026-03-10
 *   php yii surf-invoicing/generate --dry-run=1
 */
class GenerateController extends Controller
{
    public $defaultAction = 'index';

    /**
     * {@inheritdoc}
     */
    public function options($actionID)
    {
        return ['date', 'dryRun'];
    }

    /**
     * {@inheritdoc}
     */
    public function optionAliases()
    {
        return ['d' => 'date', 'r' => 'dryRun'];
    }

    /**
     * @var string|null Date to process (YYYY-MM-DD format)
     */
    public $date;

    /**
     * @var bool If true, simulates invoice generation without saving
     */
    public $dryRun = false;

    /**
     * Generate invoices for eligible orders
     *
     * @return int
     */
    public function actionIndex(): int
    {
        $date = $this->date ?? date('Y-m-d');
        
        $this->stdout("╔══════════════════════════════════════════╗\n", Console::FG_CYAN);
        $this->stdout("║  Surf Invoice Generation Command         ║\n", Console::FG_CYAN);
        $this->stdout("╚══════════════════════════════════════════╝\n", Console::FG_CYAN);
        $this->stdout("\n");

        $this->stdout("📅 Processing date: {$date}\n", Console::FG_YELLOW);
        if ($this->dryRun) {
            $this->stdout("🧪 DRY RUN MODE - No changes will be saved\n", Console::FG_YELLOW);
        }
        $this->stdout("\n");

        try {
            $service = new InvoiceGenerationService();
            $results = $service->generate($date, $this->dryRun);

            $this->displayResults($results);

            if ($results['failed'] > 0) {
                $this->stdout("\n");
                $this->stdout("❌ Errors encountered:\n", Console::FG_RED);
                foreach ($results['errors'] as $error) {
                    $this->stdout("   Cart ID: {$error['cart_id']}\n", Console::FG_RED);
                    if (isset($error['errors'])) {
                        foreach ($error['errors'] as $field => $msgs) {
                            foreach ((array)$msgs as $msg) {
                                $this->stdout("     - {$field}: {$msg}\n", Console::FG_RED);
                            }
                        }
                    } elseif (isset($error['exception'])) {
                        $this->stdout("     {$error['exception']}\n", Console::FG_RED);
                    }
                }
            }

            return ExitCode::OK;

        } catch (\Exception $e) {
            $this->stderr("❌ Fatal error: " . $e->getMessage() . "\n", Console::FG_RED);
            $this->stderr($e->getTraceAsString() . "\n");
            return ExitCode::DATAERR;
        }
    }

    /**
     * Display formatted results summary
     *
     * @param array $results
     */
    private function displayResults(array $results): void
    {
        $this->stdout("📊 Results:\n", Console::FG_CYAN);
        
        $this->stdout("  ✅ Created:  ", Console::FG_GREEN);
        $this->stdout("{$results['created']} invoices\n");
        
        $this->stdout("  ⏭️  Skipped:   ", Console::FG_YELLOW);
        $this->stdout("{$results['skipped']} (already invoiced)\n");
        
        if ($results['failed'] > 0) {
            $this->stdout("  ❌ Failed:   ", Console::FG_RED);
            $this->stdout("{$results['failed']}\n");
        }

        $total = $results['created'] + $results['skipped'] + $results['failed'];
        $this->stdout("\n  Total processed: {$total}\n");

        if ($results['dry_run']) {
            $this->stdout("\n  (DRY RUN - No changes persisted)\n", Console::FG_YELLOW);
        }
    }
}
