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

$rows = all_rows("SELECT * FROM mj_listings WHERE expires_at IS NOT NULL AND expires_at<NOW() AND status NOT IN ('expired','deleted') LIMIT 500");
foreach ($rows as $r) {
    q('UPDATE mj_listings SET status="expired", expired_at=NOW() WHERE id=?', [(int)$r['id']]);
    mj_listing_log((int)$r['id'], 'cron_expired_listing', $r, []);
    mj_listing_send_expiry_notification($r, 0, true);
    mj_create_admin_alert([
        'alert_key'=>'listing_expired_'.(int)$r['id'].'_'.date('Ymd'),
        'alert_type'=>'listing_expired',
        'module_name'=>'listings',
        'priority'=>'normal',
        'title'=>'Listing expired',
        'message'=>'Listing expired: '.($r['title']??''),
        'action_url'=>'listing-edit.php?id='.(int)$r['id'],
        'action_label'=>'View',
        'related_type'=>'listing',
        'related_id'=>(int)$r['id']
    ]);
}
echo "Expired listings processed: ".count($rows);
