<?php
require_once __DIR__ . '/../config/config.php';
$db = Database::getInstance();
$rows = $db->fetchAll("SELECT id, message_type, media_url, filename, message_id, created_at FROM conversations WHERE (message_type IN ('image','video','audio','document','sticker')) AND (local_file IS NULL OR local_file = '') AND (media_url IS NOT NULL AND media_url != '') ORDER BY created_at DESC LIMIT 200");
$inserted = 0;
foreach ($rows as $r) {
    $media = $r['media_url'];
    $data = ['conversation_id' => $r['id'], 'subdir' => date('Y/m'), 'status' => 'pending', 'created_at' => date('Y-m-d H:i:s')];
    if (preg_match('#^https?://#i', $media)) {
        $data['media_url'] = $media;
    } else {
        // assume media id
        $data['media_id'] = $media;
    }
    try {
        $db->insert('media_queue', $data);
        $inserted++;
    } catch (Exception $e) {
        // ignore duplicates
    }
}
echo "Inserted: $inserted jobs\n";