<?php
namespace EasyChat\Controller;

use EasyChat\Library\Messenger\Marketplace\MarketplaceAccountService;
use EasyChat\Library\Messenger\Marketplace\MarketplaceActionService;
use EasyChat\Library\Messenger\Marketplace\MarketplaceConversationService;
use EasyChat\Library\Messenger\Marketplace\MarketplaceAdminPresenter;
use EasyChat\Library\Messenger\ProviderRegistry;
use EasyChat\Library\Messenger\WildberriesTokenInspector;
use EasyChat\Library\RequestContext;

class Marketplace extends Base {
    protected $layouts = 'layout';

    public function __construct($registry) {
        parent::__construct($registry);
        if (empty(RequestContext::session()['manager_id'])) {
            header('Location: index.php?route=auth');
            exit;
        }
    }

    public function index(): void {
        $this->requireAdminPage();
        $provider = MarketplaceAdminPresenter::normalizeProvider(
            (string)(RequestContext::get()['provider'] ?? '')
        );
        if ($provider === '') {
            $provider = 'wildberries';
        }

        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Location: ' . $this->routeUrl('integration&tab=' . rawurlencode($provider)), true, 302);
        exit;
    }

    public function connect(): void {
        $this->requireAdminJson();
        $post = RequestContext::post();
        $input = [
            'api_token' => (string)($post['api_token'] ?? ''),
            'client_id' => (string)($post['client_id'] ?? ''),
            'api_key' => (string)($post['api_key'] ?? ''),
        ];
         
         
         
        if (array_key_exists('ai_auto_reply', $post)) {
            $input['ai_auto_reply'] = (string)$post['ai_auto_reply'] === '1';
        }
        $result = (new MarketplaceAccountService($this->registry))->connect(
            (string)($post['provider'] ?? ''),
            $input,
            (int)($post['channel_id'] ?? 0)
        );
        $this->jsonResult($result, empty($result['success']) ? 422 : 200);
    }

    




    public function inspectCredential(): void {
        $this->requireAdminJson();
        $post = RequestContext::post();
        if ((string)($post['provider'] ?? '') === 'ozon') {
            $provider = ProviderRegistry::get('ozon', $this->registry);
            $inspection = $provider ? $provider->validateMarketplaceCredentials([
                'client_id' => (string)($post['client_id'] ?? ''),
                'api_key' => (string)($post['api_key'] ?? ''),
            ]) : ['success' => false, 'error' => 'marketplace_provider_unavailable'];
            if (empty($inspection['success'])) {
                $inspection['message'] = MarketplaceAdminPresenter::errorMessage((string)($inspection['error'] ?? 'auth_failed'));
                $this->jsonResult($inspection, 422);
            }
            $capabilities = is_array($inspection['capabilities'] ?? null) ? $inspection['capabilities'] : [];
            $this->jsonResult([
                'success' => true,
                'key_health' => MarketplaceAdminPresenter::ozonKeyHealth((string)($capabilities['key_expires_at'] ?? '')),
                'stream_access' => $capabilities['stream_access'] ?? [],
            ]);
        }
        if ((string)($post['provider'] ?? '') !== 'wildberries') {
            $this->jsonResult(['success' => false, 'error' => 'marketplace_provider_unavailable'], 422);
        }
        $inspection = WildberriesTokenInspector::publicMetadata(
            WildberriesTokenInspector::inspect((string)($post['api_token'] ?? ''))
        );
        if (empty($inspection['success'])) {
            $inspection['message'] = MarketplaceAdminPresenter::errorMessage(
                (string)($inspection['error'] ?? 'wb_token_format_invalid')
            );
        }
        $this->jsonResult($inspection, empty($inspection['success']) ? 422 : 200);
    }

    public function disconnect(): void {
        $this->requireAdminJson();
        $result = (new MarketplaceAccountService($this->registry))->disconnect(
            (int)(RequestContext::post()['channel_id'] ?? 0)
        );
        $this->jsonResult($result, empty($result['success']) ? 404 : 200);
    }

    public function stream(): void {
        $this->requireAdminJson();
        $post = RequestContext::post();
        $result = (new MarketplaceAccountService($this->registry))->setStreamStatus(
            (int)($post['channel_id'] ?? 0),
            (string)($post['stream'] ?? ''),
            (string)($post['enabled'] ?? '0') === '1'
        );
        $this->jsonResult($result, empty($result['success']) ? 422 : 200);
    }

    public function syncNow(): void {
        $this->requireAdminJson();
        $post = RequestContext::post();
        $result = (new MarketplaceAccountService($this->registry))->syncNow(
            (int)($post['channel_id'] ?? 0),
            (string)($post['stream'] ?? '')
        );
        $this->jsonResult($result, empty($result['success']) ? 422 : 202);
    }

    public function options(): void {
        $this->requireAdminJson();
        $post = RequestContext::post();
        $input = [];
        foreach (['ai_auto_reply'] as $key) {
            if (array_key_exists($key, $post)) {
                $input[$key] = (string)$post[$key] === '1';
            }
        }
        $result = (new MarketplaceAccountService($this->registry))->setOptions(
            (int)($post['channel_id'] ?? 0),
            $input
        );
        $this->jsonResult($result, empty($result['success']) ? 422 : 200);
    }

     
    public function action(): void {
        $this->requireJsonRequest();
        $post = RequestContext::post();
        $result = (new MarketplaceActionService($this->registry))->execute(
            (int)($post['chat_id'] ?? 0),
            (string)($post['action'] ?? ''),
            [
                'text' => (string)($post['text'] ?? ''),
                'request_id' => (string)($post['request_id'] ?? ''),
                'action_id' => (int)($post['action_id'] ?? 0),
                'claim_action' => (string)($post['claim_action'] ?? ''),
                'compensation_amount' => $post['compensation_amount'] ?? null,
                'rejection_reason_id' => $post['rejection_reason_id'] ?? null,
                'return_for_back_way' => $post['return_for_back_way'] ?? null,
            ],
            (int)(RequestContext::session()['manager_id'] ?? 0)
        );
        $this->jsonResult($result, empty($result['success']) ? 422 : 200);
    }

     
    public function startConversation(): void {
        $this->requireJsonRequest();
        $post = RequestContext::post();
        $result = (new MarketplaceConversationService($this->registry))->start(
            [
                'channel_id' => (int)($post['channel_id'] ?? 0),
                'provider' => (string)($post['provider'] ?? ''),
                'posting_number' => (string)($post['posting_number'] ?? ''),
                'context_type' => (string)($post['context_type'] ?? ''),
                'context_id' => (string)($post['context_id'] ?? ''),
                'text' => (string)($post['text'] ?? ''),
                'request_id' => (string)($post['request_id'] ?? ''),
            ],
            (int)(RequestContext::session()['manager_id'] ?? 0)
        );
        $this->jsonResult($result, empty($result['success']) ? 422 : 200);
    }

    private function requireAdminPage(): void {
        if ((string)(RequestContext::session()['manager_role'] ?? '') !== 'admin') {
            header('Location: index.php?route=index');
            exit;
        }
    }

    private function requireAdminJson(): void {
        if ((string)(RequestContext::session()['manager_role'] ?? '') !== 'admin') {
            $this->jsonResult(['success' => false, 'error' => 'admin_required'], 403);
        }
        $this->requireJsonRequest();
    }

    private function requireJsonRequest(): void {
        header('Content-Type: application/json; charset=utf-8');
        $this->requireCsrfTokenJson();
         
         
        if (session_status() === PHP_SESSION_ACTIVE) {
            session_write_close();
        }
    }

    private function jsonResult(array $result, int $status): void {
        http_response_code($status);
        if (empty($result['success'])) {
            $result['message'] = MarketplaceAdminPresenter::errorMessage((string)($result['error'] ?? 'marketplace_request_failed'));
        }
        echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

}
