<?php

use \UtillzCore\Inc\Src\Request\Request;
use \UtillzCore\Inc\Src\Listing\Listing;

defined('ABSPATH') || exit;

global $wpdb;

$request = Request::instance();
$rows_per_page = 50;
$page = $request->has('onpage') ? $request->get('onpage') : 1;
$offset = ( $page - 1 ) * $rows_per_page;
$user_id = (int) get_current_user_id();

$results = $wpdb->get_results("
    SELECT *
    FROM {$wpdb->prefix}usermeta
    WHERE user_id = {$user_id}
    AND meta_key = 'ulz_downloaded_item'
    ORDER BY umeta_id DESC
    LIMIT {$rows_per_page}
    OFFSET {$offset}
");

$results_count = (int) $wpdb->get_var("
    SELECT COUNT(*)
    FROM {$wpdb->prefix}usermeta
    WHERE user_id = {$user_id}
    AND meta_key = 'ulz_downloaded_item'
");

$assets = (object) [
    'results' => $results,
    'max_num_pages' => ceil( $results_count / $rows_per_page ),
];

?>

<?php if( $assets->results ): ?>
    <div class="ulz-asset-list">
        <ul>
            <?php foreach( $assets->results as $asset ): ?>
                <?php $listing = new Listing( $asset->meta_value ); ?>
                <?php if( $listing->id ): ?>
                    <li>
                        <a href="<?php echo get_permalink( $listing->id ); ?>" target="_blank">
                            <?php $image = $listing->get_first_from_gallery('thumbnail'); ?>
                            <?php if( $image ): ?>
                                <div class="ulz--image">
                                    <span style="background-image: url('<?php echo esc_url( $image ); ?>');"></span>
                                </div>
                            <?php endif; ?>
                            <div class="ulz--name">
                                <?php echo esc_html( $listing->post->post_title ) ?>
                            </div>
                        </a>
                    </li>
                <?php endif; ?>
            <?php endforeach; ?>
        </ul>
    </div>
<?php else: ?>
    <p class="ulz-weight-700"><?php esc_html_e('No results were found', 'heilz'); ?></p>
<?php endif; ?>

<div class="ulz-paging">
    <?php

        echo Ucore()->pagination([
            'base' => add_query_arg( [ 'onpage' => '%#%' ], wc_get_account_endpoint_url('assets') ),
            'format' => '?onpage=%#%',
            'current' => $page,
            'total' => $assets->max_num_pages,
        ]);

    ?>
</div>
