<?php

declare(strict_types=1);


class ReminderAnalyzerJob extends Job
{

    public function getName(): string
    {
        return 'ReminderAnalyzerJob';
    }



    public function handle(): void
    {


        $st = $this->pdo->prepare("
            SELECT *
            FROM reminder_history
            WHERE result='pending'
            AND sent_at < NOW() - INTERVAL 6 HOUR
            LIMIT 500
        ");


        $st->execute();


        $rows = $st->fetchAll(PDO::FETCH_ASSOC);



        foreach($rows as $row){


            $this->analyze($row);


        }


    }



    private function analyze(array $row): void
    {


        $st = $this->pdo->prepare("
            SELECT *
            FROM event_registration_progress
            WHERE event_id=?
            AND user_id=?
        ");


        $st->execute([
            $row['event_id'],
            $row['user_id']
        ]);


        $progress=$st->fetch(PDO::FETCH_ASSOC);



        if(!$progress){
            return;
        }



        /*
         * کاربر بعد Reminder کاری کرده
         */

        if(
            strtotime($progress['last_activity_at'] ?? '0')
            >
            strtotime($row['sent_at'])
        ){

            $this->mark(
                $row['id'],
                'clicked'
            );

            return;

        }



        /*
         * هیچ واکنشی نداشته
         */

        $this->pdo->prepare("
            UPDATE event_registration_progress
            SET
                ignored_reminders = ignored_reminders + 1,

                fatigue_score =
                    LEAST(100,fatigue_score + 15)

            WHERE
                event_id=?
                AND user_id=?
        ")
        ->execute([
            $row['event_id'],
            $row['user_id']
        ]);



        $this->mark(
            $row['id'],
            'ignored'
        );

    }



    private function mark(
        int $id,
        string $result
    ):void{


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

            SET
            result=?,
            analyzed_at=NOW()

            WHERE id=?
        ");


        $st->execute([
            $result,
            $id
        ]);

    }

}