<?php

namespace PortalPeople\zupa\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;
use yii\web\ForbiddenHttpException;
use PortalPeople\zupa\models\ConfigForm;
use PortalPeople\zupa\services\FtpDownloadService;
use PortalPeople\zupa\Module;

class ConfigController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['admin'],
                    ],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        $model = new ConfigForm();
        $model->loadFromParams();

        if ($model->load(Yii::$app->request->post()) && $model->saveToParams()) {
            Yii::$app->session->setFlash('success', 'Zupa configuration saved successfully.');

            return $this->redirect(['index']);
        }

        return $this->render('index', [
            'model' => $model,
            'testResult' => null,
        ]);
    }

    public function actionTestConnection()
    {
        if (!Yii::$app->request->isAjax) {
            throw new ForbiddenHttpException('Invalid request');
        }

        $model = new ConfigForm();

        if ($model->load(Yii::$app->request->post(), '')) {
            if (!$model->validate()) {
                return $this->asJson([
                    'success' => false,
                    'errors' => $model->getErrors(),
                ]);
            }

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

            $result = $service->download();

            return $this->asJson([
                'success' => empty($result['errors']),
                'message' => empty($result['errors']) 
                    ? 'Connection successful!' 
                    : 'Connection failed: ' . implode(', ', $result['errors']),
                'errors' => $result['errors'],
            ]);
        }

        return $this->asJson(['success' => false, 'message' => 'Invalid data']);
    }

    public function actionDryRun()
    {
        if (!Yii::$app->request->isAjax) {
            throw new ForbiddenHttpException('Invalid request');
        }

        /** @var Module $module */
        $module = Yii::$app->getModule('zupa');

        if (!$module || !$module->isConfigured()) {
            return $this->asJson([
                'success' => false,
                'message' => 'Zupa module not configured',
            ]);
        }

        $dryDir = Yii::getAlias('@runtime/zupa/dry-run');
        @mkdir($dryDir, 0755, true);

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

        $result = $service->download();

        // Clean up dry-run files
        array_map('unlink', glob($dryDir . '/*.xml'));
        @rmdir($dryDir);

        return $this->asJson([
            'success' => empty($result['errors']),
            'downloaded' => count($result['downloaded']),
            'errors' => $result['errors'],
        ]);
    }

    public function actionStatus()
    {
        if (!Yii::$app->request->isAjax) {
            throw new ForbiddenHttpException('Invalid request');
        }

        /** @var Module $module */
        $module = Yii::$app->getModule('zupa');

        if (!$module || !$module->isConfigured()) {
            return $this->asJson([
                'success' => false,
                'message' => 'Zupa module not configured',
            ]);
        }

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

        $inboxCount = is_dir($inboxDir) ? count(glob($inboxDir . '/*.xml')) : 0;
        $processedCount = is_dir($processedDir) ? count(glob($processedDir . '/*.xml')) : 0;
        $failedCount = is_dir($failedDir) ? count(glob($failedDir . '/*.xml')) : 0;

        return $this->asJson([
            'success' => true,
            'inbox' => $inboxCount,
            'processed' => $processedCount,
            'failed' => $failedCount,
        ]);
    }
}
