<?php
namespace admin\Controllers;

use Domain\Category\CategoryRepository;
use Domain\Languages\LanguagesRepository;

class ShopCategoryController
{
    private CategoryRepository $repository;
    private LanguagesRepository $languagesRepository;

    public function __construct(CategoryRepository $repository, LanguagesRepository $languagesRepository)
    {
        $this->repository = $repository;
        $this->languagesRepository = $languagesRepository;
    }

    public function view_list(): string
    {
        return \Tpl::view('shop-category/categories-list', [
            'categories' => $this->repository->subcategories(null),
            'level' => 0,
            'dlang' => \front\factory\Languages::default_language(),
        ]);
    }

    public function list(): string
    {
        return $this->view_list();
    }

    public function category_edit(): string
    {
        return \Tpl::view('shop-category/category-edit', [
            'category' => $this->repository->categoryDetails(\S::get('id')),
            'pid' => \S::get('pid'),
            'languages' => $this->languagesRepository->languagesList(),
            'sort_types' => $this->repository->sortTypes(),
        ]);
    }

    public function edit(): string
    {
        return $this->category_edit();
    }

    public function save(): void
    {
        $response = [
            'status' => 'error',
            'msg' => 'Podczas zapisywania kategorii wystąpił błąd. Proszę spróbować ponownie.',
        ];

        $values = json_decode((string)\S::get('values'), true);
        if (is_array($values)) {
            $savedId = $this->repository->save($values);
            if (!empty($savedId)) {
                $response = [
                    'status' => 'ok',
                    'msg' => 'Kategoria została zapisana.',
                    'id' => (int)$savedId,
                ];
            }
        }

        echo json_encode($response);
        exit;
    }

    public function category_delete(): void
    {
        if ($this->repository->categoryDelete(\S::get('id'))) {
            \S::set_message('Kategoria została usunięta.');
        } else {
            \S::alert('Podczas usuwania kategorii wystąpił błąd. Aby usunąć kategorię nie może ona posiadać przypiętych podkategorii.');
        }

        header('Location: /admin/shop_category/view_list/');
        exit;
    }

    public function delete(): void
    {
        $this->category_delete();
    }

    public function category_products(): string
    {
        return \Tpl::view('shop-category/category-products', [
            'category_id' => \S::get('id'),
            'products' => $this->repository->categoryProducts((int)\S::get('id')),
        ]);
    }

    public function products(): string
    {
        return $this->category_products();
    }

    public function category_url_browser(): void
    {
        echo \Tpl::view('shop-category/category-browse-list', [
            'categories' => $this->repository->subcategories(null),
            'level' => 0,
            'dlang' => \front\factory\Languages::default_language(),
        ]);
        exit;
    }

    public function save_categories_order(): void
    {
        $response = [
            'status' => 'error',
            'msg' => 'Podczas zapisywania kolejności kategorii wystąpił błąd. Proszę spróbować ponownie.',
        ];

        if ( $this->repository->saveCategoriesOrder( \S::get( 'categories' ) ) ) {
            $response = [ 'status' => 'ok' ];
        }

        echo json_encode( $response );
        exit;
    }

    public function save_products_order(): void
    {
        $response = [
            'status' => 'error',
            'msg' => 'Podczas zapisywania kolejności wyświetlania produktów wystąpił błąd. Proszę spróbować ponownie.',
        ];

        if ( $this->repository->saveProductOrder( \S::get( 'category_id' ), \S::get( 'products' ) ) ) {
            $response = [ 'status' => 'ok' ];
        }

        echo json_encode( $response );
        exit;
    }

    public function cookie_categories(): void
    {
        $categoryId = (string) \S::get( 'category_id' );
        if ( $categoryId === '' ) {
            echo json_encode( [ 'status' => 'error' ] );
            exit;
        }

        $array = [];
        if ( isset( $_COOKIE['cookie_categories'] ) ) {
            $tmp = @unserialize( (string) $_COOKIE['cookie_categories'] );
            if ( is_array( $tmp ) ) {
                $array = $tmp;
            }
        }

        $array[$categoryId] = isset( $array[$categoryId] ) && (int) $array[$categoryId] === 1 ? 0 : 1;

        setcookie( 'cookie_categories', serialize( $array ), time() + 3600 * 24 * 365, '/' );

        echo json_encode( [ 'status' => 'ok' ] );
        exit;
    }
}
