<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';

requireRole('branch_admin'); 
$pageTitle = 'Cron Job Manager';
$db = db();

require_once __DIR__ . '/../cron/cron_registry.php';

$logDir = __DIR__ . '/../cron/logs';
if (!is_dir($logDir)) mkdir($logDir, 0755, true);

// Handle Force Run (Jalankan Manual)
if (isset($_GET['run']) && verifyCsrf($_GET['token'] ?? '')) {
    $slug = $_GET['run'];
    if (isset($cronRegistry[$slug])) {
        $cron = $cronRegistry[$slug];
        $logFile = $logDir . '/' . $slug . '_manual_' . date('Y-m-d_His') . '.log';
        
        ob_start();
echo "=== Manual Run: {$cron['name']} | " . date('Y-m-d H:i:s') . " ===\n";
try {
    // ✅ TANDAI bahwa ini eksekusi dari cron_manager (bypass proteksi CLI)
    $GLOBALS['CRON_MANAGER_EXEC'] = true;
    include $cron['file'];
    unset($GLOBALS['CRON_MANAGER_EXEC']);
        } catch (\Throwable $e) {
            echo "ERROR: " . $e->getMessage() . "\n";
        }
        echo "=== Finished ===\n";
        $output = ob_get_clean();
        
        file_put_contents($logFile, $output);
        
        // Hapus lock hari ini agar cron_runner bisa jalan lagi di jadwal berikutnya
        $today = date('Y-m-d');
        $lockFile = $logDir . '/' . $slug . '_' . $today . '.lock';
        if (file_exists($lockFile)) unlink($lockFile);
        
        // ✅ DIPERBAIKI: Ubah /admin/ menjadi /branch/
        redirect('/branch/cron_manager.php', "✅ <strong>{$cron['name']}</strong> berhasil dijalankan manual!", 'success');
    }
}

// Handle Reset Lock
if (isset($_GET['reset']) && verifyCsrf($_GET['token'] ?? '')) {
    $slug = $_GET['reset'];
    $today = date('Y-m-d');
    $lockFile = $logDir . '/' . $slug . '_' . $today . '.lock';
    if (file_exists($lockFile)) unlink($lockFile);
    
    // ✅ DIPERBAIKI: Ubah /admin/ menjadi /branch/
    redirect('/branch/cron_manager.php', "✅ Status cron <strong>$slug</strong> direset.", 'success');
}

// Ambil status cron
$cronStatus = [];
foreach ($cronRegistry as $slug => $cron) {
    $today = date('Y-m-d');
    $lockFile = $logDir . '/' . $slug . '_' . $today . '.lock';
    $lastRun = file_exists($lockFile) ? filemtime($lockFile) : false;
    
    $cronStatus[$slug] = [
        'last_run' => $lastRun,
        'status' => $lastRun ? 'success' : 'waiting'
    ];
}

// Generate perintah cPanel (Pastikan path ini sesuai dengan server Anda)
$publicHtmlPath = realpath(__DIR__ . '/..');
$cpanelCommand = "* * * * * /usr/local/bin/php {$publicHtmlPath}/cron/cron_runner.php >> {$publicHtmlPath}/cron/logs/cron_runner.log 2>&1";

require __DIR__ . '/../includes/header.php';
require __DIR__ . '/../includes/sidebar.php';
?>

<style>
.navbar-modern { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); padding: 15px 20px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 2px 10px rgba(0,0,0,0.1); position: sticky; top: 0; z-index: 1000; }
.navbar-left { display: flex; align-items: center; gap: 15px; }
.burger-btn { background: rgba(255,255,255,0.15); border: none; color: white; width: 40px; height: 40px; border-radius: 10px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 1.3rem; }
.navbar-title { color: white; font-size: 1.2rem; font-weight: 700; margin: 0; }
.navbar-subtitle { color: rgba(255,255,255,0.85); font-size: 0.78rem; margin: 0; }
.main-content { padding: 20px; max-width: 1200px; margin: 0 auto; }
.page-header { margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px; }
.page-title { font-size: 1.6rem; font-weight: 700; color: #003D7A; margin: 0; display: flex; align-items: center; gap: 10px; }
.page-title i { font-size: 1.8rem; color: #0066CC; }
.alert-modern { padding: 14px 18px; border-radius: 12px; margin-bottom: 16px; display: flex; align-items: flex-start; gap: 12px; font-size: 0.9rem; border: 2px solid; }
.alert-modern.success { background: #e8f5e9; border-color: #a5d6a7; color: #2e7d32; }
.alert-modern.info { background: #e3f2fd; border-color: #90caf9; color: #1565c0; }
.card-modern { background: white; border-radius: 16px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); overflow: hidden; margin-bottom: 20px; }
.card-header-modern { color: white; padding: 16px 20px; font-size: 1rem; font-weight: 600; display: flex; align-items: center; justify-content: space-between; gap: 10px; }
.card-header-modern.primary { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.card-header-modern.success { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.card-header-modern .title-left { display: flex; align-items: center; gap: 10px; }
.card-body-modern { padding: 20px; }
.cron-item { border: 2px solid #f0f0f0; border-radius: 12px; padding: 16px; margin-bottom: 12px; transition: all 0.3s ease; display: flex; align-items: center; gap: 16px; }
.cron-item:hover { border-color: #0066CC; background: #f8fafc; }
.cron-icon { width: 50px; height: 50px; border-radius: 12px; background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%); color: #0066CC; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; flex-shrink: 0; }
.cron-info { flex: 1; }
.cron-title { font-weight: 700; color: #003D7A; font-size: 1rem; margin-bottom: 4px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.cron-desc { font-size: 0.82rem; color: #666; margin-bottom: 6px; }
.cron-meta { display: flex; gap: 12px; flex-wrap: wrap; font-size: 0.75rem; color: #999; }
.cron-meta span { display: inline-flex; align-items: center; gap: 4px; }
.badge-status { padding: 4px 10px; border-radius: 20px; font-size: 0.72rem; font-weight: 700; }
.badge-status.success { background: #d1e7dd; color: #0f5132; }
.badge-status.waiting { background: #fff3cd; color: #856404; }
.cron-actions { display: flex; gap: 6px; flex-shrink: 0; flex-wrap: wrap; }
.btn-action { padding: 8px 14px; border: none; border-radius: 8px; font-size: 0.8rem; font-weight: 600; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; text-decoration: none; transition: all 0.3s ease; }
.btn-action.run { background: #d1e7dd; color: #0f5132; }
.btn-action.run:hover { background: #00C853; color: white; }
.btn-action.reset { background: #fff3cd; color: #856404; }
.btn-action.reset:hover { background: #FF9900; color: white; }
.command-box { background: #1e293b; color: #e2e8f0; padding: 16px; border-radius: 10px; font-family: 'Courier New', monospace; font-size: 0.85rem; position: relative; display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
.command-box code { flex: 1; word-break: break-all; }
.btn-copy { background: #0066CC; color: white; border: none; padding: 8px 16px; border-radius: 6px; font-size: 0.8rem; font-weight: 600; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; flex-shrink: 0; }
.btn-copy:hover { background: #00B4FF; }
</style>

<div class="content-wrapper">
<div class="main-content">
    <div class="navbar-modern">
        <div class="navbar-left">
            <button class="burger-btn" onclick="toggleSidebar()"><i class="bi bi-list"></i></button>
            <div>
                <h1 class="navbar-title">Cron Job Manager</h1>
                <p class="navbar-subtitle"><i class="bi bi-gear-fill"></i> Pusat Kontrol Otomatisasi</p>
            </div>
        </div>
    </div>

    <div class="page-header">
        <h2 class="page-title"><i class="bi bi-clock-history"></i> Daftar Cron Job</h2>
    </div>

    <?= flashMessage() ?>

    <!-- Instruksi cPanel -->
    <div class="card-modern">
        <div class="card-header-modern success">
            <div class="title-left">
                <i class="bi bi-terminal-fill"></i>
                <span>Pengaturan cPanel (Cukup 1 Cron Saja!)</span>
            </div>
        </div>
        <div class="card-body-modern">
            <div class="alert-modern info" style="margin-bottom: 16px;">
                <i class="bi bi-info-circle-fill"></i>
                <div>
                    <strong>Sistem Smart Cron:</strong> Anda tidak perlu memasukkan semua cron ke cPanel. 
                    Cukup masukkan <strong>1 PERINTAH</strong> di bawah ini ke menu <strong>Cron Jobs</strong> di cPanel. 
                    Sistem akan otomatis membagi tugas ke semua cron di atas sesuai jadwalnya.
                </div>
            </div>
            <div class="command-box">
                <code id="cpanelCommand"><?= htmlspecialchars($cpanelCommand) ?></code>
                <button class="btn-copy" onclick="copyCommand()">
                    <i class="bi bi-clipboard"></i> Copy
                </button>
            </div>
            <small style="color:#666; display:block; margin-top:10px;">
                <i class="bi bi-lightbulb"></i> <strong>Cara:</strong> Buka cPanel > <strong>Cron Jobs</strong> > Common Settings: <strong>Once a minute (* * * * *)</strong> > Paste perintah di atas > Add New Cron Job.
            </small>
        </div>
    </div>

    <!-- Daftar Cron -->
    <div class="card-modern">
        <div class="card-header-modern primary">
            <div class="title-left">
                <i class="bi bi-list-task"></i>
                <span>Daftar Tugas Otomatis</span>
                <span class="badge-status success" style="background: rgba(255,255,255,0.2); color: white;"><?= count($cronRegistry) ?> Cron</span>
            </div>
        </div>
        <div class="card-body-modern">
            <?php foreach ($cronRegistry as $slug => $cron): 
                $status = $cronStatus[$slug];
            ?>
                <div class="cron-item">
                    <div class="cron-icon">
                        <i class="bi <?= $cron['icon'] ?>"></i>
                    </div>
                    <div class="cron-info">
                        <div class="cron-title">
                            <?= htmlspecialchars($cron['name']) ?>
                            <span class="badge-status <?= $status['status'] ?>">
                                <?= $status['status'] === 'success' ? '✅ Sudah Jalan Hari Ini' : '⏳ Menunggu Jadwal' ?>
                            </span>
                        </div>
                        <div class="cron-desc"><?= htmlspecialchars($cron['description']) ?></div>
                        <div class="cron-meta">
                            <span><i class="bi bi-clock"></i> Jadwal: <strong><?= htmlspecialchars($cron['schedule']) ?></strong></span>
                            <?php if ($status['last_run']): ?>
                                <span><i class="bi bi-check-circle"></i> Terakhir: <strong><?= date('d/m/Y H:i', $status['last_run']) ?></strong></span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="cron-actions">
                        <!-- ✅ DIPERBAIKI: Ubah /admin/ menjadi /branch/ -->
                        <a href="/branch/cron_manager.php?run=<?= $slug ?>&token=<?= csrfToken() ?>" 
                           class="btn-action run" 
                           onclick="return confirm('Jalankan <?= htmlspecialchars($cron['name']) ?> sekarang?')"
                           title="Jalankan Manual">
                            <i class="bi bi-play-fill"></i> Run
                        </a>
                        <!-- ✅ DIPERBAIKI: Ubah /admin/ menjadi /branch/ -->
                        <a href="/branch/cron_manager.php?reset=<?= $slug ?>&token=<?= csrfToken() ?>" 
                           class="btn-action reset" 
                           onclick="return confirm('Reset status cron ini?')"
                           title="Reset Status (Agar jalan lagi di jadwal berikutnya)">
                            <i class="bi bi-arrow-counterclockwise"></i> Reset
                        </a>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>
</div>

<script>
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebarOverlay');
    if (sidebar && overlay) {
        sidebar.classList.toggle('active');
        overlay.classList.toggle('active');
        document.body.style.overflow = sidebar.classList.contains('active') ? 'hidden' : '';
    }
}

function copyCommand() {
    const command = document.getElementById('cpanelCommand').innerText;
    navigator.clipboard.writeText(command).then(() => {
        alert('✅ Perintah berhasil disalin! Silakan paste di cPanel > Cron Jobs.');
    });
}
</script>

<?php require __DIR__ . '/../includes/footer.php'; ?>