<?php
namespace EasyChat\Controller;

use EasyChat\Library\EasyTokensGiftProvisioner;
use EasyChat\Library\RequestContext;
use EasyChat\Library\Support\AdminHelpService;
use EasyChat\Model\Setting;

 
final class AdminHelp extends Base {
    protected $layouts = '';

    public function __construct($registry) {
        parent::__construct($registry);
        if ((int)(RequestContext::session()['manager_id'] ?? 0) <= 0) {
            $this->json(['success' => false, 'error' => 'authentication_required'], 401);
        }
    }

    




    public function index() {
        $this->bootstrap();
    }

    public function bootstrap() {
        $this->jsonHeaders();
        $service = new AdminHelpService($this->registry);
        $result = $service->bootstrap(
            $this->managerId(),
            (string)(RequestContext::get()['session_id'] ?? ''),
            $this->locale()
        );
        if ((string)(RequestContext::session()['manager_role'] ?? '') !== 'admin') {
            $result['gift_available'] = false;
            $result['gift_email_required'] = false;
        }
        $this->json($result);
    }

    public function ask() { $this->answer(false); }
    public function diagnose() { $this->answer(true); }
    public function stream() { $this->streamAnswer(false); }
    public function streamDiagnose() { $this->streamAnswer(true); }

    public function reset() {
        $this->jsonHeaders();
        $this->requireCsrfTokenJson();
        $result = (new AdminHelpService($this->registry))->reset(
            $this->managerId(),
            (string)(RequestContext::post()['session_id'] ?? '')
        );
        $this->json($result);
    }

    public function feedback() {
        $this->jsonHeaders();
        $this->requireCsrfTokenJson();
        $post = RequestContext::post();
        $result = (new AdminHelpService($this->registry))->feedback(
            $this->managerId(),
            (string)($post['session_id'] ?? ''),
            (int)($post['message_id'] ?? 0),
            (int)($post['value'] ?? 0)
        );
        $status = max(200, min(599, (int)($result['http_status'] ?? 200)));
        unset($result['http_status']);
        $this->json($result, $status);
    }

    public function gift() {
        $this->jsonHeaders();
        $this->requireCsrfTokenJson();
        if ((string)(RequestContext::session()['manager_role'] ?? '') !== 'admin') {
            $this->json(['success' => false, 'error' => 'admin_required'], 403);
        }
        $model = new Setting($this->registry);
        $support_key = trim((string)$model->get('chat_easytokens_support_key', ''));
        $primary_easytokens = strtolower(trim((string)$model->get('chat_ai_provider', ''))) === 'easytokens'
            && trim((string)$model->get('chat_ai_key', '')) !== '';
        if ($support_key !== '' || $primary_easytokens) {
            $this->json(['success' => true, 'status' => 'already_configured']);
        }
        $result = EasyTokensGiftProvisioner::provisionWithModel($model, [
            'claim_easytokens_gift' => '1',
            'admin_email' => (string)(RequestContext::post()['email'] ?? ''),
            'edition' => 'standalone',
            'version' => defined('EASYCHAT_VERSION') ? EASYCHAT_VERSION : '1.0.0',
            'site_url' => HTTP_SERVER,
            'registry' => $this->registry,
            'credential_scope' => 'support',
        ]);
         
        unset($result['api_token']);
        $this->json($result, !empty($result['success']) ? 200 : 422);
    }

    private function answer(bool $diagnose): void {
        $this->jsonHeaders();
        $this->requireCsrfTokenJson();
        $post = RequestContext::post();
        $ip = trim((string)(RequestContext::server()['REMOTE_ADDR'] ?? ''));
        $secret = (string)(new Setting($this->registry))->get('chat_install_secret', 'easychat-local');
        $ip_hash = $ip !== '' ? hash_hmac('sha256', $ip, $secret) : '';
        $result = (new AdminHelpService($this->registry))->ask(
            $this->managerId(),
            (string)($post['session_id'] ?? ''),
            (string)($post['question'] ?? ''),
            (string)($post['route'] ?? 'index'),
            $this->locale(),
            strtolower(trim((string)($post['request_key'] ?? ''))),
            $ip_hash,
            $diagnose
        );
        $status = max(200, min(599, (int)($result['http_status'] ?? 200)));
        unset($result['http_status']);
        $this->json($result, $status);
    }

    private function streamAnswer(bool $diagnose): void {
        $this->requireCsrfTokenJson();
        ignore_user_abort(true);
        if (function_exists('session_write_close')) @session_write_close();
        header('Content-Type: text/event-stream; charset=utf-8');
        header('Cache-Control: no-store, no-transform');
        header('X-Accel-Buffering: no');
        header('X-Content-Type-Options: nosniff');
        header('Referrer-Policy: no-referrer');

        $post = RequestContext::post();
        $ip = trim((string)(RequestContext::server()['REMOTE_ADDR'] ?? ''));
        $secret = (string)(new Setting($this->registry))->get('chat_install_secret', 'easychat-local');
        $ip_hash = $ip !== '' ? hash_hmac('sha256', $ip, $secret) : '';
        $emit = function (array $event): void {
            echo 'data: ' . json_encode($event, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n\n";
            if (function_exists('ob_flush')) @ob_flush();
            flush();
        };
        $result = (new AdminHelpService($this->registry))->ask(
            $this->managerId(),
            (string)($post['session_id'] ?? ''),
            (string)($post['question'] ?? ''),
            (string)($post['route'] ?? 'index'),
            $this->locale(),
            strtolower(trim((string)($post['request_key'] ?? ''))),
            $ip_hash,
            $diagnose,
            function (string $delta) use ($emit): void {
                if ($delta !== '') $emit(['type' => 'delta', 'delta' => $delta]);
            }
        );
        unset($result['http_status']);
        $emit(['type' => 'result', 'data' => $result]);
        echo "data: [DONE]\n\n";
        exit;
    }

    private function managerId(): int { return max(0, (int)(RequestContext::session()['manager_id'] ?? 0)); }
    private function locale(): string { return (string)(RequestContext::session()['easychat_locale'] ?? 'ru') === 'en' ? 'en' : 'ru'; }

    private function jsonHeaders(): void {
        header('Content-Type: application/json; charset=utf-8');
        header('Cache-Control: no-store');
        header('X-Content-Type-Options: nosniff');
        header('Referrer-Policy: no-referrer');
    }

    private function json(array $payload, int $status = 200): void {
        http_response_code($status);
        echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
}
