<?php
declare(strict_types=1);

namespace App\Modules\AcademyContracts\Services;

use App\Core\App;
use App\Core\EventBus;
use App\Modules\AcademyContracts\Models\AcademyContract;

final class AcademyContractService
{
    /**
     * Activate a contract (set status to 'active', record approver).
     */
    public static function activate(int $contractId, int $approvedBy): void
    {
        $contract = AcademyContract::findOrFail($contractId);

        $contract->update([
            'status'      => 'active',
            'approved_by' => $approvedBy,
            'approved_at' => date('Y-m-d H:i:s'),
        ]);

        EventBus::dispatch('academy.contract.activated', [
            'contract_id' => $contractId,
            'approved_by' => $approvedBy,
        ]);
    }

    /**
     * Terminate a contract.
     */
    public static function terminate(int $contractId, int $terminatedBy, string $reason): void
    {
        $contract = AcademyContract::findOrFail($contractId);

        $contract->update([
            'status'             => 'terminated',
            'terminated_by'      => $terminatedBy,
            'terminated_at'      => date('Y-m-d H:i:s'),
            'termination_reason' => $reason,
        ]);

        EventBus::dispatch('academy.contract.terminated', [
            'contract_id'   => $contractId,
            'terminated_by' => $terminatedBy,
            'reason'        => $reason,
        ]);
    }

    /**
     * Generate a unique contract number in the format AC-YYYY-XXXX.
     */
    public static function generateContractNumber(): string
    {
        $db = App::getInstance()->db();
        $year = date('Y');
        $prefix = 'AC-' . $year . '-';

        $lastRow = $db->selectOne(
            "SELECT contract_number FROM academy_contracts
             WHERE contract_number LIKE ?
             ORDER BY contract_number DESC LIMIT 1",
            [$prefix . '%']
        );

        if ($lastRow) {
            $lastSeq = (int) substr($lastRow['contract_number'], strlen($prefix));
            $nextSeq = $lastSeq + 1;
        } else {
            $nextSeq = 1;
        }

        return $prefix . str_pad((string) $nextSeq, 4, '0', STR_PAD_LEFT);
    }
}
