<?php
/**
 * admin/api_clean_projects.php
 * Backend AJAX untuk Manajemen Project Autokoding
 * Developer: Sikawarsito, S.Kom
 */
session_start();
include '../config/database.php';

header('Content-Type: application/json');
error_reporting(0);

// ===== PROTEKSI: Hanya Admin =====
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    echo json_encode(['success' => false, 'message' => 'Akses ditolak.']);
    exit;
}

$projects_dir = realpath(__DIR__ . '/../autokoding/projects');
if (!$projects_dir || !is_dir($projects_dir)) {
    echo json_encode(['success' => false, 'message' => 'Folder projects tidak ditemukan.']);
    exit;
}

// ===== HELPER: Hapus folder & semua isinya secara rekursif =====
function deleteFolder($path) {
    if (!is_dir($path)) return false;
    $items = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::CHILD_FIRST
    );
    foreach ($items as $item) {
        if ($item->isDir()) rmdir($item->getPathname());
        else unlink($item->getPathname());
    }
    return rmdir($path);
}

// ===== HELPER: Hitung ukuran folder =====
function getFolderSize($path) {
    $size = 0;
    $items = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS));
    foreach ($items as $item) {
        if ($item->isFile()) $size += $item->getSize();
    }
    return $size;
}

// ===== HELPER: Hitung jumlah file dalam folder =====
function countFiles($path) {
    $count = 0;
    $items = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS));
    foreach ($items as $item) {
        if ($item->isFile()) $count++;
    }
    return $count;
}

// ===== HELPER: Format ukuran =====
function formatSize($bytes) {
    if ($bytes >= 1048576) return round($bytes / 1048576, 2) . ' MB';
    if ($bytes >= 1024)    return round($bytes / 1024, 2) . ' KB';
    return $bytes . ' B';
}

// ===== PASTIKAN KOLOM JADWAL ADA DI SETTINGS (kompatibel semua versi MySQL) =====
function ensureCleanColumns($conn) {
    $cols = [];
    $r = mysqli_query($conn, "SHOW COLUMNS FROM settings");
    while ($row = mysqli_fetch_assoc($r)) $cols[] = $row['Field'];

    if (!in_array('auto_clean_days', $cols))
        mysqli_query($conn, "ALTER TABLE settings ADD COLUMN auto_clean_days INT DEFAULT 7");
    if (!in_array('auto_clean_enabled', $cols))
        mysqli_query($conn, "ALTER TABLE settings ADD COLUMN auto_clean_enabled TINYINT(1) DEFAULT 0");
    if (!in_array('auto_clean_last_run', $cols))
        mysqli_query($conn, "ALTER TABLE settings ADD COLUMN auto_clean_last_run DATETIME DEFAULT NULL");
}
ensureCleanColumns($conn);

$action = $_POST['action'] ?? $_GET['action'] ?? '';

// ===== ACTION: Ambil daftar semua project =====
if ($action === 'list') {
    $folders = glob($projects_dir . '/ses_*', GLOB_ONLYDIR);
    $result  = [];
    $total_size = 0;

    foreach ($folders as $folder) {
        $name    = basename($folder);
        $created = filemtime($folder);
        $age_days = floor((time() - $created) / 86400);
        $size    = getFolderSize($folder);
        $files   = countFiles($folder);
        $total_size += $size;

        // Badge warna berdasar umur
        if ($age_days < 3)       $badge = 'success';
        elseif ($age_days < 7)   $badge = 'warning';
        else                     $badge = 'danger';

        $result[] = [
            'name'     => $name,
            'created'  => date('d M Y H:i', $created),
            'age_days' => $age_days,
            'size'     => formatSize($size),
            'size_raw' => $size,
            'files'    => $files,
            'badge'    => $badge,
        ];
    }

    // Urutkan: terlama dulu
    usort($result, fn($a, $b) => $b['age_days'] - $a['age_days']);

    echo json_encode([
        'success'    => true,
        'projects'   => $result,
        'total'      => count($result),
        'total_size' => formatSize($total_size),
    ]);
    exit;
}

// ===== ACTION: Hapus satu folder =====
if ($action === 'delete_one') {
    $folder_name = basename($_POST['folder'] ?? '');
    if (!$folder_name || strpos($folder_name, 'ses_') !== 0) {
        echo json_encode(['success' => false, 'message' => 'Nama folder tidak valid.']);
        exit;
    }
    $target = $projects_dir . '/' . $folder_name;
    if (!is_dir($target)) {
        echo json_encode(['success' => false, 'message' => 'Folder tidak ditemukan.']);
        exit;
    }
    $ok = deleteFolder($target);
    echo json_encode(['success' => $ok, 'message' => $ok ? "Folder $folder_name berhasil dihapus." : "Gagal menghapus folder."]);
    exit;
}

// ===== ACTION: Hapus semua folder =====
if ($action === 'delete_all') {
    $folders  = glob($projects_dir . '/ses_*', GLOB_ONLYDIR);
    $deleted  = 0;
    $failed   = 0;
    foreach ($folders as $folder) {
        if (deleteFolder($folder)) $deleted++;
        else $failed++;
    }
    echo json_encode([
        'success' => true,
        'message' => "$deleted folder berhasil dihapus." . ($failed ? " $failed folder gagal." : ''),
        'deleted' => $deleted,
        'failed'  => $failed,
    ]);
    exit;
}

// ===== ACTION: Hapus folder lebih tua dari N hari =====
if ($action === 'delete_old') {
    $days    = max(1, (int)($_POST['days'] ?? 7));
    $folders = glob($projects_dir . '/ses_*', GLOB_ONLYDIR);
    $deleted = 0;
    $failed  = 0;
    $skipped = 0;
    $cutoff  = time() - ($days * 86400);

    foreach ($folders as $folder) {
        $created = filemtime($folder);
        if ($created <= $cutoff) {
            if (deleteFolder($folder)) $deleted++;
            else $failed++;
        } else {
            $skipped++;
        }
    }
    echo json_encode([
        'success' => true,
        'message' => "$deleted folder lama (>$days hari) dihapus. $skipped folder dipertahankan." . ($failed ? " $failed gagal." : ''),
        'deleted' => $deleted,
        'skipped' => $skipped,
    ]);
    exit;
}

// ===== ACTION: Simpan setting jadwal =====
if ($action === 'save_schedule') {
    $days    = max(1, (int)($_POST['days']    ?? 7));
    $enabled = (int)($_POST['enabled'] ?? 0);

    // Pastikan kolom sudah ada (sudah dipanggil di atas via ensureCleanColumns)
    $ok = mysqli_query($conn, "UPDATE settings SET auto_clean_days = $days, auto_clean_enabled = $enabled WHERE id = 1");
    $affected = mysqli_affected_rows($conn);

    if ($ok) {
        // Baca kembali untuk konfirmasi
        $check = mysqli_fetch_assoc(mysqli_query($conn, "SELECT auto_clean_days, auto_clean_enabled FROM settings WHERE id=1"));
        echo json_encode([
            'success'  => true,
            'message'  => 'Jadwal berhasil disimpan. Status: ' . ($check['auto_clean_enabled'] ? 'Aktif' : 'Nonaktif') . ', ' . $check['auto_clean_days'] . ' hari.',
            'enabled'  => (int)$check['auto_clean_enabled'],
            'days'     => (int)$check['auto_clean_days'],
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Gagal UPDATE: ' . mysqli_error($conn)]);
    }
    exit;
}

// ===== ACTION: Jalankan jadwal sekarang (trigger manual) =====
if ($action === 'run_schedule') {
    $cfg = mysqli_fetch_assoc(mysqli_query($conn, "SELECT auto_clean_days, auto_clean_enabled FROM settings WHERE id = 1"));
    $days    = max(1, (int)($cfg['auto_clean_days'] ?? 7));
    $folders = glob($projects_dir . '/ses_*', GLOB_ONLYDIR);
    $deleted = 0;
    $cutoff  = time() - ($days * 86400);

    foreach ($folders as $folder) {
        if (filemtime($folder) <= $cutoff) {
            if (deleteFolder($folder)) $deleted++;
        }
    }

    // Update waktu terakhir dijalankan
    mysqli_query($conn, "UPDATE settings SET auto_clean_last_run = NOW() WHERE id = 1");

    echo json_encode([
        'success' => true,
        'message' => "Jadwal dijalankan: $deleted folder dihapus (umur > $days hari).",
        'deleted' => $deleted,
    ]);
    exit;
}

// ===== ACTION: Cek & jalankan jadwal otomatis (dipanggil saat admin buka halaman) =====
if ($action === 'auto_check') {
    $cfg = mysqli_fetch_assoc(mysqli_query($conn, "SELECT auto_clean_days, auto_clean_enabled, auto_clean_last_run FROM settings WHERE id = 1"));

    if (empty($cfg['auto_clean_enabled'])) {
        echo json_encode(['success' => true, 'triggered' => false, 'message' => 'Jadwal tidak aktif.']);
        exit;
    }

    $last_run = $cfg['auto_clean_last_run'] ? strtotime($cfg['auto_clean_last_run']) : 0;
    $next_run = $last_run + 86400; // Jalankan max 1x per hari

    if (time() < $next_run) {
        $next_str = date('d M Y H:i', $next_run);
        echo json_encode(['success' => true, 'triggered' => false, 'message' => "Jadwal berikutnya: $next_str"]);
        exit;
    }

    // Saatnya bersih-bersih!
    $days    = max(1, (int)($cfg['auto_clean_days'] ?? 7));
    $folders = glob($projects_dir . '/ses_*', GLOB_ONLYDIR);
    $deleted = 0;
    $cutoff  = time() - ($days * 86400);

    foreach ($folders as $folder) {
        if (filemtime($folder) <= $cutoff) {
            if (deleteFolder($folder)) $deleted++;
        }
    }

    mysqli_query($conn, "UPDATE settings SET auto_clean_last_run = NOW() WHERE id = 1");

    echo json_encode([
        'success'   => true,
        'triggered' => true,
        'message'   => "Auto-clean dijalankan: $deleted folder dihapus (umur > $days hari).",
        'deleted'   => $deleted,
    ]);
    exit;
}

echo json_encode(['success' => false, 'message' => 'Action tidak dikenal.']);
?>
