<?php
require_once __DIR__.'/../includes/functions.php';
mj_ensure_listing_module_schema(true);
mj_user_limits_ensure_schema();

if (setting('listing_expiry_notify_enabled','1') !== '1') {
    echo "Listing expiry notification disabled.";
    exit;
}

$daysList = mj_listing_expiry_notify_days();
$total = 0;

// Expiring soon / today
foreach ($daysList as $days) {
    if ($days <= 0) { continue; }
    $rows = all_rows("SELECT * FROM mj_listings
        WHERE expires_at IS NOT NULL
        AND DATE(expires_at)=DATE(DATE_ADD(NOW(), INTERVAL ? DAY))
        AND status IN ('active','approved','published')
        LIMIT 500", [$days]);

    foreach ($rows as $r) {
        mj_listing_send_expiry_notification($r, $days, false);
        $total++;
    }
}

// Expired today/already expired and active statuses
$expiredRows = all_rows("SELECT * FROM mj_listings
    WHERE expires_at IS NOT NULL
    AND expires_at < NOW()
    AND status IN ('active','approved','published','expired')
    LIMIT 500");

foreach ($expiredRows as $r) {
    mj_listing_send_expiry_notification($r, 0, true);
    $total++;
}

echo "Listing expiry user notifications queued: ".$total;
