<?php

declare(strict_types=1);

class BehaviorTracker
{
    private PDO $pdo;


    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }


    /**
     * شروع ثبت نام کاربر
     */
public function registrationStarted(
    int $eventId,
    int $userId
): void {

    $this->logEvent(
        $eventId,
        $userId,
        BehaviorEvents::REGISTRATION_STARTED
    );

    $this->updateProgress(
        $eventId,
        $userId,
        [
            'step_changed_at' => date('Y-m-d H:i:s'),
            'total_step_changes' => 1,
        ]
    );
}


    /**
     * تغییر مرحله ثبت نام
     */
    public function stepChanged(
        int $eventId,
        int $userId
    ): void {

        $now = date('Y-m-d H:i:s');

        $this->updateProgress(
            $eventId,
            $userId,
            [
                'total_step_changes'=>[
                    'increment'=>true
                ],

                'step_changed_at'=>$now,

                'last_activity_at'=>$now
            ]
        );
    }



    /**
     * ارسال Reminder
     */
    public function reminderSent(
        int $eventId,
        int $userId,
        ReminderDecision $decision,
        array $progress
    ): void
    {
        $this->updateProgress(
            $eventId,
            $userId,
            [
                'reminder_count' => [
                    'increment' => true
                ],

                'last_reminder_at' => date('Y-m-d H:i:s')
            ]
        );

        $historyId = $this->insertReminderHistory(
            $eventId,
            $userId,
            $decision,
            $progress
        );


        $this->updateProgress(
            $eventId,
            $userId,
            [
                'reminder_count'=>[
                    'increment'=>true
                ],

                'last_reminder_at'=>date('Y-m-d H:i:s'),

                'last_reminder_id'=>$historyId
            ]
        );
    }



    /**
     * کلیک روی دکمه Reminder
     */
    public function reminderClicked(
        int $eventId,
        int $userId
    ): void {


        $now = date('Y-m-d H:i:s');


        $this->updateProgress(
            $eventId,
            $userId,
            [

                'last_cta_click_at'=>$now,

                'last_activity_at'=>$now

            ]
        );



        $st=$this->pdo->prepare("
            UPDATE reminder_history

            SET

                clicked_at=?,

                result='clicked'

            WHERE

                event_id=?

            AND user_id=?

            AND result='pending'

            ORDER BY id DESC

            LIMIT 1
        ");


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

    }



    /**
     * تکمیل ثبت نام
     */
    public function registrationCompleted(
        int $eventId,
        int $userId
    ): void {


        $this->updateProgress(
            $eventId,
            $userId,
            [

                'completed_at'=>date('Y-m-d H:i:s'),

                'step_changed_at'=>date('Y-m-d H:i:s'),

                'successful_reminders'=>[
                    'increment'=>true
                ]

            ]
        );

    }



    /**
     * کاربر بدون تکمیل رها کرده
     */
    public function registrationIgnored(
        int $eventId,
        int $userId
    ): void {


        $this->updateProgress(
            $eventId,
            $userId,
            [

                'ignored_reminders'=>[
                    'increment'=>true
                ]

            ]
        );

    }




    /**
     * متد مرکزی آپدیت
     */
    private function updateProgress(
        int $eventId,
        int $userId,
        array $data
    ): void {


        $fields = [];
        $values = [];


        foreach ($data as $column=>$value){


            if(is_array($value) && isset($value['increment'])){


                $fields[] =
                    "{$column} = {$column} + 1";


                continue;
            }



            $fields[] = "{$column} = ?";

            $values[] = $value;

        }



        $values[] = $eventId;
        $values[] = $userId;



        $sql="
            UPDATE event_registration_progress

            SET
                ".implode(",", $fields)."

            WHERE event_id=?
            AND user_id=?
        ";



        $stmt=$this->pdo->prepare($sql);

        $stmt->execute($values);

    }

    private function insertReminderHistory(
        int $eventId,
        int $userId,
        ReminderDecision $decision,
        array $progress
    ): int {


        $st = $this->pdo->prepare("
            INSERT INTO reminder_history
            (
                event_id,
                user_id,
                reminder_no,
                level,
                score,
                next_delay,
                reasons,
                score_breakdown,
                current_step,
                sent_at,
                result
            )

            VALUES
            (
                :event_id,
                :user_id,
                :reminder_no,
                :level,
                :score,
                :next_delay,
                :reasons,
                :score_breakdown,
                :current_step,
                NOW(),
                'pending'
            )
        ");



        $st->execute([

            'event_id'=>$eventId,

            'user_id'=>$userId,

            'reminder_no'=>
                ((int)$progress['reminder_count']) + 1,

            'level'=>$decision->level,

            'score'=>$decision->score,

            'next_delay'=>$decision->nextDelay,


            'reasons'=>json_encode(
                $decision->reasons,
                JSON_UNESCAPED_UNICODE
            ),


            'score_breakdown'=>json_encode(
                $decision->scores,
                JSON_UNESCAPED_UNICODE
            ),


            'current_step'=>$progress['current_step']

        ]);



        return (int)$this->pdo->lastInsertId();

    }

        private function logEvent(
        int $eventId,
        int $userId,
        string $type,
        ?string $value = null,
        array $meta = []
    ): void {

        $st = $this->pdo->prepare("
            INSERT INTO event_behavior_logs
            (
                event_id,
                user_id,
                event_type,
                event_value,
                meta
            )
            VALUES
            (
                ?, ?, ?, ?, ?
            )
        ");

        $st->execute([
            $eventId,
            $userId,
            $type,
            $value,
            empty($meta)
                ? null
                : json_encode($meta, JSON_UNESCAPED_UNICODE)
        ]);
    }


}