<?php if ( ! defined( 'ABSPATH' ) ) exit;
global $wpdb;

// phpcs:disable WordPress.Security.NonceVerification.Recommended -- read-only display filter, no state change
$pbuaiv_per_page   = 20;
$pbuaiv_page       = max( 1, absint( isset( $_GET['paged'] ) ? wp_unslash( $_GET['paged'] ) : 1 ) );
$pbuaiv_offset     = ( $pbuaiv_page - 1 ) * $pbuaiv_per_page;
$pbuaiv_doc_type   = sanitize_key( isset( $_GET['doc_type'] ) ? wp_unslash( $_GET['doc_type'] ) : '' );
$pbuaiv_search     = sanitize_text_field( isset( $_GET['s'] )         ? wp_unslash( $_GET['s'] )         : '' );
$pbuaiv_date_from  = sanitize_text_field( isset( $_GET['date_from'] ) ? wp_unslash( $_GET['date_from'] ) : '' );
$pbuaiv_date_to    = sanitize_text_field( isset( $_GET['date_to'] )   ? wp_unslash( $_GET['date_to'] )   : '' );
// phpcs:enable

$pbuaiv_like_search = '%' . $wpdb->esc_like( $pbuaiv_search ) . '%';

// Fixed placeholder structure keeps Plugin Check happy while still allowing optional filters.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Plugin-owned table read for admin report; table names are generated from the WordPress database prefix.
$pbuaiv_total = (int) $wpdb->get_var( $wpdb->prepare(
    "SELECT COUNT(*)
     FROM {$wpdb->prefix}pbuaiv_documents d
     LEFT JOIN {$wpdb->posts} p ON p.ID = d.order_id
     WHERE ( %s = '' OR d.doc_type = %s )
       AND ( %s = '' OR d.doc_number LIKE %s OR p.post_title LIKE %s )
       AND ( %s = '' OR d.doc_date >= %s )
       AND ( %s = '' OR d.doc_date <= %s )",
    $pbuaiv_doc_type,
    $pbuaiv_doc_type,
    $pbuaiv_search,
    $pbuaiv_like_search,
    $pbuaiv_like_search,
    $pbuaiv_date_from,
    $pbuaiv_date_from,
    $pbuaiv_date_to,
    $pbuaiv_date_to
) );

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Plugin-owned table read for admin report; table names are generated from the WordPress database prefix.
$pbuaiv_rows = $wpdb->get_results( $wpdb->prepare(
    "SELECT d.*, p.post_title as order_title
     FROM {$wpdb->prefix}pbuaiv_documents d
     LEFT JOIN {$wpdb->posts} p ON p.ID = d.order_id
     WHERE ( %s = '' OR d.doc_type = %s )
       AND ( %s = '' OR d.doc_number LIKE %s OR p.post_title LIKE %s )
       AND ( %s = '' OR d.doc_date >= %s )
       AND ( %s = '' OR d.doc_date <= %s )
     ORDER BY d.id DESC
     LIMIT %d OFFSET %d",
    $pbuaiv_doc_type,
    $pbuaiv_doc_type,
    $pbuaiv_search,
    $pbuaiv_like_search,
    $pbuaiv_like_search,
    $pbuaiv_date_from,
    $pbuaiv_date_from,
    $pbuaiv_date_to,
    $pbuaiv_date_to,
    $pbuaiv_per_page,
    $pbuaiv_offset
) );
?>
<div class="pbuaiv-wrap">
    <div class="pbuaiv-page-header">
        <h1 class="pbuaiv-page-title">🇦🇪 <?php esc_html_e( 'Documents', 'pb-invoicing-system' ); ?></h1>
    </div>

    <!-- Filters -->
    <form method="get" class="pbuaiv-filters">
        <input type="hidden" name="page" value="pbuaiv-documents" />
        <select name="doc_type" class="pbuaiv-select pbuaiv-select--sm">
            <option value=""><?php esc_html_e( 'All Types', 'pb-invoicing-system' ); ?></option>
            <?php foreach(['invoice'=>'Tax Invoice','receipt'=>'Receipt','credit_note'=>'Credit Note','proforma'=>'Proforma','packing_slip'=>'Packing Slip','delivery_note'=>'Delivery Note'] as $pbuaiv_type_key => $pbuaiv_type_label): ?>
                <option value="<?php echo esc_attr( $pbuaiv_type_key ); ?>" <?php selected( $pbuaiv_doc_type, $pbuaiv_type_key ); ?>><?php echo esc_html( $pbuaiv_type_label ); ?></option>
            <?php endforeach; ?>
        </select>
        <input type="text" name="s" value="<?php echo esc_attr($pbuaiv_search); ?>" placeholder="<?php esc_attr_e('Search document number...','pb-invoicing-system'); ?>" class="pbuaiv-input pbuaiv-input--sm" />
        <input type="date" name="date_from" value="<?php echo esc_attr($pbuaiv_date_from); ?>" class="pbuaiv-input pbuaiv-input--sm" />
        <input type="date" name="date_to" value="<?php echo esc_attr($pbuaiv_date_to); ?>" class="pbuaiv-input pbuaiv-input--sm" />
        <button type="submit" class="pbuaiv-btn pbuaiv-btn--secondary pbuaiv-btn--sm"><?php esc_html_e('Filter','pb-invoicing-system'); ?></button>
        <a href="<?php echo esc_url(admin_url('admin.php?page=pbuaiv-documents')); ?>" class="pbuaiv-btn pbuaiv-btn--ghost pbuaiv-btn--sm"><?php esc_html_e('Reset','pb-invoicing-system'); ?></a>
    </form>

    <div class="pbuaiv-card" style="margin-top:16px;">
        <table class="pbuaiv-table">
            <thead>
                <tr>
                    <th><?php esc_html_e('Doc Number','pb-invoicing-system'); ?></th>
                    <th><?php esc_html_e('Type','pb-invoicing-system'); ?></th>
                    <th><?php esc_html_e('Order','pb-invoicing-system'); ?></th>
                    <th><?php esc_html_e('Date','pb-invoicing-system'); ?></th>
                    <th><?php esc_html_e('Status','pb-invoicing-system'); ?></th>
                    <th><?php esc_html_e('Sent','pb-invoicing-system'); ?></th>
                    <th><?php esc_html_e('Actions','pb-invoicing-system'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php if ( empty($pbuaiv_rows) ) : ?>
                    <tr><td colspan="7" style="text-align:center;padding:30px;color:#94a3b8;"><?php esc_html_e('No documents found.','pb-invoicing-system'); ?></td></tr>
                <?php else: ?>
                    <?php foreach ( $pbuaiv_rows as $pbuaiv_row ) :
                        $pbuaiv_order = wc_get_order( (int) $pbuaiv_row->order_id );
                    ?>
                    <tr>
                        <td><strong><?php echo esc_html($pbuaiv_row->doc_number); ?></strong></td>
                        <td><span class="pbuaiv-type-badge pbuaiv-type-badge--<?php echo esc_attr($pbuaiv_row->doc_type); ?>"><?php echo esc_html(ucwords(str_replace('_',' ',$pbuaiv_row->doc_type))); ?></span></td>
                        <td><?php if ( $pbuaiv_order ) : ?><a href="<?php echo esc_url(get_edit_post_link($pbuaiv_row->order_id)); ?>">#<?php echo esc_html($pbuaiv_order->get_order_number()); ?></a><?php else: echo esc_html('#'.$pbuaiv_row->order_id); endif; ?></td>
                        <td><?php echo esc_html(date_i18n(get_option('date_format'),strtotime($pbuaiv_row->doc_date))); ?></td>
                        <td><span class="pbuaiv-badge pbuaiv-badge--<?php echo esc_attr($pbuaiv_row->status); ?>"><?php echo esc_html($pbuaiv_row->status); ?></span></td>
                        <td><?php echo $pbuaiv_row->sent_at ? esc_html(date_i18n(get_option('date_format'),strtotime($pbuaiv_row->sent_at))) : '—'; ?></td>
                        <td>
                            <?php if ( $pbuaiv_order ) : ?>
                                <a href="<?php echo esc_url(PBUAIV_Download_Handler::get_url($pbuaiv_row->order_id,$pbuaiv_row->doc_type,'download')); ?>" target="_blank" class="pbuaiv-btn pbuaiv-btn--ghost pbuaiv-btn--sm" title="<?php esc_attr_e('Download PDF','pb-invoicing-system'); ?>">
                                    <span class="dashicons dashicons-download"></span>
                                </a>
                                <a href="<?php echo esc_url(PBUAIV_Download_Handler::get_url($pbuaiv_row->order_id,$pbuaiv_row->doc_type,'view')); ?>" target="_blank" class="pbuaiv-btn pbuaiv-btn--ghost pbuaiv-btn--sm" title="<?php esc_attr_e('View','pb-invoicing-system'); ?>">
                                    <span class="dashicons dashicons-visibility"></span>
                                </a>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <?php if ( $pbuaiv_total > $pbuaiv_per_page ) :
        $pbuaiv_pages = ceil($pbuaiv_total/$pbuaiv_per_page);
        echo '<div class="pbuaiv-pagination">';
        for ( $pbuaiv_i = 1; $pbuaiv_i <= $pbuaiv_pages; $pbuaiv_i++ ) {
            $pbuaiv_url = add_query_arg( [ 'paged' => $pbuaiv_i ] );
            $pbuaiv_active = $pbuaiv_i === $pbuaiv_page ? 'pbuaiv-pagination__item--active' : '';
            echo '<a href="' . esc_url( $pbuaiv_url ) . '" class="pbuaiv-pagination__item ' . esc_attr( $pbuaiv_active ) . '">' . (int) $pbuaiv_i . '</a>';
        }
        echo '</div>';
    endif; ?>
</div>
