<?php
// Simple maintenance script for installment plans: send upcoming payment reminders
// and mark missed installments, suspending user accounts when necessary.

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/helpers/notification.php';

$db = Database::getInstance();

// 1. Send reminders exactly 3, 2, and 1 days before each due installment.
// We use reminder_sent_at as the last reminder timestamp, so each installment
// gets at most one reminder per day.
$upcoming = $db->getAll(
    "SELECT ei.id
     FROM enrollment_installments ei
     WHERE ei.status = 'pending'
       AND DATEDIFF(ei.due_date, NOW()) IN (1, 2, 3)
       AND (ei.reminder_sent_at IS NULL OR DATE(ei.reminder_sent_at) <> CURDATE())",
    []
);

foreach ($upcoming as $row) {
    $installmentId = (int)$row['id'];
    sendInstallmentReminder($installmentId);
    $db->update('enrollment_installments', [
        'reminder_sent_at' => formatDate(),
    ], 'id = ?', [$installmentId]);
}

// 2. Mark missed installments and suspend associated users
$overdue = $db->getAll(
    "SELECT ei.id AS installment_id, ei.enrollment_id, ce.student_id, u.status AS user_status
     FROM enrollment_installments ei
     JOIN course_enrollments ce ON ei.enrollment_id = ce.id
     JOIN users u ON ce.student_id = u.id
     WHERE ei.status = 'pending' AND ei.due_date < NOW()",
    []
);

foreach ($overdue as $row) {
    $installmentId = (int)$row['installment_id'];
    $enrollmentId = (int)$row['enrollment_id'];
    $studentId = (int)$row['student_id'];

    $db->update('enrollment_installments', [
        'status' => 'missed',
    ], 'id = ?', [$installmentId]);

    if ($row['user_status'] !== 'suspended') {
        $db->update('users', [
            'status' => 'suspended',
        ], 'id = ?', [$studentId]);
    }
}

echo json_encode(['success' => true, 'message' => 'Installment maintenance completed']);
