<?php

namespace App\Services;

use App\Core\Database;

class ReviewReminderService
{
    public static function sendReminders(): void
    {
        $db =
            Database::getInstance();

        /*
        Find overdue assignments
        */

        $stmt =
            $db->prepare("
                SELECT
                    ra.id,
                    ra.submission_id,
                    ra.reviewer_id,
                    ra.due_date,
                    u.email,
                    s.title
                FROM review_assignments ra
                JOIN users u
                    ON u.id = ra.reviewer_id
                JOIN submissions s
                    ON s.id = ra.submission_id
                WHERE ra.status = 'assigned'
                AND ra.due_date IS NOT NULL
                AND ra.due_date < CURDATE()
            ");

        $stmt->execute();

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

        foreach ($rows as $r) {

            self::logReminder(

                (int)$r['id'],

                (int)$r['reviewer_id']

            );

            error_log(
                "REMINDER SENT: assignment="
                . $r['id']
            );

        }

        error_log(
            "REMINDER JOB COMPLETE: "
            . count($rows)
        );
    }

    private static function logReminder(
        int $assignmentId,
        int $reviewerId
    ): void
    {
        $db =
            Database::getInstance();

        $db->prepare("
            INSERT INTO notifications
            (
                user_id,
                title,
                message,
                created_at
            )
            VALUES
            (?, ?, ?, NOW())
        ")
        ->execute([

            $reviewerId,

            "Review Reminder",

            "You have an overdue review assignment."

        ]);
    }
}
