<?php
namespace EasyChat\Controller;

use EasyChat\Model\AppPairing;
use EasyChat\Model\Manager;

class MobileConnect extends Base {

    protected $layouts = '';

    public function index() {
        $this->jsonError('endpoint_not_found', 404);
    }

    public function create() {
        header('Content-Type: application/json; charset=utf-8');
        $this->requireOperator();

        if ((\EasyChat\Library\RequestContext::server()['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
            $this->jsonError('method_not_allowed', 405);
        }
        $input = $this->readJsonInput();
        $this->verifyNonce((string)($input['nonce'] ?? ''));

        $manager_id = (int)\EasyChat\Library\RequestContext::session()['manager_id'];
        $model_pairing = new AppPairing($this->registry);
        $pairing = $model_pairing->create($manager_id, AppPairing::DEFAULT_TTL_SECONDS, $this->clientIp());
        $site_url = $this->publicSiteUrl();

        $payload = array(
            'v' => 1,
            'site_url' => $site_url,
            'pairing_id' => $pairing['public_id'],
            'pairing_secret' => $pairing['secret'],
            'expires_at' => $pairing['expires_at'],
            'source' => 'easychat_admin',
        );

        $this->jsonOut(array(
            'success' => 1,
            'connect_url' => $this->connectUrl($payload),
            'site_url' => $site_url,
            'expires_at' => $pairing['expires_at'],
            'ttl_seconds' => AppPairing::DEFAULT_TTL_SECONDS,
            'android_package' => 'ru.liveopencart.easychat',
            'android_store_url' => 'https://www.rustore.ru/catalog/app/ru.liveopencart.easychat',
        ));
    }

    private function connectUrl(array $payload) {
        $json = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $base64 = rtrim(strtr(base64_encode($json), '+/', '-_'), '=');

         
         
        return 'https://easychat24.ru/app/connect/#p=' . $base64;
    }

    private function publicSiteUrl() {
        if (function_exists('\\easychat_public_base_url')) {
            return \easychat_public_base_url();
        }

        return defined('HTTP_SERVER') ? rtrim(HTTP_SERVER, '/') . '/' : '/';
    }

    private function requireOperator() {
        if (empty(\EasyChat\Library\RequestContext::session()['manager_id'])) {
            $this->jsonError('unauthorized', 401);
        }

        $model_manager = new Manager($this->registry);
        $manager = $model_manager->getManagerById((int)\EasyChat\Library\RequestContext::session()['manager_id']);
        if (!$manager || (int)$manager['status'] !== 1) {
            \EasyChat\Library\SessionBootstrap::destroy();
            $this->jsonError('unauthorized', 401);
        }
    }

    private function clientIp() {
        $ip = trim((string)(\EasyChat\Library\RequestContext::server()['REMOTE_ADDR'] ?? ''));
        return strlen($ip) <= 45 ? $ip : '';
    }

    private function verifyNonce($nonce) {
        if (empty(\EasyChat\Library\RequestContext::session()['easychat_mobile_connect_nonce']) || !hash_equals((string)\EasyChat\Library\RequestContext::session()['easychat_mobile_connect_nonce'], (string)$nonce)) {
            $this->jsonError('invalid_nonce', 403);
        }
    }

    private function readJsonInput() {
        $raw = file_get_contents('php://input');
        $decoded = json_decode(is_string($raw) ? $raw : '', true);
        return is_array($decoded) ? $decoded : array();
    }

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

    private function jsonError($code, $status = 400) {
        $this->jsonOut(array('success' => 0, 'code' => $code, 'error' => $code), $status);
    }
}
