<?php

class RegistrationProgress
{
    public static function setStep(
        PDO $pdo,
        int $eventId,
        int $userId,
        string $step
    ): void {

        $tracker = new BehaviorTracker($pdo);

        // وضعیت فعلی
        $st = $pdo->prepare("
            SELECT current_step
            FROM event_registration_progress
            WHERE event_id = ?
            AND user_id = ?
            LIMIT 1
        ");

        $st->execute([$eventId, $userId]);

        $currentStep = $st->fetchColumn();

        // اولین ورود به Funnel
        if ($currentStep === false) {

            $st = $pdo->prepare("
                INSERT INTO event_registration_progress
                (
                    event_id,
                    user_id,
                    current_step
                )
                VALUES
                (
                    ?,
                    ?,
                    ?
                )
            ");

            $st->execute([
                $eventId,
                $userId,
                $step
            ]);

            $tracker->registrationStarted(
                $eventId,
                $userId
            );

            return;
        }

        // مرحله تغییری نکرده
        if ($currentStep === $step) {
            return;
        }

        // تغییر مرحله
        $st = $pdo->prepare("
            UPDATE event_registration_progress
            SET
                current_step = ?,
                reminder_count = 0,
                last_reminder_at = NULL,
                step_changed_at = NOW()
            WHERE event_id = ?
            AND user_id = ?
        ");

        $st->execute([
            $step,
            $eventId,
            $userId
        ]);

        $tracker->stepChanged(
            $eventId,
            $userId
        );
    }

    public static function complete(
        PDO $pdo,
        int $eventId,
        int $userId
    ): void {

        $st = $pdo->prepare("
            UPDATE event_registration_progress
            SET

                current_step='completed',

                completed_at=NOW(),

                reminder_count=0,

                last_reminder_at=NULL

            WHERE event_id=?
            AND user_id=?
        ");

        $st->execute([
            $eventId,
            $userId
        ]);

        $tracker = new BehaviorTracker($pdo);

        $tracker->registrationCompleted(
            $eventId,
            $userId
        );
    }
}