<?php
/*-----------------------------------------------*/
/* EXTHEM.ES - Apps Updates Dashboard (with Auto-Refresh on New Updates)
/*-----------------------------------------------*/
if ( ! defined( 'ABSPATH' ) ) exit;

/* --------------------------------------------------------------------
 * Add Admin Menu with Live Update Counter
 * ------------------------------------------------------------------ */
if ( ! function_exists( 'apk_update_menux' ) ) {
    function apk_update_menux() {
        $count = apk_update_count_posts(); // Your existing count function
        $badge = $count > 0 ? '<span class="update-plugins count-'.$count.'"><span class="plugin-count">'.$count.'</span></span>' : '';
        add_menu_page(
            'Apps Updates',
            'Apps Updates '.$badge,
            'manage_options',
            'apps_updates',
            'apps_updates',
            'dashicons-update',
            999
        );
    }
    add_action( 'admin_menu', 'apk_update_menux' );
}

/* --------------------------------------------------------------------
 * AJAX: Apply single app update
 * ------------------------------------------------------------------ */
add_action('wp_ajax_ajax_update_single_app', 'ajax_update_single_app');
function ajax_update_single_app() {
    check_ajax_referer('single_app_refresh_updates_nonce', 'nonce');

    $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
    if (!$post_id || !current_user_can('edit_post', $post_id)) {
        wp_send_json_error(['message' => 'Permission denied']);
    }

    $available_version = get_post_meta($post_id, 'available_version', true);
    $available_whatsnew = get_post_meta($post_id, 'available_whatsnew', true);
    $title = get_post_meta($post_id, 'wp_title_GP', true) ?: get_the_title($post_id) ?: 'Unknown App';

    if (empty($available_version)) {
        wp_send_json_error(['message' => 'No new version available.']);
    }

    // YOUR REAL UPDATE LOGIC HERE
    $result = true;

    if (is_wp_error($result)) {
        wp_send_json_error(['message' => $result->get_error_message()]);
    }

    delete_post_meta($post_id, 'available_updated');
    delete_post_meta($post_id, 'available_version');
    delete_post_meta($post_id, 'available_whatsnew');
    update_post_meta($post_id, 'wp_version_GP', $available_version);
    update_post_meta($post_id, 'wp_whatnews_GP', $available_whatsnew);
    update_post_meta($post_id, 'last_updated', current_time('mysql'));

    wp_send_json_success([
        'message'     => 'App updated successfully!',
        'app_name'    => $title,
        'new_version' => $available_version,
    ]);
}

/* --------------------------------------------------------------------
 * AJAX: Render list + pagination + total count only
 * ------------------------------------------------------------------ */
add_action('wp_ajax_apk_update_render_updates_list_ajax', 'apk_update_render_updates_list_ajax');
function apk_update_render_updates_list_ajax() {
    check_ajax_referer('single_app_refresh_updates_nonce', 'nonce');
    if (!current_user_can('edit_posts')) {
        wp_send_json_error(['message' => 'Permission denied']);
    }

    $paged    = max(1, intval($_POST['paged'] ?? 1));
    $per_page = 10;
    $offset   = ($paged - 1) * $per_page;
    $post_type = 'post'; // CHANGE IF USING CUSTOM POST TYPE

    global $wpdb;

    // Accurate total count
    $total = apk_update_count_posts();

    $total_pages = ceil($total / $per_page);

    ob_start();
    apk_update_render_updates_list($offset, $per_page);
    $html = ob_get_clean();

    $pagination = '';
    if ($total_pages > 1) {
        $pagination = '<div class="mediart-pagination">' . paginate_links([
            'base'      => add_query_arg('upaged', '%#%'),
            'format'    => '',
            'current'   => $paged,
            'total'     => $total_pages,
            'prev_text' => 'Prev',
            'next_text' => 'Next',
            'type'      => 'plain',
        ]) . '</div>';
    }

    wp_send_json_success([
        'html'       => $html,
        'pagination' => $pagination,
        'total'      => $total,
    ]);
}

/* --------------------------------------------------------------------
 * Render app cards
 * ------------------------------------------------------------------ */
function apk_update_render_updates_list($offset = 0, $per_page = 10) {
    global $wpdb;
    $post_type = 'post';

    $query2 = $wpdb->prepare("
        SELECT COUNT(p.ID)
        FROM $wpdb->posts p
        INNER JOIN $wpdb->postmeta pm_avail ON p.ID = pm_avail.post_id
            AND pm_avail.meta_key = 'available_version' AND pm_avail.meta_value != ''
        LEFT JOIN $wpdb->postmeta pm_curr ON p.ID = pm_curr.post_id
            AND pm_curr.meta_key = 'wp_version_GP'
        WHERE p.post_type = %s
          AND p.post_status = 'publish'
          AND pm_avail.meta_value > IFNULL(pm_curr.meta_value, '0.0.0')
		   AND EXISTS (
			 SELECT 1 FROM {$wpdb->postmeta} pm2 
			 WHERE pm2.post_id = p.ID 
			   AND pm2.meta_key = 'available_updated' 
			   AND pm2.meta_value = 'yes'
		   ) 
    ", $post_type, $offset, $per_page);

	$query = $wpdb->prepare("
        SELECT p.ID, p.post_title,
               pm_avail.meta_value AS available_version,
               pm_curr.meta_value AS current_version,
               pm_title.meta_value AS display_title,
               pm_whatsnew.meta_value AS available_whatsnew,
               pm_poster.meta_value AS fallback_image,
               pm_lastcheck.meta_value AS last_checked
        FROM {$wpdb->posts} p
        INNER JOIN {$wpdb->postmeta} pm_avail ON p.ID = pm_avail.post_id
            AND pm_avail.meta_key = 'available_version' AND pm_avail.meta_value != ''
        LEFT JOIN {$wpdb->postmeta} pm_curr ON p.ID = pm_curr.post_id
            AND pm_curr.meta_key = 'wp_version_GP'
        LEFT JOIN {$wpdb->postmeta} pm_title ON p.ID = pm_title.post_id
            AND pm_title.meta_key = 'wp_title_GP'
        LEFT JOIN {$wpdb->postmeta} pm_whatsnew ON p.ID = pm_whatsnew.post_id
            AND pm_whatsnew.meta_key = 'available_whatsnew'
        LEFT JOIN {$wpdb->postmeta} pm_poster ON p.ID = pm_poster.post_id
            AND pm_poster.meta_key = 'wp_poster_GP'
        LEFT JOIN {$wpdb->postmeta} pm_lastcheck ON p.ID = pm_lastcheck.post_id
            AND pm_lastcheck.meta_key = '_time_scrape_app_update'
        WHERE p.post_type = %s
          AND p.post_status = 'publish'
          AND pm_avail.meta_value > IFNULL(pm_curr.meta_value, '0.0.0')
          AND EXISTS (
              SELECT 1 FROM {$wpdb->postmeta} pm2
              WHERE pm2.post_id = p.ID
                AND pm2.meta_key = 'available_updated'
                AND pm2.meta_value = 'yes'
          )
        ORDER BY pm_lastcheck.meta_value + 0 DESC  -- +0 forces numeric sort on timestamp
        LIMIT %d, %d
    ", $post_type, $offset, $per_page);
	
	$query11 = $wpdb->prepare("
        SELECT p.ID, p.post_title,
               pm_avail.meta_value AS available_version,
               pm_curr.meta_value AS current_version,
               pm_title.meta_value AS display_title,
               pm_whatsnew.meta_value AS available_whatsnew,
               pm_poster.meta_value AS fallback_image,
               pm_lastcheck.meta_value AS last_checked
        FROM {$wpdb->posts} p
        INNER JOIN {$wpdb->postmeta} pm_avail ON p.ID = pm_avail.post_id
            AND pm_avail.meta_key = 'available_version' AND pm_avail.meta_value != ''
        LEFT JOIN {$wpdb->postmeta} pm_curr ON p.ID = pm_curr.post_id
            AND pm_curr.meta_key = 'wp_version_GP'
        LEFT JOIN {$wpdb->postmeta} pm_title ON p.ID = pm_title.post_id
            AND pm_title.meta_key = 'wp_title_GP'
        LEFT JOIN {$wpdb->postmeta} pm_whatsnew ON p.ID = pm_whatsnew.post_id
            AND pm_whatsnew.meta_key = 'available_whatsnew'
        LEFT JOIN {$wpdb->postmeta} pm_poster ON p.ID = pm_poster.post_id
            AND pm_poster.meta_key = 'wp_poster_GP'
        INNER JOIN {$wpdb->postmeta} pm_lastcheck ON p.ID = pm_lastcheck.post_id
            AND pm_lastcheck.meta_key = '_time_scrape_app_update'
        WHERE p.post_type = %s
          AND p.post_status = 'publish'
          AND pm_avail.meta_value > IFNULL(pm_curr.meta_value, '0.0.0')
          AND EXISTS (
              SELECT 1 FROM {$wpdb->postmeta} pm2
              WHERE pm2.post_id = p.ID
                AND pm2.meta_key = 'available_updated'
                AND pm2.meta_value = 'yes'
          )
        ORDER BY pm_lastcheck.meta_value + 0 DESC  -- +0 forces numeric sort on timestamp
        LIMIT %d, %d
    ", $post_type, $offset, $per_page);
	
    $apps = $wpdb->get_results($query);

    echo '<section><div class="row">';
	
    if (empty($apps)) {
        echo '<div class="text-center col-12" style="padding:100px;color:#888;"><h4 style="color:#00ba37;">All apps are up to date</h4></div>';
        //echo '</div></section>';
        return;
    }

    $counter = $offset + 1;
    foreach ($apps as $app) {
        $post_id = intval($app->ID);
        $title = !empty($app->display_title) ? $app->display_title : ($app->post_title ?: 'Unknown App');
        $current = $app->current_version ?: 'Unknown';
        $available = $app->available_version;
        $whatsnew = $app->available_whatsnew ? wp_kses_post(nl2br($app->available_whatsnew)) : '';
        $last_checked = $app->last_checked ? human_time_diff(intval($app->last_checked)) . ' ago' : 'Never';

        $thumb = get_the_post_thumbnail_url($post_id, 'thumbnail')
              ?: ($app->fallback_image ?: 'https://via.placeholder.com/64x64/333/666?text=APP');
        ?>
        <div class="col-12 col-md-6 mb-4">
            <div class="app-container" data-post-id="<?php echo esc_attr($post_id); ?>"
                 style="display:flex;align-items:center;gap:12px;padding:12px;background:#111;border:1px solid #333;border-radius:8px;">
                <label style="margin:0;cursor:pointer;"><input type="checkbox" class="app-checkbox"></label>
                <div style="position:relative;">
                    <img src="<?php echo esc_url($thumb); ?>" width="64" height="64" style="border-radius:8px;object-fit:cover;">
                    <span style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);background:rgba(0,0,0,0.8);color:white;padding:6px 10px;border-radius:6px;font-weight:bold;border:2px solid white;">
                        <?php echo $counter++; ?>
                    </span>
                </div>
                <div style="flex:1;">
                    <h3 style="margin:0;font-size:16px;color:#fff;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;max-width: 220px;display: inline-block;vertical-align: middle;" class="up-down-shake"><?php echo esc_html($title); ?></h3>
                    <div style="font-size:13px;color:#aaa;">
                        <span style="color:white;">v<?php echo esc_html($current); ?></span> → 
                        <span style="color:lime;">v<?php echo esc_html($available); ?></span><br>
                        Last checked: <span style="color:gold;"><?php echo esc_html($last_checked); ?></span>
                    </div>
                </div>
                <a href="#" class="mediart-single-update" data-post-id="<?php echo esc_attr($post_id); ?>"
                   style="background:brown;color:white;padding:10px 16px;border-radius:6px;border:none;font-weight:bold;text-decoration:none;">
                    Update Now
                </a>
                <a href="<?php echo esc_url(get_edit_post_link($post_id)); ?>" target="_blank"
                   style="background:#34495e;color:white;padding:10px 16px;border-radius:6px;border:none;font-weight:bold;text-decoration:none;margin-left:8px;">
                    Edit
                </a>
            </div>
        </div>
        <?php
    }
    echo '</div></section>';
}

/* --------------------------------------------------------------------
 * Main Admin Page (with Auto Refresh)
/* ------------------------------------------------------------------ */
function apps_updates() {
    if (!current_user_can('edit_posts')) wp_die('Permission denied.');

    echo do_shortcode('[css]');
    $nonce = wp_create_nonce('single_app_refresh_updates_nonce');
    $linkforce = wp_nonce_url(add_query_arg('app_update_force_check', '1'), 'app_update_force_check_all');
    ?>
	
<style>
#wpwrap,#wpbody-content {
	background: #171c1f!important;
}

.play_menu {
	background: #454a4d!important;
	color: #fff!important;
}

.mediart-updates-container {
	transition: opacity .4s;
}

.mediart-updates-container.loading {
	opacity: .5;
	pointer-events: none;
}

.highlight-flash {
	animation: highlightFlash 1.8s ease-out;
}

.app-updating {
	border: 2px solid #8b5cf6!important;
	animation: pulse 1.5s infinite;
}

.app-success {
	border: 2px solid #00ba37!important;
	background: rgba(0,186,55,.15)!important;
}

.app-error {
	border: 2px solid #d63638!important;
	background: rgba(214,54,56,.15)!important;
}

@keyframes highlightFlash {
	0%,100% {
		background: transparent;
	}

	50% {
		background: rgba(139,92,246,.3);
	}
}

@keyframes pulse {
	0%,100% {
		box-shadow: 0 0 0 0 rgba(139,92,246,.7);
	}

	70% {
		box-shadow: 0 0 0 10px transparent;
	}
}

.app-checkbox {
	margin-right: 10px;
	transform: scale(1.2);
}

.app-container {
	position: relative;
}

.app-container[title]:hover::after {
	content: attr(title);
	position: absolute;
	bottom: 100%;
	left: 50%;
	transform: translateX(-50%);
	background: #333;
	color: #fff;
	padding: 8px 12px;
	border-radius: 6px;
	font-size: 13px;
	white-space: nowrap;
	z-index: 10;
	margin-bottom: 8px;
}

.mediart-pagination {
	margin: 30px 0;
	text-align: center;
}

.mediart-pagination a,.mediart-pagination span {
	display: inline-block;
	padding: 10px 16px;
	margin: 0 4px;
	border-radius: 6px;
	background: #333;
	color: #fff;
	text-decoration: none;
	min-width: 44px;
}

.mediart-pagination a:hover {
	background: #555;
}

.mediart-pagination .current {
	background: brown;
	font-weight: bold;
}

.sticky-header {
	position: sticky;
	top: 32px;
	z-index: 1000;
	transition: all 0.3s ease;
	margin-bottom: 0 !important;
}

.admin-bar .sticky-header {
	top: 32px;
}

@media screen and (max-width: 782px) {
	.admin-bar .sticky-header {
		top: 46px;
	}
}

.sticky-header.scrolled {
	box-shadow: 0 8px 20px rgba(0,0,0,0.4);
	border-radius: 0;
	margin: 0 -10px;
	padding-left: 20px;
	padding-right: 20px;
}

</style>

    <div class="play_menu sticky-header" style="text-transform:uppercase;margin-bottom:15px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:15px;">
        <b><span id="mediart-updates-count">Loading...</span> App(s) Available for Update</b>
        <div style="display:flex;gap:12px;flex-wrap:wrap;">
            <a href="<?php echo esc_url($linkforce); ?>" style="padding: 1rem;">Check All Apps Now</a>
            <button type="button" id="mediart-update-selected" class="button button-primary" style="background:#9b59b6;display:none;">Update Selected (<span id="selected-count">0</span>)</button>
            <button type="button" id="mediart-update-all" class="button button-primary" style="background:#c7254e;border:none;">Update All This Page (<span id="update-all-count">0</span>)</button>
        </div>
    </div>

    <div id="mediart-progress-container" style="display:none;margin:20px 0;background:#111;padding:15px;border-radius:8px;border:1px solid #444;">
        <div style="display:flex;justify-content:space-between;margin-bottom:10px;color:#fff;">
            <strong id="progress-title">Updating apps...</strong>
            <span id="mediart-progress-text">0 of 0</span>
        </div>
        <div style="width:100%;height:30px;background:#222;border-radius:8px;overflow:hidden;">
            <div id="mediart-progress-bar" style="width:0%;height:100%;background:linear-gradient(90deg,#8b5cf6,#ec4899);transition:width .6s ease;"></div>
        </div>
        <div id="mediart-progress-status" style="margin-top:8px;color:#aaa;">Starting...</div>
    </div>

    <div style="margin-bottom:15px;padding:10px 0;border-bottom:1px solid #444;">
        <label style="color:#aaa;"><input type="checkbox" id="select-all-apps"> <strong>Select All (This Page)</strong></label>
    </div>

    <div id="mediart-updates-container" class="mediart-updates-container loading">
        <div style="text-align:center;padding:100px;color:#888;">Loading updates...</div>
    </div>
    <div id="mediart-pagination" class="mediart-pagination" style="display:none;"></div>

    <?php echo do_shortcode('[ft_menu]'); ?>
    <?php echo do_shortcode('[ft_js]'); ?>

<script>
// Sticky header scroll effect
$(window).on('scroll', function() {
    if ($(this).scrollTop() > 100) {
        $('.sticky-header').addClass('scrolled');
    } else {
        $('.sticky-header').removeClass('scrolled');
    }
});

jQuery(function($) {
    let isUpdating = false;
    let currentPage = 1;
    let currentTotal = 0;
    const $container = $('#mediart-updates-container');
    const $pagination = $('#mediart-pagination');
    const $countSpan = $('#mediart-updates-count');
    const $progress = $('#mediart-progress-container');
    const $bar = $('#mediart-progress-bar');
    const $text = $('#mediart-progress-text');
    const $status = $('#mediart-progress-status');
    const $title = $('#progress-title');
    const $updateAll = $('#mediart-update-all');
    const $updateSelected = $('#mediart-update-selected');
    const $selectedCount = $('#selected-count');
    const $allCount = $('#update-all-count');
    const nonce = '<?php echo esc_js($nonce); ?>';

	const $badge2 = $('#toplevel_page_apps_updates .plugin-count');
	const $menuItem = $('#wp-admin-bar-mediart-apk-updates > .ab-item');
	
    function loadPage(page = 1, forceHighlight = false) {
        currentPage = page;
        $container.addClass('loading').html('<div style="text-align:center;padding:100px;color:#888;font-size:18px;">Loading page ' + page + '...</div>');
        $pagination.hide();

        $.post(ajaxurl, {
            action: 'apk_update_render_updates_list_ajax',
            paged: page,
            nonce: nonce
        })
        .done(function(response) {
            if (response.success) {
                $container.html(response.data.html);
                $pagination.html(response.data.pagination || '');
                const newTotal = response.data.total || 0;
                $countSpan.text(newTotal || 'No');
				$badge2.text(newTotal);
				//$menuItem.text(newTotal);
                if (newTotal > 0) $pagination.show();

                if (forceHighlight || newTotal > currentTotal) {
                    $container.addClass('highlight-flash');
                    setTimeout(() => $container.removeClass('highlight-flash'), 1800);
                }
                currentTotal = newTotal;

                updateCounts();
            } else {
                $container.html('<div style="text-align:center;padding:100px;color:#d63638;">Error loading updates.</div>');
            }
        })
        .fail(function() {
            $container.html('<div style="text-align:center;padding:100px;color:#d63638;">Request failed. Please refresh.</div>');
        })
        .always(() => $container.removeClass('loading'));
    }

    loadPage(1);

    // Background polling for new updates
    setInterval(() => {
        if (isUpdating) return;
        $.post(ajaxurl, {
            action: 'apk_update_render_updates_list_ajax',
            paged: currentPage,
            nonce: nonce
        })
        .done(res => {
            if (res.success && (res.data.total || 0) > currentTotal) {
                loadPage(currentPage, true);
            }
        });
    }, 30000);

    $(document).on('click', '.mediart-pagination a', function(e) {
        e.preventDefault();
        const match = this.href.match(/upaged=(\d+)/);
        if (match) {
            const page = parseInt(match[1]);
            if (page !== currentPage) {
                loadPage(page);
                $('html, body').animate({ scrollTop: $container.offset().top - 100 }, 400);
            }
        }
    });

    function updateCounts() {
        const total = $container.find('.app-container').length;
        const selected = $container.find('.app-checkbox:checked').length;
        $allCount.text(total);
        $selectedCount.text(selected);
        $updateSelected.toggle(selected > 0);
        $updateAll.prop('disabled', total === 0 || isUpdating);
        $updateSelected.prop('disabled', isUpdating);
    }

    $(document).on('change', '#select-all-apps', function() {
        $container.find('.app-checkbox').prop('checked', this.checked);
        updateCounts();
    });
    $(document).on('change', '.app-checkbox', updateCounts);

    $(document).on('click', '.mediart-single-update', function(e) {
        e.preventDefault();
        if (isUpdating) return;
        const post_id = $(this).data('post-id');
        updateApps([post_id], 'Updating 1 app...');
    });

    $updateSelected.on('click', function() {
        const ids = $container.find('.app-checkbox:checked').map(function() {
            return $(this).closest('.app-container').find('.mediart-single-update').data('post-id');
        }).get();
        if (ids.length) updateApps(ids, `Updating ${ids.length} selected app(s)...`);
    });

    $updateAll.on('click', function() {
        const ids = $container.find('.mediart-single-update').map(function() {
            return $(this).data('post-id');
        }).get();
        if (ids.length) updateApps(ids, 'Updating all apps on this page...');
    });

    function updateApps(post_ids, titleText) {
        if (!confirm(`Update ${post_ids.length} app(s)? This action cannot be undone.`)) return;

        isUpdating = true;
        $progress.show();
        $title.text(titleText);
        $bar.css('width', '0%');
        $text.text('0 of ' + post_ids.length);
        $status.text('Starting...');
        $updateAll.prop('disabled', true);
        $updateSelected.prop('disabled', true);

        let done = 0, failed = 0;

        function processNext() {
            if (done + failed >= post_ids.length) {
                let statusMsg = 'Finished! ';
                if (failed === 0) {
                    statusMsg += `<span style="color:#00ba37">All ${done} apps updated successfully!</span>`;
                } else if (done === 0) {
                    statusMsg += `<span style="color:#d63638">All ${failed} updates failed.</span>`;
                } else {
                    statusMsg += `<span style="color:#ffa500">${done} updated, ${failed} failed.</span>`;
                }
                $status.html(statusMsg);
                $bar.css('width', '100%');

                // Hide progress bar after 2 seconds and refresh the list
                setTimeout(() => {
                    $progress.hide();  // ← Auto-hide progress bar
                    loadPage(currentPage, true);
                }, 2000);

                isUpdating = false;
                return;
            }

            const post_id = post_ids[done + failed];
            const $box = $container.find(`[data-post-id="${post_id}"]`).closest('.app-container');
            const name = $box.find('h3').text().trim();

            $box.removeClass('app-success app-error highlight-flash').addClass('app-updating');
            $status.html(`Updating: <strong>${name}</strong>`);

            $.post(ajaxurl, {
                action: 'ajax_update_single_app',
                post_id: post_id,
                nonce: nonce
            })
            .done(function(response) {
                if (response.success) {
                    done++;
                    $box.removeClass('app-updating').addClass('app-success highlight-flash');
                } else {
                    failed++;
                    const msg = response.data?.message || 'Update failed';
                    $box.removeClass('app-updating').addClass('app-error').attr('title', 'Error: ' + msg);
                }
            })
            .fail(function(xhr) {
                failed++;
                const msg = xhr.responseJSON?.data?.message || xhr.responseText || 'Request failed';
                $box.removeClass('app-updating').addClass('app-error').attr('title', 'Error: ' + msg);
            })
            .always(function() {
                $text.text((done + failed) + ' of ' + post_ids.length);
                $bar.css('width', ((done + failed) / post_ids.length * 100) + '%');
                setTimeout(processNext, 800);
            });
        }

        processNext();
    }
});
</script> 
 
    <?php
}