<?php
namespace EasyChat\Controller;

use EasyChat\Library\Operator\OperatorAvatarService;
use EasyChat\Library\Operator\OperatorSelfService;
use EasyChat\Library\RequestContext;





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

    public function index() {
        $this->jsonHeaders();
        $manager_id = $this->managerId();
        if ($manager_id <= 0) {
            $this->json(['success' => false, 'error' => 'authentication_required'], 401);
        }
        $profile = (new OperatorSelfService($this->registry))->profile($manager_id);
        if (!$profile) {
            $this->json(['success' => false, 'error' => 'operator_not_found'], 404);
        }
        $this->json(['success' => true, 'profile' => $profile]);
    }

    public function changePassword() {
        $this->jsonHeaders();
        $this->requireCsrfTokenJson();
        $manager_id = $this->managerId();
        if ($manager_id <= 0) {
            $this->json(['success' => false, 'error' => 'authentication_required'], 401);
        }

        $post = RequestContext::post();
        $result = (new OperatorSelfService($this->registry))->changePassword(
            $manager_id,
            (string)($post['current_password'] ?? ''),
            (string)($post['new_password'] ?? ''),
            (string)($post['password_confirmation'] ?? ''),
            (string)(RequestContext::server()['REMOTE_ADDR'] ?? '')
        );
        if (empty($result['success'])) {
            $status = ($result['code'] ?? '') === 'password_rate_limited' ? 429 : 422;
            $this->json($result, $status);
        }

         
         
         
        RequestContext::session()['manager_pass_hash'] = md5((string)$result['password_hash']);
        unset(RequestContext::session()['suggest_password_change']);
        unset($result['password_hash']);
        $result['message'] = 'Пароль изменён. На других устройствах выполнен выход.';
        $this->json($result);
    }

    public function uploadAvatar() {
        $this->jsonHeaders();
        $this->requireCsrfTokenJson();
        $manager_id = $this->managerId();
        $files = RequestContext::files();
        if ($manager_id <= 0) {
            $this->json(['success' => false, 'error' => 'authentication_required'], 401);
        }
        if (empty($files['avatar']) || !is_array($files['avatar'])) {
            $this->json(['success' => false, 'error' => 'Выберите фотографию.'], 422);
        }
        $result = (new OperatorAvatarService($this->registry))->upload($manager_id, $files['avatar']);
        if (empty($result['success'])) {
            $this->json($result, 422);
        }
         
        RequestContext::session()['manager_img'] = (string)($result['filename'] ?? '');
        $this->json($result);
    }

    public function removeAvatar() {
        $this->jsonHeaders();
        $this->requireCsrfTokenJson();
        $manager_id = $this->managerId();
        if ($manager_id <= 0) {
            $this->json(['success' => false, 'error' => 'authentication_required'], 401);
        }
        $result = (new OperatorAvatarService($this->registry))->remove($manager_id);
        if (empty($result['success'])) {
            $this->json($result, 422);
        }
        RequestContext::session()['manager_img'] = '';
        $this->json($result);
    }

    private function managerId(): int {
        return max(0, (int)(RequestContext::session()['manager_id'] ?? 0));
    }

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

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