<?php
namespace admin\Controllers;

use Domain\Integrations\IntegrationsRepository;
use admin\ViewModels\Common\PaginatedTableViewModel;

class IntegrationsController
{
    private IntegrationsRepository $repository;

    public function __construct( IntegrationsRepository $repository )
    {
        $this->repository = $repository;
    }

    public function logs(): string
    {
        $sortableColumns = ['id', 'action', 'order_id', 'message', 'date'];

        $filterDefinitions = [
            [
                'key' => 'log_action',
                'label' => 'Akcja',
                'type' => 'text',
            ],
            [
                'key' => 'message',
                'label' => 'Wiadomosc',
                'type' => 'text',
            ],
            [
                'key' => 'order_id',
                'label' => 'ID zamowienia',
                'type' => 'text',
            ],
        ];

        $listRequest = \admin\Support\TableListRequestFactory::fromRequest(
            $filterDefinitions,
            $sortableColumns,
            'id'
        );

        $result = $this->repository->getLogs(
            $listRequest['filters'],
            $listRequest['sortColumn'],
            $listRequest['sortDir'],
            $listRequest['page'],
            $listRequest['perPage']
        );

        $rows = [];
        $lp = ($listRequest['page'] - 1) * $listRequest['perPage'] + 1;

        foreach ( $result['items'] as $item ) {
            $id = (int)($item['id'] ?? 0);
            $context = trim( (string)($item['context'] ?? '') );
            $contextHtml = '';
            if ( $context !== '' ) {
                $contextHtml = '<button class="btn btn-xs btn-default log-context-btn" data-id="' . $id . '">Pokaz</button>'
                    . '<pre class="log-context-pre" id="log-context-' . $id . '" style="display:none;max-height:300px;overflow:auto;margin-top:5px;font-size:11px;white-space:pre-wrap;">'
                    . htmlspecialchars( $context, ENT_QUOTES, 'UTF-8' )
                    . '</pre>';
            }

            $rows[] = [
                'lp' => $lp++ . '.',
                'action' => htmlspecialchars( (string)($item['action'] ?? ''), ENT_QUOTES, 'UTF-8' ),
                'order_id' => $item['order_id'] ? (int)$item['order_id'] : '-',
                'message' => htmlspecialchars( (string)($item['message'] ?? ''), ENT_QUOTES, 'UTF-8' ),
                'context' => $contextHtml,
                'date' => !empty( $item['date'] ) ? date( 'Y-m-d H:i:s', strtotime( (string)$item['date'] ) ) : '-',
            ];
        }

        $total = (int)$result['total'];
        $totalPages = max( 1, (int)ceil( $total / $listRequest['perPage'] ) );

        $viewModel = new PaginatedTableViewModel(
            [
                ['key' => 'lp', 'label' => 'Lp.', 'class' => 'text-center', 'sortable' => false],
                ['key' => 'date', 'sort_key' => 'date', 'label' => 'Data', 'class' => 'text-center', 'sortable' => true],
                ['key' => 'action', 'sort_key' => 'action', 'label' => 'Akcja', 'sortable' => true],
                ['key' => 'order_id', 'sort_key' => 'order_id', 'label' => 'Zamowienie', 'class' => 'text-center', 'sortable' => true],
                ['key' => 'message', 'sort_key' => 'message', 'label' => 'Wiadomosc', 'sortable' => true],
                ['key' => 'context', 'label' => 'Kontekst', 'sortable' => false, 'raw' => true],
            ],
            $rows,
            $listRequest['viewFilters'],
            [
                'column' => $listRequest['sortColumn'],
                'dir' => $listRequest['sortDir'],
            ],
            [
                'page' => $listRequest['page'],
                'per_page' => $listRequest['perPage'],
                'total' => $total,
                'total_pages' => $totalPages,
            ],
            array_merge( $listRequest['queryFilters'], [
                'sort' => $listRequest['sortColumn'],
                'dir' => $listRequest['sortDir'],
                'per_page' => $listRequest['perPage'],
            ] ),
            $listRequest['perPageOptions'],
            $sortableColumns,
            '/admin/integrations/logs/',
            'Brak wpisow w logach.'
        );

        return \Shared\Tpl\Tpl::view( 'integrations/logs', [
            'viewModel' => $viewModel,
        ] );
    }

    public function logs_clear(): void
    {
        $this->repository->clearLogs();
        \Shared\Helpers\Helpers::alert( 'Logi zostaly wyczyszczone.' );
        header( 'Location: /admin/integrations/logs/' );
        exit;
    }

    public function apilo_settings(): string
    {
        return \Shared\Tpl\Tpl::view( 'integrations/apilo-settings', [
            'settings' => $this->repository->getSettings( 'apilo' ),
            'apilo_status' => $this->repository->apiloIntegrationStatus(),
        ] );
    }

    public function apilo_settings_save(): void
    {
        $response = [ 'status' => 'error', 'msg' => 'Podczas zapisywania ustawien wystapil blad. Prosze sprobowac ponownie.' ];
        $fieldId = \Shared\Helpers\Helpers::get( 'field_id' );
        $value = \Shared\Helpers\Helpers::get( 'value' );

        if ( $this->repository->saveSetting( 'apilo', $fieldId, $value ) ) {
            $response = [ 'status' => 'ok', 'msg' => 'Ustawienia zostaly zapisane.', 'value' => $value ];
        }

        echo json_encode( $response );
        exit;
    }

    public function apilo_authorization(): void
    {
        $settings = $this->repository->getSettings( 'apilo' );

        if ( $this->repository->apiloAuthorize(
            (string)($settings['client-id'] ?? ''),
            (string)($settings['client-secret'] ?? ''),
            (string)($settings['authorization-code'] ?? '')
        ) ) {
            echo json_encode( [ 'status' => 'ok', 'msg' => 'Autoryzacja przebiegla pomyslnie.' ] );
            exit;
        }

        $status = $this->repository->apiloIntegrationStatus();
        $message = trim( (string)($status['message'] ?? '') );
        if ( $message === '' ) {
            $message = 'Podczas autoryzacji wystapil blad. Prosze sprawdzic dane i sprobowac ponownie.';
        } else {
            $message = 'Autoryzacja nieudana. ' . $message;
        }

        echo json_encode( [ 'status' => 'error', 'msg' => $message ] );
        exit;
    }

    public function get_platform_list(): void
    {
        $this->fetchApiloListWithFeedback( 'platform', 'Liste platform' );
    }

    public function get_status_types_list(): void
    {
        $this->fetchApiloListWithFeedback( 'status', 'Liste statusow' );
    }

    public function get_carrier_account_list(): void
    {
        $this->fetchApiloListWithFeedback( 'carrier', 'Liste kont przewoznikow' );
    }

    public function get_payment_types_list(): void
    {
        $this->fetchApiloListWithFeedback( 'payment', 'Liste metod platnosci' );
    }

    public function apilo_create_product(): void
    {
        $productId = (int) \Shared\Helpers\Helpers::get( 'product_id' );
        $result = $this->repository->apiloCreateProduct( $productId );

        \Shared\Helpers\Helpers::alert( (string)($result['message'] ?? 'Wystapil blad podczas tworzenia produktu w Apilo.') );
        header( 'Location: /admin/shop_product/view_list/' );
        exit;
    }

    public function apilo_product_search(): void
    {
        $productId = (int) \Shared\Helpers\Helpers::get( 'product_id' );
        $sku = $this->repository->getProductSku( $productId );

        if ( !$sku ) {
            echo json_encode( [ 'status' => 'error', 'msg' => 'Podany produkt nie posiada kodu SKU.' ] );
            exit;
        }

        echo json_encode( $this->repository->apiloProductSearch( $sku ) );
        exit;
    }

    public function apilo_product_select_save(): void
    {
        if ( $this->repository->linkProduct( (int) \Shared\Helpers\Helpers::get( 'product_id' ), \Shared\Helpers\Helpers::get( 'apilo_product_id' ), \Shared\Helpers\Helpers::get( 'apilo_product_name' ) ) ) {
            echo json_encode( [ 'status' => 'ok' ] );
        } else {
            echo json_encode( [ 'status' => 'error', 'msg' => 'Podczas zapisywania produktu wystapil blad. Prosze sprobowac ponownie.' ] );
        }

        exit;
    }

    public function apilo_product_select_delete(): void
    {
        if ( $this->repository->unlinkProduct( (int) \Shared\Helpers\Helpers::get( 'product_id' ) ) ) {
            echo json_encode( [ 'status' => 'ok' ] );
        } else {
            echo json_encode( [ 'status' => 'error', 'msg' => 'Podczas usuwania produktu wystapil blad. Prosze sprobowac ponownie.' ] );
        }

        exit;
    }

    public function shoppro_settings(): string
    {
        return \Shared\Tpl\Tpl::view( 'integrations/shoppro-settings', [
            'settings' => $this->repository->getSettings( 'shoppro' ),
        ] );
    }

    public function shoppro_settings_save(): void
    {
        $response = [ 'status' => 'error', 'msg' => 'Podczas zapisywania ustawien wystapil blad. Prosze sprobowac ponownie.' ];
        $fieldId = \Shared\Helpers\Helpers::get( 'field_id' );
        $value = \Shared\Helpers\Helpers::get( 'value' );

        if ( $this->repository->saveSetting( 'shoppro', $fieldId, $value ) ) {
            $response = [ 'status' => 'ok', 'msg' => 'Ustawienia zostaly zapisane.', 'value' => $value ];
        }

        echo json_encode( $response );
        exit;
    }

    public function shoppro_product_import(): void
    {
        $productId = (int) \Shared\Helpers\Helpers::get( 'product_id' );
        $result = $this->repository->shopproImportProduct( $productId );

        \Shared\Helpers\Helpers::alert( (string)($result['message'] ?? 'Wystapil blad podczas importu produktu.') );
        header( 'Location: /admin/shop_product/view_list/' );
        exit;
    }

    private function fetchApiloListWithFeedback( string $type, string $label ): void
    {
        $result = $this->repository->apiloFetchListResult( $type );

        if ( !empty( $result['success'] ) ) {
            $count = (int)($result['count'] ?? 0);
            \Shared\Helpers\Helpers::alert( $label . ' zostala pobrana. Liczba rekordow: ' . $count . '.' );
        } else {
            $details = trim( (string)($result['message'] ?? 'Nieznany blad.') );
            \Shared\Helpers\Helpers::alert(
                'Nie udalo sie pobrac ' . strtolower( $label ) . '. '
                . $details
                . ' Co zrobic: sprawdz konfiguracje Apilo, wykonaj autoryzacje i ponow pobranie listy.'
            );
        }

        header( 'Location: /admin/integrations/apilo_settings/' );
        exit;
    }
}
