<?php
set_time_limit(0);

require_once __DIR__ . '/../../config.php';

/*
|--------------------------------------------------------------------------
| GLOBAL AYARLAR
|--------------------------------------------------------------------------
*/
$DRY_RUN = false; // false => SİLER

// Hangi temizlikler çalışsın?
$CLEAN_SEND    = true;
$CLEAN_AVATAR  = true;

/*
|--------------------------------------------------------------------------
| PATHLER
|--------------------------------------------------------------------------
*/
$SEND_DIR      = '/home/heysen/public_html/app.heysen.net/assets/upload/send';
$AVATAR_DIR    = '/home/heysen/public_html/app.heysen.net/assets/upload/avatar';
$GO_AVATAR_DIR = '/home/heysen/public_html/app.heysen.net/assets/upload/go_avatar';

$DEFAULT_AVATAR = 'assets/img/no-avatar.png';

/*
|--------------------------------------------------------------------------
| YARDIMCI
|--------------------------------------------------------------------------
*/
function scanFiles($dir) {
    return array_diff(scandir($dir), ['.', '..']);
}

function hr($title) {
    echo "<hr><h2>{$title}</h2>";
}

/*
|--------------------------------------------------------------------------
| 1️⃣ SEND TEMİZLİĞİ
|--------------------------------------------------------------------------
*/
if ($CLEAN_SEND) {

    hr("SEND TEMİZLİĞİ");

    $fsFiles = scanFiles($SEND_DIR);
    $fsSet = array_flip($fsFiles);

    // DB’de kullanılan send dosyaları
    $used = [];

    $stmt = $db->query("
        SELECT icerik
        FROM mesajlar
        WHERE icerik LIKE '%/assets/upload/send/%'
    ");

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        preg_match_all('#/assets/upload/send/([^"\s]+)#', $row['icerik'], $m);
        foreach ($m[1] as $raw) {
            $file = basename(preg_split('/[?#]/', $raw, 2)[0]);
            if (isset($fsSet[$file])) {
                $used[$file] = true;
            }
        }
    }

    $usedCount   = count($used);
    $orphanCount = count($fsFiles) - $usedCount;

    echo "<ul>";
    echo "<li>Filesystem toplam: " . count($fsFiles) . "</li>";
    echo "<li>DB’de kullanılan: {$usedCount}</li>";
    echo "<li>SİLİNECEK: {$orphanCount}</li>";
    echo "</ul>";

    if (!$DRY_RUN) {
        foreach ($fsFiles as $f) {
            if (!isset($used[$f])) {
                @unlink($SEND_DIR . '/' . $f);
            }
        }
        echo "<p>✅ {$orphanCount} send dosyası silindi.</p>";
    } else {
        echo "<p><strong>TEST MODU:</strong> send silinmedi.</p>";
    }
}

/*
|--------------------------------------------------------------------------
| 2️⃣ AVATAR + GO_AVATAR TEMİZLİĞİ
|--------------------------------------------------------------------------
*/
if ($CLEAN_AVATAR) {

    hr("AVATAR TEMİZLİĞİ");

    $fsAvatars   = scanFiles($AVATAR_DIR);
    $fsGoAvatars = scanFiles($GO_AVATAR_DIR);

    $fsSet = [];
    foreach ($fsAvatars as $f)   $fsSet[$f] = true;
    foreach ($fsGoAvatars as $f) $fsSet[$f] = true;

    $totalFs = count($fsAvatars) + count($fsGoAvatars);

    // Aktif + bot olmayan kullanıcı avatarları
    $active = [];

    $stmt = $db->query("
        SELECT user_picture
        FROM kullanicilar
        WHERE user_picture IS NOT NULL
          AND user_picture != ''
          AND user_picture != '{$DEFAULT_AVATAR}'
          AND user_deaktif = 0
          AND user_ban = 0
          AND user_bot = 0
    ");

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $file = basename(trim($row['user_picture']));
        if (isset($fsSet[$file])) {
            $active[$file] = true;
        }
    }

    $activeCount = count($active);
    $orphanCount = $totalFs - $activeCount;

    echo "<ul>";
    echo "<li>Filesystem toplam: {$totalFs}</li>";
    echo "<li>Aktif (korunan): {$activeCount}</li>";
    echo "<li>SİLİNECEK: {$orphanCount}</li>";
    echo "</ul>";

    if (!$DRY_RUN) {
        foreach ($fsAvatars as $f) {
            if (!isset($active[$f])) {
                @unlink($AVATAR_DIR . '/' . $f);
            }
        }
        foreach ($fsGoAvatars as $f) {
            if (!isset($active[$f])) {
                @unlink($GO_AVATAR_DIR . '/' . $f);
            }
        }
        echo "<p>✅ {$orphanCount} avatar silindi.</p>";
    } else {
        echo "<p><strong>TEST MODU:</strong> avatarlar silinmedi.</p>";
    }
}

/*
|--------------------------------------------------------------------------
| BİTİŞ
|--------------------------------------------------------------------------
*/
echo "<hr><p><strong>İşlem tamamlandı.</strong></p>";
