<?php 
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

// Verify nonce for incoming GET requests
if (isset($_GET['aifilterpage']) && isset($_GET['_wpnonce'])) {
    if (!wp_verify_nonce(sanitize_key($_GET['_wpnonce']), 'unleash_ai_aifilterpage_nonce')) {
        wp_die(esc_html__('Invalid request. Nonce verification failed.', 'unleashai'));
    }
}

// Current page number for filter
$aifilterpage = isset($_GET['aifilterpage']) ? absint($_GET['aifilterpage']) : 10;

// Extract pagination-related values from response
$total_results = $response_data->data['total_result'] ?? 0;
$items_per_page = $response_data->data['per_page'] ?? 10;
$current_page = $response_data->data['page'] ?? 1;
$total_pages = ceil($total_results / $items_per_page);

// Validate pagination parameters
if ($current_page < 1) $current_page = 1;
if ($current_page > $total_pages) $current_page = $total_pages;

// Data for pages
$data = $response_data->data['data'] ?? [];

$stored_response = get_option('unleash_ai_registration_response');
if ($stored_response) {
    $stored_response = json_decode($stored_response, true); // Decode if needed
}
if (empty($stored_response)) { ?>
			  <div>You are not logged in. Please log in <a href="?page=cg_meta_al">here</a> to continue.</div>
<?php  exit; }?>



<div class="flexButtonsCg">
    <div class="gridFlexCg">
        <ul class="buttonsCg">
            <li><a id="pages-tab" href="admin.php?page=cg_meta_al_list" class="normalBtnCG normalBtnCGV2">Pages/Post</a></li>
            <!--<li><a id="posts-tab" href="admin.php?page=cg_meta_al_product" class="normalBtnCG normalBtnCGV2">Products</a></li>-->
            <li><a id="posts-tab" href="admin.php?page=cg_meta_al_altag" class="normalBtnCG ">Alt Tags</a></li>

        </ul>
    </div>
	
	 <div class="gridFlexCg justifyRight">
        <ul class="buttonsCg">
		
		<!--<li><a style="cursor:pointer;" onclick="metakeywordailogout()" herf="javascript:void(0);" class="normalBtnCG normalBtnCGV3 metakeywordailogout">Logout</a></li>
		   --->
		   <li> <li><select id="page_filter" onchange="call_filter();">
            <option value="">select filter</option>
            <option <?php if ($aifilterpage == 5) { ?> selected <?php } ?> value="5">5</option>
            <option <?php if ($aifilterpage == 10) { ?> selected <?php } ?> value="10">10</option>
            <option <?php if ($aifilterpage == 30) { ?> selected <?php } ?> value="30">30</option>
            <option <?php if ($aifilterpage == 50) { ?> selected <?php } ?> value="50">50</option>
        </select></li></li>
		
		   <li>

<?php if ($total_pages > 1): ?>
    <div class="flexDirectionCg flexDirectionCgSB" style="margin:0;">
        <div class="space-betweenCls" style="order:2;">
            <div class="generatePlain heightBtnCenter2">
                <button class="btnWdH clickToExpand fetch_dataall">
                    <?php echo esc_html__('Generate All', 'unleashai'); ?>
                </button>
            </div>
            <div class="generatePlain heightBtnCenter2">
                <button class="btnWdH blueBtncg clickToExpand update_btnall">
                    <?php echo esc_html__('Update All', 'unleashai'); ?>
                </button>
            </div>
        </div>
    </div>
<?php endif; ?>

    </li>
		  
        </ul>
    </div>

</div>



	
<div class="tableStCg" class="tab-pane fade show active" id="pages" role="tabpanel" aria-labelledby="pages-tab">
    <div class="scrollTable">
        <div class="bgAreaGray37">
        
            <table cellpadding="0" cellspacing="0" >
			
                <tbody>
                    <tr class="flexDs">
                        <td class="wd30s noBGColor noBGColor2 relabs20007">
                            <table cellpadding="0" cellspacing="0" class="boldTd">
                                <tbody>
                                    <tr>
                                        <td class="">
										<label class="containerCheckmark absCheckbocLeft selectall abs45New">
                    <input type="checkbox" id="selectAllCheckbox" class="selectall_checkbox">
                    <span class="checkmark"></span>
                  </label>
										<b>Media</b></td>
                                    </tr>
                                </tbody>
                            </table>
                        </td>
                        <td class="wd80s wd78s noBGColor noBGColor2">
                            <table cellpadding="0" cellspacing="0">
                                <tbody>
                                    <tr class="rightFlexForm">
                                        <td class="wd80s">
                                            <table cellpadding="0" cellspacing="0" class="boldTd">
                                                <tbody>
                                                    <tr class="flexWdTd">
                                                        <td>
                                                            <label style="padding-left:54px;" class="containerCheckmark"><b>Alt Tags</b></label>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </td>
                                        <td class="wd20s">
                                            <table cellpadding="0" cellspacing="0" class="boldTd" style="text-align:center;">
                                                <tbody>
                                                    <tr>
                                                        <td><b>Action</b></td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div class="borderSeparate">
            <?php
           if (!empty($data)) {
            $pages = [];
            $il = 1;
            foreach ($data as $page) {
                $page_title = $page['post_title'] ?? 'Untitled';
                $parent_id = $page['post_id'] ?? '';
                $attachments = $page['attachments'] ?? [];
                if ($il == 1) {
                    $activsl = "active";
                    $displaysty = "display:block;";
                } else {
                    $activsl = "";
                    $displaysty = "display:none;";
                }

                // Extract image URLs
                $images = [];
              
                            ?>
                            <!-- Render Attachment Content -->
                            <button id="<?php echo esc_attr($parent_id); ?>" class="accordionBtn <?php echo esc_attr($activsl); ?>">
    <?php echo esc_html($page_title); ?>
    <label class="containerCheckmark absCheckbocLeft">
        <input type="checkbox" class="pre_title_checkbox pageitem" data-id="<?php echo esc_attr($parent_id); ?>" data-content="<?php echo esc_url($file_url); ?>" data-parent-id="<?php echo esc_attr($parent_id); ?>" data-page-id="<?php echo esc_attr($parent_id); ?>" reqatt="0" value="0">
        <span class="checkmark"></span>
    </label>
</button> <div class="bgAreaGray37 panel" style="<?php echo esc_attr($displaysty); ?>">
                          <?php  foreach ($attachments as $attachment) {
                 $post_id = $attachment_id =  $attachment['post_id'] ?? null;
                 $file_url =  $attachment['url'] ?? null;
                 $calt =  $attachment['alt_tag'] ?? null; ?>
                           
        <table cellpadding="0" cellspacing="0">
            <tbody>
                <tr class="flexDs" id="alt_<?php echo esc_attr($post_id); ?>">
                    <td class="wd30s noBGColor ">
                        <table cellpadding="0" cellspacing="0">
                            <tbody>
                                <tr>
                                    <td class="setwdTdImg45unq">
                                        <img src="<?php echo esc_url($file_url); ?>" style="width: 100%; height: 170px; object-fit: cover; border-radius: 5px;">
                                    </td>
                                    <td>
                                        <div class="titLeLink">
                                            <a href="<?php echo esc_url($file_url); ?>"></a>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </td>
                
                    
                    <td class="wd70s wd78s">
                        <table cellpadding="0" cellspacing="0">
                            <tbody>
                                <tr class="rightFlexForm"  id="page_<?php echo esc_attr($post_id); ?>">
                                    <td class="wd80s">
									<div class="mb-2">
                      <input class="form-control h-25 rounded" id="meta_des_<?php echo esc_attr($post_id); ?>" type="text" value="<?php echo esc_attr($calt);?>" aria-label="Disabled input example" placeholder="Current Alt Tag" disabled="" readonly="">
                    </div>
                                        <table cellpadding="0" cellspacing="0">
                                            <tbody>
                                                <tr class="flexWdTd">
                                                    
                                                    <td>
                                                        <div class="flexCheckCg flexCheckCgNoFlex extraHeight">
                                                            <div class="flexCheckCgChild flexCheckCgChildV2">
                                                                <label class="containerCheckmark">
                                                                    <input type="checkbox" class="alt_checkbox pre_des_chk" desreqatt="0"  data-parent-id="<?php echo esc_attr($parent_id); ?>" data-id="<?php echo esc_attr($post_id); ?>" name="meta_d_0_chkd_<?php echo esc_attr($post_id); ?>" value="0">
                                                                    <span class="checkmark"></span>
                                                                </label>
                                                            </div>
                                                            <div class="flexCheckCgChild PDleft22">
                                                                <textarea class="altg_aig" name="meta_des_0_<?php echo esc_attr($post_id); ?>" placeholder="Generated Alt Tag"></textarea>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    
                                                    <td>
                                                        <div class="flexCheckCg flexCheckCgNoFlex extraHeight">
                                                            <div class="flexCheckCgChild flexCheckCgChildV2">
                                                                <label class="containerCheckmark">
                                                                    <input type="checkbox" class="alt_checkbox pre_des_chk" desreqatt="1"  data-parent-id="<?php echo esc_attr($parent_id); ?>" data-id="<?php echo esc_attr($post_id); ?>" name="meta_d_1_chkd_<?php echo esc_attr($post_id); ?>" value="1">
                                                                    <span class="checkmark"></span>
                                                                </label>
                                                            </div>
                                                            <div class="flexCheckCgChild PDleft22">
                                                                <textarea class="altg_aig" name="meta_des_1_<?php echo esc_attr($post_id); ?>" placeholder="Generated Alt Tag"></textarea>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    
                                                    <td>
                                                        <div class="flexCheckCg flexCheckCgNoFlex extraHeight">
                                                            <div class="flexCheckCgChild flexCheckCgChildV2">
                                                                <label class="containerCheckmark">
                                                                    <input type="checkbox" class="alt_checkbox pre_des_chk" desreqatt="2"  data-parent-id="<?php echo esc_attr($parent_id); ?>" data-id="<?php echo esc_attr($post_id); ?>" name="meta_d_2_chkd_<?php echo esc_attr($post_id); ?>" value="2">
                                                                    <span class="checkmark"></span>
                                                                </label>
                                                            </div>
                                                            <div class="flexCheckCgChild PDleft22">
                                                                <textarea class="altg_aig" name="meta_des_2_<?php echo esc_attr($post_id); ?>" placeholder="Generated Alt Tag"></textarea>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    
                                                </tr>
                                            </tbody>
                                        </table>
                                    </td>
                                    <td class="wd20s">
                                        <table cellpadding="0" cellspacing="0">
                                            <tbody>
                                            <tr>
    <td class="centerAppBtn">
        <div class="generatePlain heightBtnCenter2">
            <button class="btnWdH clickToExpand fetch_data" typattrb="meta_both" 
                data-id="<?php echo esc_attr($post_id); ?>" 
                data-content="<?php echo esc_url(wp_get_attachment_url()); ?>" 
                data-parent-id="<?php echo esc_attr($parent_id); ?>" 
                data-page-id="<?php echo esc_attr($attachment_id); ?>">
                <?php echo esc_html__('Generate', 'unleashai'); ?>
            </button>
        </div>                                                                                                     
        <div class="generatePlain heightBtnCenter2">
            <button class="btnWdH blueBtncg update-btn" 
                data-id="<?php echo esc_attr($attachment_id); ?>" 
                data-parent-id="<?php echo esc_attr($parent_id); ?>" 
                data-page-id="<?php echo esc_attr($attachment_id); ?>">
                <?php echo esc_html__('Update', 'unleashai'); ?>
            </button>
        </div>
    </td>
</tr>

                                            </tbody>
                                        </table>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </td>
                </tr>
            </tbody>
        </table>
   
	
                            <?php
                    }
                    $il = $il + 1;
                       echo ' </div>';
                    }
                }

  
  
            ?>
            
        </div>
    </div>
</div>
<?php
// Pagination Links
if ($total_pages > 1) {
    echo '<div class="flexDirectionCg flexDirectionCgSB">';
    echo '<div class="space-betweenCls" style="order:2;">
            <div class="generatePlain heightBtnCenter2">
                <button class="btnWdH clickToExpand fetch_dataall">' . esc_html__('Generate All', 'unleashai') . '</button>
            </div>
            <div class="generatePlain heightBtnCenter2">
                <button class="btnWdH blueBtncg clickToExpand update_btnall">' . esc_html__('Update All', 'unleashai') . '</button>
            </div>
        </div>';
    echo '<div class="space-betweenCls" style="order:1;">';
    
    // Adjust pagination base and add the correct query args
    //$base_url = esc_url(get_pagenum_link(1)); // Get the base URL for pagination
    //$base_url = esc_url(remove_query_arg('paged', $base_url)); // Remove any existing 'paged' parameter
    $base_url = esc_url_raw(add_query_arg('paged', '%#%'));

    echo  wp_kses_post(paginate_links(array(
        'base'      => $base_url . '%_%',  // Correct base URL for pagination
        'format'    => '',
        'current'   => $current_page,
        'total'     => $total_pages,
        'mid_size'  => 2,
        'prev_text' => esc_html__('« Previous', 'unleashai'),
        'next_text' => esc_html__('Next »', 'unleashai'),
    )));

    echo '</div></div>';
}

