<?php
namespace App\Controllers;

use App\Services\AuthService;
use App\Services\PayrollIntegrationService;
use App\Utils\Sanitizer;

class PayrollController extends ApiController
{
    private $payrollService;
    private $authService;

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

    public function aggregateMonthlyPayouts()
    {
        $this->assertManagerAccess();
        $billingMonth = Sanitizer::sanitize($_POST['billing_month'] ?? date('Y-m'));
        $payrollDay = (int)($_POST['payroll_day'] ?? 30);
        $managerId = (int)($_SESSION['user_id'] ?? 0);
        $rows = $this->payrollService->aggregateMonthlySettledCommissions($billingMonth, $managerId, $payrollDay);
        $this->successResponse(['cycles' => $rows], 'چرخه‌های پورسانت ایجاد/به‌روزرسانی شد');
    }

    public function getPayoutQueue()
    {
        $this->assertManagerAccess();
        $billingMonth = Sanitizer::sanitize($_POST['billing_month'] ?? $_GET['billing_month'] ?? '');
        $rows = $this->payrollService->getManagerQueue($billingMonth, true);
        $this->successResponse(['cycles' => $rows]);
    }

    public function decidePayout()
    {
        $this->assertManagerAccess();
        $cycleId = (int)($_POST['cycle_id'] ?? 0);
        $action = Sanitizer::sanitize($_POST['action'] ?? '');
        $reason = trim((string)($_POST['override_reason'] ?? $_POST['reason'] ?? ''));
        $overrideAmountRaw = $_POST['override_amount'] ?? null;
        $overrideAmount = ($overrideAmountRaw === null || $overrideAmountRaw === '') ? null : (float)$overrideAmountRaw;
        $managerId = (int)($_SESSION['user_id'] ?? 0);

        $cycle = $this->payrollService->decidePayoutCycle($cycleId, $action, $managerId, $overrideAmount, $reason);
        $this->successResponse(['cycle' => $cycle->toArray()], 'وضعیت چرخه با موفقیت ثبت شد');
    }

    private function assertManagerAccess(): void
    {
        $role = trim((string)($_SESSION['role'] ?? ''));
        if (!in_array($role, ['admin', 'system'], true)) {
            $this->errorResponse('دسترسی محدود', 403);
        }
    }
}
