<?php
namespace EasyChat\Controller;

use EasyChat\Library\EasyTokensGiftProvisioner;
use EasyChat\Library\InstallationConsent;
use EasyChat\Library\Install\InstallationAttributionReporter;
use EasyChat\Library\RequestContext;
use EasyChat\Library\Catalog\CatalogSemanticBootstrap;
use EasyChat\Model\Setting;

class Onboarding extends Base {

    protected $layouts = 'layoutclean';

    public function __construct($registry) {
        parent::__construct($registry);

        if (empty(RequestContext::session()['manager_id'])) {
            $this->redirectToRoute('auth');
            exit;
        }

        if ((string)(RequestContext::session()['manager_role'] ?? '') !== 'admin') {
            $this->redirectToRoute('index');
            exit;
        }
    }

    public function index() {
        $model_setting = new Setting($this->registry);

        if (!$this->isOnboardingRequired($model_setting)) {
            $this->redirectToRoute('index');
            exit;
        }

        $gift_status = (string)$model_setting->get('chat_easytokens_gift_status', '');
        $gift_email = $this->preferredEmail($model_setting);
        $this->vars['title'] = 'Первый запуск EasyChat';
        $this->vars['onboarding_gift_status'] = $gift_status;
        $this->vars['onboarding_gift_email'] = $gift_email;
        $this->vars['onboarding_gift_locked'] = $this->isGiftFinalOrWaiting($gift_status) ? '1' : '0';
        $services_consent = (string)$model_setting->get('chat_easychat_services_consent', '0');
        $services_consent_source = (string)$model_setting->get('chat_easychat_services_consent_source', '');
         
         
         
        $this->vars['onboarding_services_consent'] = $services_consent_source === '' ? '1' : $services_consent;
        $this->vars['onboarding_news_consent'] = (string)$model_setting->get('chat_easychat_news_consent', '0');
        $this->vars['onboarding_news_email'] = (string)$model_setting->get('chat_easychat_news_email', '') ?: $gift_email;
        $this->vars['onboarding_install_code'] = (string)$model_setting->get('chat_marketing_install_code', '');

        $this->template->view('onboarding');
    }

    public function save() {
        $this->jsonHeaders();
        $this->requireCsrfTokenJson();

        $model_setting = new Setting($this->registry);
        if (!$this->isOnboardingRequired($model_setting)) {
            echo json_encode(array('success' => true, 'redirect' => $this->routeUrl('index')), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            exit;
        }

        $post = RequestContext::post();
        $skip = isset($post['skip']) && (string)$post['skip'] === '1';
        $gift_result = array('success' => true, 'status' => 'skipped');
        $attribution_result = array('success' => true, 'status' => 'not_requested');

        if (!$skip) {
            $consent = InstallationConsent::fromInstallParams($post, $this->source() . '_first_launch');
            if (empty($consent['success'])) {
                echo json_encode(array('success' => false, 'error' => (string)$consent['error']), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                exit;
            }
            $model_setting->setMany($consent['settings']);
            $attribution_result = InstallationAttributionReporter::reportWithModel($model_setting, array(
                'install_code' => isset($post['install_code']) ? (string)$post['install_code'] : '',
                'easychat_services_consent' => isset($post['easychat_services_consent']) ? (string)$post['easychat_services_consent'] : '0',
                'edition' => $this->source(),
                'cms' => $this->source(),
                'version' => defined('EASYCHAT_VERSION') ? EASYCHAT_VERSION : '',
                'site_url' => defined('HTTP_SERVER') ? HTTP_SERVER : '',
                'registry' => $this->registry,
            ));

            $gift_status = (string)$model_setting->get('chat_easytokens_gift_status', '');
            $claim_gift = isset($post['claim_easytokens_gift']) && (string)$post['claim_easytokens_gift'] === '1';
            if ($claim_gift && !$this->isGiftFinalOrWaiting($gift_status)) {
                $gift_result = EasyTokensGiftProvisioner::provisionWithModel($model_setting, array(
                    'claim_easytokens_gift' => '1',
                    'admin_email' => isset($post['admin_email']) ? (string)$post['admin_email'] : '',
                    'edition' => $this->source(),
                    'version' => defined('EASYCHAT_VERSION') ? EASYCHAT_VERSION : '1.0.0',
                    'site_url' => defined('HTTP_SERVER') ? HTTP_SERVER : '',
                    'registry' => $this->registry,
                ));
            }

            $start_ai = isset($post['start_ai_consultant']) && (string)$post['start_ai_consultant'] === '1';
            if ($start_ai && trim((string)$model_setting->get('chat_ai_key', '')) !== '') {
                $model_setting->setMany(array(
                    'chat_ai_status' => '1',
                    'chat_ai_suggestions_status' => '1',
                ));
                CatalogSemanticBootstrap::enableIfReady($this->registry, 'first_launch');
            }
        }

        $now = date('c');
        $model_setting->set('chat_first_launch_consent_completed', '1');
        $model_setting->set('chat_first_launch_consent_completed_at', $now);
        $model_setting->set('chat_first_launch_consent_source', $skip ? $this->source() . '_first_launch_skip' : $this->source() . '_first_launch');

        echo json_encode(array(
            'success' => true,
            'gift' => $gift_result,
            'attribution' => $attribution_result,
            'redirect' => $this->routeUrl('setting') . '#cron-panel',
        ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

    private function isOnboardingRequired(Setting $model_setting) {
        return (string)$model_setting->get('chat_first_launch_consent_required', '0') === '1'
            && (string)$model_setting->get('chat_first_launch_consent_completed', '0') !== '1';
    }

    private function isGiftFinalOrWaiting($status) {
        return in_array((string)$status, array('issued', 'already_issued', 'pending', 'pending_review'), true);
    }

    private function preferredEmail(Setting $model_setting) {
        foreach (array('chat_easytokens_gift_email', 'chat_first_launch_admin_email', 'chat_widget_email', 'chat_easychat_news_email') as $key) {
            $value = strtolower(trim((string)$model_setting->get($key, '')));
            if ($value !== '' && filter_var($value, FILTER_VALIDATE_EMAIL)) {
                return $value;
            }
        }
        return '';
    }

    private function source() {
        $edition = defined('EASYCHAT_CMS_EDITION') ? (string)EASYCHAT_CMS_EDITION : 'cms';
        $edition = preg_replace('/[^a-z0-9_ -]/i', '', $edition);
        return $edition !== '' ? strtolower(str_replace(' ', '_', $edition)) : 'cms';
    }

    private function jsonHeaders() {
        header('Content-Type: application/json; charset=utf-8');
    }
}
