<?php
namespace admin\Controllers;

use Domain\Product\ProductRepository;
use Domain\Category\CategoryRepository;

/**
 * Kontroler masowej edycji produktów.
 * Obsługuje akcje: mass_edit (widok), mass_edit_save (AJAX), get_products_by_category (AJAX).
 * Pozostałe akcje shop_product (view_list, product_edit, save itd.) nadal działają
 * przez fallback na \admin\controls\ShopProduct.
 */
class ShopProductController
{
    private ProductRepository $repository;

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

    /**
     * Widok masowej edycji produktów.
     */
    public function mass_edit(): string
    {
        $categoryRepository = new CategoryRepository( $GLOBALS['mdb'] );

        return \Tpl::view( 'shop-product/mass-edit', [
            'products' => $this->repository->allProductsForMassEdit(),
            'categories' => $categoryRepository->subcategories( null ),
            'dlang' => \front\factory\Languages::default_language()
        ] );
    }

    /**
     * AJAX: zastosowanie rabatu procentowego na zaznaczonych produktach.
     */
    public function mass_edit_save(): void
    {
        $discountPercent = \S::get( 'discount_percent' );
        $products = \S::get( 'products' );

        if ( $discountPercent != '' && $products && is_array( $products ) && count( $products ) > 0 ) {
            $productId = (int) $products[0];
            $result = $this->repository->applyDiscountPercent( $productId, (float) $discountPercent );

            if ( $result !== null ) {
                echo json_encode( [
                    'status' => 'ok',
                    'price_brutto_promo' => $result['price_brutto_promo'],
                    'price_brutto' => $result['price_brutto']
                ] );
                exit;
            }
        }

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

    /**
     * AJAX: pobranie ID produktów z danej kategorii.
     */
    public function get_products_by_category(): void
    {
        $categoryId = (int) \S::get( 'category_id' );
        $products = $this->repository->getProductsByCategory( $categoryId );

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