<?php
namespace admin\Controllers;

use Domain\Integrations\IntegrationsRepository;

class IntegrationsController
{
    private IntegrationsRepository $repository;

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

    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;
    }
}
