<?php

class OpportunityStageHistoryService
{
    public static function record(PDO $pdo, int $opportunityId, ?string $fromStage, string $toStage, ?int $userId, string $userName, string $source = 'system'): void
    {
        if ($opportunityId <= 0 || $toStage === '' || $fromStage === $toStage) return;
        $allowedSources = array('kanban','form','close','reopen','system');
        if (!in_array($source, $allowedSources, true)) $source = 'system';

        $stmt = $pdo->prepare("\n            INSERT INTO crm_opportunity_stage_history\n                (opportunity_id, from_stage, to_stage, changed_by_user_id, changed_by_name, change_source, changed_at)\n            VALUES (?, ?, ?, ?, ?, ?, NOW())\n        ");
        $stmt->execute(array($opportunityId, $fromStage, $toStage, $userId ?: null, $userName, $source));
    }

    public static function lifecycle(PDO $pdo, int $opportunityId, string $action, array $before, array $after, ?int $userId, string $userName, string $source): void
    {
        $stmt = $pdo->prepare("\n            INSERT INTO crm_opportunity_lifecycle_history\n                (opportunity_id, action_key, source_key, actor_user_id, actor_name, before_json, after_json, created_at)\n            VALUES (?, ?, ?, ?, ?, ?, ?, NOW())\n        ");
        $stmt->execute(array(
            $opportunityId,
            $action,
            $source,
            $userId ?: null,
            $userName,
            json_encode($before, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            json_encode($after, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        ));
    }
}
