<?php

namespace PortalPeople\zupa\commands;

use Yii;
use yii\console\Controller;
use yii\console\ExitCode;
use PortalPeople\zupa\Module;
use PortalPeople\zupa\services\FtpDownloadService;
use PortalPeople\zupa\services\ProcessFilesService;

class ZupaController extends Controller
{
    public function actionDownload($delete = false)
    {
        $this->stdout("Starting Zupa file download...\n");

        /** @var Module $module */
        $module = Yii::$app->getModule('zupa');
        if (!$module || !$module->isConfigured()) {
            $this->stderr("ERROR: Zupa module not configured\n");

            return ExitCode::CONFIG;
        }

        $inboxDir = Yii::getAlias('@runtime/zupa/inbox');
        if (!is_dir($inboxDir)) {
            @mkdir($inboxDir, 0755, true);
        }

        $service = new FtpDownloadService([
            'protocol' => $module->protocol,
            'host' => $module->ftpHost,
            'port' => $module->ftpPort,
            'username' => $module->ftpUser,
            'password' => $module->ftpPassword,
            'remotePath' => $module->ftpPath,
            'deleteAfterDownload' => (bool) $delete,
            'inboxPath' => $inboxDir,
        ]);

        $result = $service->download();

        $this->stdout("Downloaded: " . count($result['downloaded']) . " files\n");

        if (!empty($result['downloaded'])) {
            foreach ($result['downloaded'] as $file) {
                $this->stdout("  ✓ $file\n");
            }
        }

        if (!empty($result['errors'])) {
            $this->stderr("Errors:\n");
            foreach ($result['errors'] as $err) {
                $this->stderr("  ✗ $err\n");
            }

            return ExitCode::IOERR;
        }

        return ExitCode::OK;
    }

    public function actionProcess($dryRun = false)
    {
        $this->stdout("Starting Zupa file processing...\n");

        /** @var Module $module */
        $module = Yii::$app->getModule('zupa');
        if (!$module || !$module->isConfigured()) {
            $this->stderr("ERROR: Zupa module not configured\n");

            return ExitCode::CONFIG;
        }

        $inboxDir = Yii::getAlias('@runtime/zupa/inbox');
        $processedDir = Yii::getAlias('@runtime/zupa/processed');
        $failedDir = Yii::getAlias('@runtime/zupa/failed');

        foreach ([$inboxDir, $processedDir, $failedDir] as $dir) {
            if (!is_dir($dir)) {
                @mkdir($dir, 0755, true);
            }
        }

        $service = new ProcessFilesService([
            'inboxPath' => $inboxDir,
            'processedPath' => $processedDir,
            'failedPath' => $failedDir,
            'module' => $module,
        ]);

        $result = $service->process();

        $this->stdout("Processed: {$result['processed']} files\n");
        $this->stdout("Orders created: {$result['created']}\n");

        if ($result['failed'] > 0) {
            $this->stderr("Failed: {$result['failed']}\n");

            if (!empty($result['errors'])) {
                foreach ($result['errors'] as $err) {
                    $this->stderr("  {$err['file']}: {$err['error']}\n");
                }
            }
        }

        return $result['success'] ? ExitCode::OK : ExitCode::IOERR;
    }

    public function actionTest()
    {
        $this->stdout("Testing Zupa FTP connection...\n");

        /** @var Module $module */
        $module = Yii::$app->getModule('zupa');
        if (!$module) {
            $this->stderr("ERROR: Zupa module not loaded\n");

            return ExitCode::CONFIG;
        }

        if (!$module->isConfigured()) {
            $this->stderr("ERROR: Zupa module not configured\n");
            $this->stderr("Missing configuration in params-local.php under plugins.zupa\n");

            return ExitCode::CONFIG;
        }

        $this->stdout("Config found:\n");
        $this->stdout("  Protocol: {$module->protocol}\n");
        $this->stdout("  Host: {$module->ftpHost}\n");
        $this->stdout("  Port: {$module->ftpPort}\n");
        $this->stdout("  Path: {$module->ftpPath}\n");
        $this->stdout("  Download interval: {$module->downloadInterval}s\n");
        $this->stdout("  Process interval: {$module->processInterval}s\n");
        $this->stdout("  Summary email: {$module->summaryEmail}\n\n");

        $this->stdout("Testing connection...\n");

        $service = new FtpDownloadService([
            'protocol' => $module->protocol,
            'host' => $module->ftpHost,
            'port' => $module->ftpPort,
            'username' => $module->ftpUser,
            'password' => $module->ftpPassword,
            'remotePath' => $module->ftpPath,
            'deleteAfterDownload' => false,
            'inboxPath' => Yii::getAlias('@runtime/zupa/inbox'),
        ]);

        $result = $service->download();

        if ($result['success'] || empty($result['errors'])) {
            $this->stdout("✓ Connection successful\n");

            return ExitCode::OK;
        } else {
            $this->stderr("✗ Connection failed\n");
            foreach ($result['errors'] as $err) {
                $this->stderr("  $err\n");
            }

            return ExitCode::IOERR;
        }
    }
}
