<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\Database;
use App\Modules\Notifications\Services\SmsService;

class InstallmentReminderJob
{
    private Database $db;
    public function __construct(Database $db) { $this->db = $db; }
    public function shouldRun(): bool { return true; }

    public function run(): array
    {
        $reminderDate = date('Y-m-d', strtotime('+7 days'));
        $upcoming = $this->db->select(
            "SELECT s.installment_number, s.amount, s.due_date, p.member_id,
                    m.full_name_ar, m.phone_mobile
             FROM installment_schedule s
             JOIN installment_plans p ON p.id = s.installment_plan_id
             JOIN members m ON m.id = p.member_id
             WHERE p.status = 'active' AND s.status = 'pending' AND s.due_date = ?
             AND m.phone_mobile IS NOT NULL",
            [$reminderDate]
        );

        $processed = 0;
        foreach ($upcoming as $item) {
            SmsService::sendFromTemplate('INSTALLMENT_REMINDER', $item['phone_mobile'], [
                'member_name'        => $item['full_name_ar'],
                'installment_number' => $item['installment_number'],
                'amount'             => number_format((float) $item['amount'], 2),
                'due_date'           => $item['due_date'],
            ], (int) $item['member_id']);
            $processed++;
        }
        return ['processed' => $processed];
    }
}