<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Silence is golden.

/* =====================================================
   EXTREMES – FAST CHECK UPDATES FULL PACKAGE
   ===================================================== */

/* -------------------------------------------
   1. Direct Debug Mode: ?fastcheck=123,456
-------------------------------------------- */
add_action('init', function() {
    if (!isset($_GET['fastcheck']) || !current_user_can('manage_options')) return;

    $raw_ids = sanitize_text_field($_GET['fastcheck']);
    $ids = array_filter(array_map('intval', explode(',', $raw_ids)));

    if (empty($ids)) wp_die('No valid post IDs provided.');

    echo '<pre style="
        background:#1e1e1e;
        color:#0f9d58;
        padding:30px;
        font-family:Consolas,Monaco,\'Courier New\',monospace;
        font-size:15px;
        line-height:1.7;
        border:3px solid #0f9d58;
        border-radius:12px;
        margin:50px auto;
        max-width:960px;
        white-space:pre-wrap;
        box-shadow:0 0 30px rgba(15,157,88,0.5);
        overflow-x:auto;">';

    echo "🚀 FAST UPDATE CHECKER STARTED\n";
    echo "📅 " . date('Y-m-d H:i:s') . " (Server Time)\n";
    echo str_repeat('─', 60) . "\n\n";

    foreach($ids as $id){
        $post = get_post($id);
        if(!$post){
            echo "❌ POST ID <strong>$id</strong> → Does not exist\n\n";
            continue;
        }

        $title = get_the_title($id);
        $appid = get_post_meta($id,'wp_GP_ID',true);

        echo "📱 POST ID <strong>$id</strong> → <span style='color:#ff0;'>$title</span>";
        if($appid) echo " (<span style='color:#0ff;'>$appid</span>)";
        echo "\n";

        ob_start();
        $has_update = fast_app_update_light($id,true);
        $debug_output = ob_get_clean();

        if(strpos($debug_output,'[UPDATE AVAILABLE]')!==false){
            echo "✅ <span style='color:lime;'>UPDATE FOUND!</span>\n";
        }elseif(strpos($debug_output,'[UP TO DATE]')!==false){
            echo "✔️ <span style='color:cyan;'>Up to date</span>\n";
        }elseif(strpos($debug_output,'[FAILED]')!==false){
            echo "❌ <span style='color:red;'>Failed to retrieve version</span>\n";
        }else{
            echo "ℹ️ Checked\n";
        }

        echo $debug_output."\n";
        echo str_repeat('─',50)."\n\n";
    }

    echo "🏁 FAST CHECK COMPLETE\n</pre>";
    die();
});

/* -------------------------------------------
   3. Add Fast Check Link per Post Row
-------------------------------------------- */
add_action('post_row_actions', function($actions,$post){
    if(!current_user_can('manage_options')) return $actions;
    $nonce = wp_create_nonce('fastcheck_nonce');
    $actions['fast_check'] = '<a href="#" class="fast-check-btn" data-postid="'.$post->ID.'" data-nonce="'.$nonce.'">🚀 FAST CHECK</a>';
    return $actions;
},10,2);

/* -------------------------------------------
   4. AJAX Handler
-------------------------------------------- */
add_action('wp_ajax_fastcheck_ajax', function(){
    if(!current_user_can('manage_options')) wp_send_json_error('Permission denied');

    $post_id = intval($_POST['post_id'] ?? 0);
    $nonce   = $_POST['nonce'] ?? '';

    if(!wp_verify_nonce($nonce,'fastcheck_nonce') || !$post_id) wp_send_json_error('Invalid request');

    $notice = fast_app_update_light_notice($post_id);
    echo $notice;
    wp_die();
});

/* -------------------------------------------
   5. Bulk Action
-------------------------------------------- */
add_filter('bulk_actions-edit-post', function($actions){
    if(current_user_can('manage_options')) $actions['fastcheck_ultra'] = '🚀 FAST CHECK';
    return $actions;
});


if ( ! function_exists( 'add_check_all_visible_button' ) ) 
{
	//add_action('manage_posts_extra_tablenav', 'add_check_all_visible_button');
	function add_check_all_visible_button($which) 
	{
		if ($which !== 'top') {
			return;
		}

		$screen = get_current_screen();
		if (!$screen || $screen->post_type !== 'post') {
			return;
		}

		if (!current_user_can('manage_options')) {
			return;
		}

		// Enqueue script hanya di halaman edit-post
		// wp_enqueue_script('jquery');

		// Script inline untuk handle klik button		 
		
		// Tampilkan button di alignleft actions (sebelah kiri, bersama bulk actions)
		//echo '<div class="alignleft actions" style="margin-right:10px;">';
		//submit_button('🚀 Fast Update Checker', 'secondary', 'check-all-visible-btn', false, array('id' => 'check-all-visible-btn'));
		//echo '</div>';
		
		//echo $script;
	}
}

/**
 * 7. (Opsional) Tambahkan juga di bawah tabel agar lebih mudah diakses saat scroll
 */
if ( ! function_exists( 'add_check_all_visible_button_bottom' ) ) 
{
	add_action('manage_posts_extra_tablenav', 'add_check_all_visible_button_bottom', 10, 1);
	function add_check_all_visible_button_bottom($which) 
	{
		if ($which !== 'bottom') {
			return;
		}
		add_check_all_visible_button('top'); // Reuse fungsi yang sama, tapi button akan muncul di bottom
	}
}
 
if ( ! function_exists( 'add_check_all_visible_button_ajax' ) ) 
{
    add_action('manage_posts_extra_tablenav', 'add_check_all_visible_button_ajax', 10, 1);
    function add_check_all_visible_button_ajax($which) {
        if ($which !== 'top') return;

        $screen = get_current_screen();
        if (!$screen || $screen->post_type !== 'post') return;
        if (!current_user_can('manage_options')) return;

        // Button HTML
        echo '<div class="alignleft actions" style="margin-right:10px;">';
        submit_button('🚀 Check All Visible', 'secondary', 'check-all-visible-ajax-btn', false, array('id'=>'check-all-visible-ajax-btn'));
        echo '</div>';

		// Enqueue script hanya di halaman edit-post
		wp_enqueue_script('jquery');
		
        // Inline JS
		//modal_popup();
        ?>
 

		<?php
    }
} 

add_action('admin_footer', function()
{ 
modal_popup();
?>

<!-- ================= TERMINAL MODAL STYLE ================= -->
<style>
#fastcheck-modal-overlay {
    display: none;
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,.45);
    z-index: 100000;
}
#fastcheck-modal {
    display: none;
    position: fixed;
    top: 50%; left: 50%;
    transform: translate(-50%,-50%);
    width: 90%;
    max-width: 760px;
    max-height: 80%;
    background: #0b0f14;
    color: #c9d1d9;
    border: 1px solid #30363d;
    border-radius: 10px;
    padding: 18px;
    overflow: auto;
    font-family: "JetBrains Mono", Consolas, Monaco, monospace;
    font-size: 13px;
    z-index: 100001;
    box-shadow: 0 0 25px rgba(0,255,120,.15);
}
#fastcheck-modal-close {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 32px;
    height: 32px;
    background: #ff7b72;
    color: #fff;
    border-radius: 50%;
    text-align: center;
    line-height: 32px;
    font-size: 16px;
    font-weight: bold;
    cursor: pointer;
    box-shadow: 0 2px 6px rgba(0,0,0,0.3);
    transition: background 0.2s, transform 0.2s;
}

#fastcheck-modal-close:hover {
    background: #ff4f45;
    transform: scale(1.1);
}

#fastcheck-progress-container {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 16px;
    flex-wrap: wrap;
}
#fastcheck-progress-bar {
    flex: 1;
    height: 10px;
    background: #161b22;
    border-radius: 6px;
    overflow: hidden;
    min-width: 180px;
}
#fastcheck-progress-bar-inner {
    height: 100%;
    width: 0%;
    background: linear-gradient(90deg, #00ff88, #00cc6a);
    transition: width .25s;
}
#fastcheck-counter {
    min-width: 140px;
    text-align: right;
    color: white;
    font-weight: 500;
}
#fastcheck-done {
    color: #3fb950;
    font-weight: bold;
    white-space: nowrap;
    display: none;
    align-items: center;
}
#fastcheck-done.show {
    display: flex;
}
#fastcheck-done::before {
    content: "✔ ";
    margin-right: 4px;
}
#fastcheck-output > div {
    background: #010409;
    border: 1px solid #30363d;
    border-radius: 6px;
    padding: 8px;
    margin-bottom: 8px;
}
#fastcheck-output > div > div {
    cursor: pointer;
    font-weight: 600;
    color: #7ee787;
}
 
#fastcheck-output > div > div::before {
    content: "C:\\Users\\<?php echo ucwords(parse_url(home_url( '/' ))['host']); ?> >_ ";
    color: #fff;
}

#fastcheck-output > div > div::before > div::before {
    content: ". ";
    color: #fff;
    animation: blinkCursor 1s step-start infinite;
}

#fastcheck-output > div > div::after {
    content: "."; /* cursor blink */
    color: #fff;
    margin-left: 2px; /* jarak dari teks statis */
    animation: blinkCursor 1s step-start infinite;
}

@keyframes blinkCursor {
    0%, 50% {
        opacity: 1;
    }
    51%, 100% {
        opacity: 0;
    }
}
.terminal-prefix {
    color: #fff; /* teks statis */
}

.terminal-cursor {
    color: #fff;
    animation: blinkCursor 1s step-start infinite;
}

@keyframes blinkCursor {
    0%, 50% { opacity: 1; }
    51%, 100% { opacity: 0; }
}


#fastcheck-output span {
    display: none;
    margin-top: 6px;
    padding-left: 12px;
    border-left: 2px solid #30363d;
    white-space: pre-wrap;
    color: #c9d1d9;
}
@media (max-width: 600px) {
    #fastcheck-modal {
        width: 80%;
        max-width: none; /* hilangkan max-width untuk layar kecil */
        padding: 12px;
        font-size: 12px;
    }

    #fastcheck-progress-container {
        flex-direction: column;
        align-items: stretch;
        gap: 8px;
    }

    #fastcheck-counter {
        text-align: left;
        min-width: auto;
    }

    #fastcheck-progress-bar {
        min-width: auto;
    }
}

</style>

<script type="text/javascript">
jQuery(function($){
    var paused = false;
    var queue = [];
    var completed = 0;
    var total = 0;
    var allCompleted = false;

    // Modal control
    function showModal() {
        $('#fastcheck-modal-overlay, #fastcheck-modal').fadeIn(200);
		$('body').css('overflow', 'hidden'); // Nonaktifkan scroll body
    }
 
	function hideModal() {
		$('#fastcheck-modal-overlay, #fastcheck-modal').fadeOut(200, function(){
			$('body').css('overflow', ''); // Kembalikan scroll body
			if (allCompleted) {
				location.reload();
			}
		});
	}


    $('#fastcheck-modal-close, #fastcheck-modal-overlay').on('click', hideModal);
    $(document).on('keydown', function(e){
        if (e.key === "Escape") hideModal();
    });

    // Update text progress (ASCII bar)
    function updateTerminalProgress() {
        var barLength = 20;
        var filled = Math.round((completed / total) * barLength);
        var empty = barLength - filled;
        var bar = '[' + '#'.repeat(filled) + '-'.repeat(empty) + ']';
        $('#fastcheck-counter').text(
            'Progress: ' + completed + '/' + total + ' ' + bar
        );

        // Optional: update visual progress bar juga
        if (total > 0) {
            //$('#fastcheck-progress-bar-inner').css('width', ((completed / total) * 100) + '%');
        }
    }

    function finishAll() {
        $('#fastcheck-output span').hide();
        $('#fastcheck-counter').text(
            'Progress: ' + total + '/' + total + ' [####################]'
        );
        $('#fastcheck-done').addClass('show');
        allCompleted = true;
    }

    function processNext() {
        if (paused) return;
        if (queue.length === 0) {
            finishAll();
            return;
        }

        var item = queue.shift();
        var postID = (typeof item === 'object') ? item.postID : item;
        var nonce = (typeof item === 'object' && item.nonce)
            ? item.nonce
            : '<?php echo wp_create_nonce("fastcheck_nonce"); ?>';

        var container = $('<div>');
        var header = $('<div>').text('Post ID ' + postID + ' → loading...');
        var body = $('<span>').css({ display: 'none', whiteSpace: 'pre-wrap' });

        container.append(header).append(body);
        $('#fastcheck-output').append(container);

        $.post(ajaxurl, {
            action: 'fastcheck_ajax',
            post_id: postID,
            nonce: nonce
        })
        .done(function(response) {
            body.text(response);

            var title = (response.match(/Title:\s*(.+)/i) || [])[1] || 'Unknown';
            var newVer = (response.match(/New:\s*([^\s]+)/i) || [])[1] || '';

            header.off('click'); // bersihkan event sebelumnya

            if (response.includes('UPDATE AVAILABLE')) {
                header
                    .text(title + ' → v.' + newVer + ' UPDATE AVAILABLE')
                    .css({
                        'color': '#3fb950',      // Hijau cerah - perlu update
                        'font-weight': 'bold'
                    })
                    .on('click', function(){ body.toggle(); });
                body.show(); // auto-expand untuk yang perlu update
            }
            else if (response.includes('UP TO DATE')) {
                header
                    .text(title + ' → UP TO DATE')
                    .css({
                        'color': '#fff',      // Biru-hijau - aman
                        'font-weight': '500'
                    })
                    .on('click', function(){ body.toggle(); });
            }
            else if (response.includes('FAILED')) {
                header
                    .text(title + ' → FAILED')
                    .css({
                        'color': '#d29922',      // Merah - gagal
                        'font-weight': 'bold'
                    })
                    .on('click', function(){ body.toggle(); });
            }
            else {
                header.text(title)
                      .css('color', '#FFD700'); // default/abnormal
            }

            completed++;
            updateTerminalProgress();
            processNext();
        })
        .fail(function() {
            body.text('AJAX ERROR').show();
            header
                .text('Post ID ' + postID + ' → ERROR')
                .css({
                    'color': '#d29922',          // Kuning/oranye - error teknis
                    'font-weight': 'bold'
                })
                .on('click', function(){ body.toggle(); });

            completed++;
            updateTerminalProgress();
            processNext();
        });
    }

    // ── EVENT HANDLERS ───────────────────────────────────────────────

    // 1. Single row check
    $(document).on('click', '.fast-check-btn', function(e){
        e.preventDefault();

        queue = [{
            postID: $(this).data('postid'),
            nonce: $(this).data('nonce')
        }];

        completed = 0;
        total = 1;
        allCompleted = false;

        $('#fastcheck-output').empty();
        $('#fastcheck-counter').text('');
        $('#fastcheck-done').removeClass('show');
        //$('#fastcheck-progress-bar-inner').css('width', '0%');

        updateTerminalProgress();
        showModal();
        processNext();
    });

    // 2. Bulk action (fastcheck_ultra dari dropdown)
    $(document).on('click', '#doaction, #doaction2', function(e){
        var $form = $(this).closest('form');
        var action = $form.find('select[name="action"], select[name="action2"]').val();

        if (action !== 'fastcheck_ultra') return;

        e.preventDefault();

        var ids = [];
        $('tbody th.check-column input:checked').each(function(){
            var id = $(this).val();
            if (id) ids.push(id);
        });

        if (!ids.length) {
            alert('Please select at least one item');
            return;
        }

        queue = ids.map(function(id) {
            return { postID: id, nonce: '<?php echo wp_create_nonce("fastcheck_nonce"); ?>' };
        });

        completed = 0;
        total = queue.length;
        allCompleted = false;

        $('#fastcheck-output').empty();
        $('#fastcheck-counter').text('');
        $('#fastcheck-done').removeClass('show');
        //$('#fastcheck-progress-bar-inner').css('width', '0%');

        updateTerminalProgress();
        showModal();
        processNext();
    });

    // 3. Check all visible posts on current page
    $(document).on('click', '#check-all-visible-ajax-btn', function(e){
        e.preventDefault();

        var postIDs = [];
        $('#the-list tr input[type="checkbox"][name="post[]"]').each(function(){
            var val = $(this).val();
            if (val) postIDs.push(val);
        });

        if (!postIDs.length) {
            alert('There are no visible posts on this page.');
            return;
        }

        queue = postIDs; // nonce pakai default dari PHP

        completed = 0;
        total = postIDs.length;
        allCompleted = false;

        $('#fastcheck-output').empty();
        $('#fastcheck-counter').text('');
        $('#fastcheck-done').removeClass('show');
        //$('#fastcheck-progress-bar-inner').css('width', '0%');

        updateTerminalProgress();
        showModal();
        processNext();
    });

    // Tambah elemen "ALL CHECKS COMPLETED" jika belum ada
    if ($('#fastcheck-done').length === 0) {
        $('#fastcheck-progress-container').append(
            '<span id="fastcheck-done">ALL CHECKS COMPLETED</span>'
        );
    }
});
</script>
 
<?php
});

function modal_popup() 
{
?>

<!-- Overlay -->
<div id="fastcheck-modal-overlay"></div>

<!-- Modal -->
<div id="fastcheck-modal">
    <!-- Tombol close bulat -->
    <span id="fastcheck-modal-close">×</span>

    <!-- Progress container -->
    <div id="fastcheck-progress-container">
        <span id="fastcheck-counter"></span>
        <div id="fastcheck-progress-bar">
            <div id="fastcheck-progress-bar-inner"></div>
        </div> 
    </div>

    <!-- Output area -->
    <div id="fastcheck-output"></div>
</div>

<?php
}



/* =============================
   ⚠️ END OF FULL PACKAGE
   ============================= */
