<?php
namespace App\Controllers;

use App\Repositories\ProductRepository;
use App\Services\AuthService;
use App\Utils\Sanitizer;

class ProductController extends ApiController
{
    private $productRepo;
    private $authService;

    public function __construct(ProductRepository $productRepo, AuthService $authService)
    {
        $this->productRepo = $productRepo;
        $this->authService = $authService;
    }

    public function getList()
    {
        $products = $this->productRepo->all();
        $this->successResponse(['products' => array_map(fn($p) => $p->toArray(), $products)]);
    }

    public function getUsedInDeals()
    {
        $products = $this->productRepo->allUsedInDeals();
        $this->successResponse(['products' => array_map(fn($p) => $p->toArray(), $products)]);
    }

    public function getKpiList()
    {
        $products = $this->productRepo->allForKpiReportDimension();
        $this->successResponse(['products' => array_map(fn($p) => $p->toArray(), $products)]);
    }

    public function save()
    {
        $id = (int)($_POST['id'] ?? 0);
        if (!$this->can($id > 0 ? 'products.edit' : 'products.create')) {
            $this->errorResponse('فقط ادمین می‌تواند محصول را مدیریت کند');
        }
        $name = Sanitizer::sanitize($_POST['name'] ?? '');
        $serviceLookupItemId = isset($_POST['service_lookup_item_id']) && $_POST['service_lookup_item_id'] !== ''
            ? (int)$_POST['service_lookup_item_id']
            : null;
        if (empty($name)) {
            $this->errorResponse('نام محصول الزامی است');
        }
        if ($serviceLookupItemId !== null && !$this->productRepo->isAllowedServiceLookupItem($serviceLookupItemId)) {
            $this->errorResponse('خدمت لینک‌شده نامعتبر است');
        }

        if ($id > 0) {
            $this->productRepo->update($id, $name, $serviceLookupItemId);
            $this->successResponse(['id' => $id], 'محصول با موفقیت به‌روزرسانی شد');
            return;
        }

        $newId = $this->productRepo->create($name, $serviceLookupItemId);
        $this->successResponse(['id' => $newId], 'محصول با موفقیت اضافه شد');
    }

    public function delete()
    {
        if (!$this->can('products.delete')) {
            $this->errorResponse('فقط ادمین می‌تواند محصول را حذف کند');
        }
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) {
            $this->errorResponse('شناسه محصول نامعتبر است');
        }
        $this->productRepo->delete($id);
        $this->successResponse([], 'محصول حذف شد');
    }

    public function saveServiceLinks()
    {
        if (!$this->can('products.service_links.manage')) {
            $this->errorResponse('فقط ادمین می‌تواند لینک محصولات و خدمات را مدیریت کند');
        }

        $serviceLookupItemId = (int)($_POST['service_lookup_item_id'] ?? 0);
        if ($serviceLookupItemId <= 0 || !$this->productRepo->isAllowedServiceLookupItem($serviceLookupItemId)) {
            $this->errorResponse('خدمت انتخاب‌شده نامعتبر است');
        }

        $productIdsRaw = $_POST['product_ids'] ?? [];
        if (!is_array($productIdsRaw)) {
            $productIdsRaw = array_filter(array_map('trim', explode(',', (string)$productIdsRaw)));
        }
        $productIds = array_values(array_unique(array_filter(array_map('intval', (array)$productIdsRaw))));

        $this->productRepo->bulkAssignProductsToService($serviceLookupItemId, $productIds);
        $this->successResponse([], 'لینک محصولات به خدمت ذخیره شد');
    }

    private function can(string $capabilityKey): bool
    {
        if ($this->authService->isAdmin()) {
            return true;
        }
        global $app;
        return isset($app->services->rbac) && $app->services->rbac && $app->services->rbac->can($capabilityKey);
    }
}
