<?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();
        $filters = [
            'billing_month' => Sanitizer::sanitize($_POST['billing_month'] ?? $_GET['billing_month'] ?? ''),
            'status' => Sanitizer::sanitize($_POST['status'] ?? $_GET['status'] ?? ''),
            'salesperson_name' => Sanitizer::sanitize($_POST['salesperson_name'] ?? $_GET['salesperson_name'] ?? ''),
            'amount_min' => $_POST['amount_min'] ?? $_GET['amount_min'] ?? '',
            'amount_max' => $_POST['amount_max'] ?? $_GET['amount_max'] ?? '',
        ];
        $rows = $this->payrollService->getManagerQueueAdvanced($filters, 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);
        }
    }
}
