<?php
namespace App\Controllers;

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

class CommissionController extends ApiController
{
    private $commissionService;
    private $authService;
    private $userRepo;
    private $productRepo;

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

    public function getMatrixData()
    {
        $this->assertAdminOrCrm();
        $users = array_map(static function ($user) {
            return [
                'id' => (int)$user->id,
                'display_name' => trim((string)($user->display_name ?: ($user->first_name . ' ' . $user->last_name))),
                'role' => (string)$user->role,
                'is_active' => (int)$user->is_active,
            ];
        }, $this->userRepo->getAll());

        $products = array_map(static function ($product) {
            return [
                'id' => (int)$product->id,
                'name' => (string)$product->name,
            ];
        }, $this->productRepo->all());

        $rules = array_map(static function ($rule) {
            return $rule->toArray();
        }, $this->commissionService->getRules(['is_active' => '']));

        $this->successResponse([
            'users' => $users,
            'products' => $products,
            'rules' => $rules,
        ]);
    }

    public function saveRule()
    {
        $this->assertAdminOrCrm();
        $actorUserId = (int)($_SESSION['user_id'] ?? 0);
        $payload = [
            'id' => (int)($_POST['id'] ?? 0),
            'salesperson_user_id' => (int)($_POST['salesperson_user_id'] ?? 0),
            'product_id' => (int)($_POST['product_id'] ?? 0),
            'base_rate_percent' => (float)($_POST['base_rate_percent'] ?? 0),
            'valid_from' => Sanitizer::sanitize($_POST['valid_from'] ?? ''),
            'valid_to' => Sanitizer::sanitize($_POST['valid_to'] ?? ''),
            'is_active' => isset($_POST['is_active']) ? (int)$_POST['is_active'] : 1,
        ];
        $id = $this->commissionService->saveRule($payload, $actorUserId);
        $this->successResponse(['id' => $id], 'قانون پورسانت ذخیره شد');
    }

    public function getDealCommissions()
    {
        $this->assertAdminOrCrm();
        $status = Sanitizer::sanitize($_POST['status'] ?? $_GET['status'] ?? '');
        $salespersonUserId = (int)($_POST['salesperson_user_id'] ?? $_GET['salesperson_user_id'] ?? 0);
        $filters = [];
        if ($status !== '') $filters['status'] = $status;
        if ($salespersonUserId > 0) $filters['salesperson_user_id'] = $salespersonUserId;

        $rows = array_map(static function ($row) {
            return $row->toArray();
        }, $this->commissionService->getDealCommissions($filters));

        $this->successResponse(['commissions' => $rows]);
    }

    public function updateDealCommissionStatus()
    {
        $this->assertAdminOrCrm();
        $id = (int)($_POST['commission_id'] ?? 0);
        $status = Sanitizer::sanitize($_POST['status'] ?? '');
        if ($id <= 0 || $status === '') {
            $this->errorResponse('شناسه رکورد و وضعیت الزامی است');
        }
        $actorUserId = (int)($_SESSION['user_id'] ?? 0);
        $ok = $this->commissionService->advanceStatus($id, $status, $actorUserId);
        if (!$ok) {
            $this->errorResponse('به‌روزرسانی وضعیت انجام نشد');
        }
        $this->successResponse([], 'وضعیت پورسانت به‌روزرسانی شد');
    }

    private function assertAdminOrCrm(): void
    {
        if (!$this->authService->isAdminOrCrmSpecialist()) {
            $this->errorResponse('دسترسی محدود', 403);
        }
    }
}
