<?php
namespace App\Controllers;

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

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

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

    public function getRules()
    {
        $selfOnly = (($_SESSION['role'] ?? '') === 'agent') && !$this->authService->isAdminOrCrmSpecialist();
        if (!$selfOnly) {
            $this->assertAdminOrCrm();
        }
        $rules = array_map(function ($rule) use ($selfOnly) {
            $payload = $rule->toArray();
            if ($selfOnly) {
                $payload['target_users'] = [];
            }
            return $payload;
        }, $this->commissionService->getRules());
        $this->successResponse(['rules' => $rules]);
    }

    public function getMyLedger()
    {
        if (!$this->authService->isAuthenticated()) {
            $this->errorResponse('دسترسی محدود', 403);
        }
        $userId = (int)($_SESSION['user_id'] ?? 0);
        if ($userId <= 0) {
            $this->errorResponse('کاربر معتبر نیست', 422);
        }
        $rows = array_map(static function ($row) {
            return $row->toArray();
        }, $this->commissionService->getUserLedger($userId));
        $this->successResponse(['ledger' => $rows]);
    }

    public function storeRule()
    {
        $this->assertAdminOrCrm();

        $targetUsers = $_POST['target_users'] ?? '[]';
        $payload = [
            'id' => (int)($_POST['id'] ?? 0),
            'title' => Sanitizer::sanitize($_POST['title'] ?? ''),
            'kpi_source' => Sanitizer::sanitize($_POST['kpi_source'] ?? ''),
            'target_users' => $targetUsers,
            'requested_services' => $_POST['requested_services'] ?? '[]',
            'kpi_min_threshold' => (float)($_POST['kpi_min_threshold'] ?? 0),
            'kpi_max_threshold' => (float)($_POST['kpi_max_threshold'] ?? 0),
            'base_amount' => (float)($_POST['base_amount'] ?? 0),
            'reward_percentage' => (float)($_POST['reward_percentage'] ?? 0),
            'status' => Sanitizer::sanitize($_POST['status'] ?? 'active'),
            'tiers' => $_POST['tiers'] ?? '[]',
        ];

        if ($payload['kpi_max_threshold'] <= $payload['kpi_min_threshold']) {
            $this->errorResponse('حداکثر آستانه باید از حداقل بزرگ‌تر باشد', 422);
        }
        if ($payload['reward_percentage'] <= 0 || $payload['reward_percentage'] > 100) {
            $this->errorResponse('درصد پاداش باید بین 1 تا 100 باشد', 422);
        }

        $id = $this->commissionService->saveRule($payload);
        $this->successResponse(['id' => $id], 'قانون کمیسیون ذخیره شد');
    }

    public function evaluate()
    {
        $this->assertAdminOrCrm();

        $userId = (int)($_POST['user_id'] ?? 0);
        $kpiScore = (float)($_POST['kpi_score'] ?? 0);
        $kpiSource = Sanitizer::sanitize($_POST['kpi_source'] ?? '');
        if ($userId <= 0 || $kpiSource === '') {
            $this->errorResponse('کاربر، منبع KPI و امتیاز الزامی هستند', 422);
        }

        $result = $this->commissionService->evaluateUserCommissions($userId, $kpiScore, $kpiSource);
        $this->successResponse(['results' => $result]);
    }

    public function getSetupData()
    {
        $selfOnly = (($_SESSION['role'] ?? '') === 'agent') && !$this->authService->isAdminOrCrmSpecialist();
        if (!$selfOnly) {
            $this->assertAdminOrCrm();
        }
        $allUsers = $this->userRepo->getAll();
        if ($selfOnly) {
            $currentId = (int)($_SESSION['user_id'] ?? 0);
            $allUsers = array_values(array_filter($allUsers, static function ($u) use ($currentId) {
                return (int)($u->id ?? 0) === $currentId;
            }));
        }
        $users = array_map(static function ($user) {
            return [
                'id' => (int)$user->id,
                'display_name' => trim((string)($user->display_name ?: ($user->first_name . ' ' . $user->last_name))),
                'is_active' => (int)$user->is_active,
                'role' => (string)$user->role,
            ];
        }, $allUsers);

        $this->successResponse([
            'users' => $users,
            'kpi_sources' => ['kpi_calls', 'kpi_meetings', 'kpi_sales_volume', 'kpi_followups'],
        ]);
    }

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