<?php

namespace PortalPeople\zupa\models;

use Yii;
use yii\base\Model;

class ConfigForm extends Model
{
    public string $protocol = 'sftp';
    public string $ftpHost = '';
    public int $ftpPort = 22;
    public string $ftpUser = '';
    public string $ftpPassword = '';
    public string $ftpPath = '/';
    public bool $deleteAfterDownload = false;
    public int $downloadInterval = 3600;
    public int $processInterval = 7200;
    public string $summaryEmail = '';
    public bool $passiveMode = true;

    public function rules()
    {
        return [
            [['protocol', 'ftpHost', 'ftpUser', 'ftpPassword', 'ftpPath'], 'required'],
            [['ftpPort', 'downloadInterval', 'processInterval'], 'integer', 'min' => 1],
            [['protocol'], 'in', 'range' => ['ftp', 'sftp']],
            [['ftpHost', 'ftpUser', 'ftpPath'], 'string', 'max' => 255],
            [['ftpPassword'], 'string'],
            [['summaryEmail'], 'email', 'when' => fn () => !empty($this->summaryEmail)],
            [['summaryEmail'], 'string', 'max' => 255],
            [['deleteAfterDownload', 'passiveMode'], 'boolean'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'protocol' => 'Protocol',
            'ftpHost' => 'Hostname',
            'ftpPort' => 'Port',
            'ftpUser' => 'Username',
            'ftpPassword' => 'Password',
            'ftpPath' => 'Remote Path',
            'deleteAfterDownload' => 'Delete files after download',
            'downloadInterval' => 'Download interval (seconds)',
            'processInterval' => 'Process interval (seconds)',
            'summaryEmail' => 'Summary email address',
            'passiveMode' => 'Use passive mode (FTP)',
        ];
    }

    public function loadFromParams(): self
    {
        $zupa = Yii::$app->params['plugins']['zupa'] ?? [];

        $this->protocol = $zupa['protocol'] ?? 'sftp';
        $this->ftpHost = $zupa['host'] ?? '';
        $this->ftpPort = (int) ($zupa['port'] ?? 22);
        $this->ftpUser = $zupa['user'] ?? '';
        $this->ftpPassword = $this->decryptPassword($zupa['password'] ?? '');
        $this->ftpPath = $zupa['path'] ?? '/';
        $this->deleteAfterDownload = (bool) ($zupa['delete_after_download'] ?? false);
        $this->downloadInterval = (int) ($zupa['download_interval'] ?? 3600);
        $this->processInterval = (int) ($zupa['process_interval'] ?? 7200);
        $this->summaryEmail = $zupa['summary_email'] ?? '';
        $this->passiveMode = (bool) ($zupa['passive_mode'] ?? true);

        return $this;
    }

    public function saveToParams(): bool
    {
        if (!$this->validate()) {
            return false;
        }

        $zupa = [
            'protocol' => $this->protocol,
            'host' => $this->ftpHost,
            'port' => $this->ftpPort,
            'user' => $this->ftpUser,
            'password' => $this->encryptPassword($this->ftpPassword),
            'path' => $this->ftpPath,
            'delete_after_download' => $this->deleteAfterDownload,
            'download_interval' => $this->downloadInterval,
            'process_interval' => $this->processInterval,
            'summary_email' => $this->summaryEmail,
            'passive_mode' => $this->passiveMode,
        ];

        if (!isset(Yii::$app->params['plugins'])) {
            Yii::$app->params['plugins'] = [];
        }

        Yii::$app->params['plugins']['zupa'] = $zupa;

        return true;
    }

    private function encryptPassword(string $password): string
    {
        if (empty($password)) {
            return '';
        }

        try {
            return Yii::$app->security->encryptByPassword($password, 'zupa_password_key');
        } catch (\Throwable $e) {
            Yii::error('Failed to encrypt Zupa password: ' . $e->getMessage(), 'zupa');

            return '';
        }
    }

    private function decryptPassword(string $encrypted): string
    {
        if (empty($encrypted)) {
            return '';
        }

        try {
            return Yii::$app->security->decryptByPassword($encrypted, 'zupa_password_key');
        } catch (\Throwable $e) {
            return '';
        }
    }
}
