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

global $wpdb;

// Read-only report filters. Nonce is optional so bookmarked report URLs still work.
// phpcs:disable WordPress.Security.NonceVerification.Recommended
$pbuaiv_report_from = isset( $_GET['from'] ) ? sanitize_text_field( wp_unslash( $_GET['from'] ) ) : wp_date( 'Y-m-01' );
$pbuaiv_report_to   = isset( $_GET['to'] ) ? sanitize_text_field( wp_unslash( $_GET['to'] ) ) : wp_date( 'Y-m-d' );
// phpcs:enable

$pbuaiv_report_from = preg_match( '/^\d{4}-\d{2}-\d{2}$/', $pbuaiv_report_from ) ? $pbuaiv_report_from : wp_date( 'Y-m-01' );
$pbuaiv_report_to   = preg_match( '/^\d{4}-\d{2}-\d{2}$/', $pbuaiv_report_to ) ? $pbuaiv_report_to : wp_date( 'Y-m-d' );

$pbuaiv_order_ids = wc_get_orders( [
    'limit'        => -1,
    'type'         => 'shop_order',
    'date_created' => $pbuaiv_report_from . ' 00:00:00...' . $pbuaiv_report_to . ' 23:59:59',
    'return'       => 'ids',
    'status'       => array_keys( wc_get_order_statuses() ),
] );

$pbuaiv_total_tax   = 0.0;
$pbuaiv_order_count = count( $pbuaiv_order_ids );
foreach ( $pbuaiv_order_ids as $pbuaiv_order_id ) {
    $pbuaiv_order = wc_get_order( $pbuaiv_order_id );
    if ( $pbuaiv_order ) {
        $pbuaiv_total_tax += (float) $pbuaiv_order->get_total_tax();
    }
}

$pbuaiv_report_orders = [];
$pbuaiv_total_sales   = 0.0;
$pbuaiv_total_ex_vat  = 0.0;
foreach ( $pbuaiv_order_ids as $pbuaiv_order_id ) {
    $pbuaiv_order = wc_get_order( $pbuaiv_order_id );
    if ( ! $pbuaiv_order ) {
        continue;
    }
    $pbuaiv_total = (float) $pbuaiv_order->get_total();
    $pbuaiv_vat   = (float) $pbuaiv_order->get_total_tax();
    $pbuaiv_ex    = max( 0, $pbuaiv_total - $pbuaiv_vat );

    $pbuaiv_total_sales  += $pbuaiv_total;
    $pbuaiv_total_ex_vat += $pbuaiv_ex;
    $pbuaiv_report_orders[] = [
        'id'       => $pbuaiv_order->get_id(),
        'number'   => $pbuaiv_order->get_order_number(),
        'date'     => $pbuaiv_order->get_date_created() ? $pbuaiv_order->get_date_created()->date_i18n( 'Y-m-d' ) : '',
        'customer' => trim( $pbuaiv_order->get_billing_first_name() . ' ' . $pbuaiv_order->get_billing_last_name() ),
        'status'   => wc_get_order_status_name( $pbuaiv_order->get_status() ),
        'ex_vat'   => $pbuaiv_ex,
        'vat'      => $pbuaiv_vat,
        'total'    => $pbuaiv_total,
    ];
}

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Plugin-owned reporting table.
$pbuaiv_docs_issued = (int) $wpdb->get_var( $wpdb->prepare(
    "SELECT COUNT(*) FROM {$wpdb->prefix}pbuaiv_documents WHERE doc_type = %s AND doc_date BETWEEN %s AND %s",
    'invoice',
    $pbuaiv_report_from,
    $pbuaiv_report_to
) );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Plugin-owned reporting table.
$pbuaiv_docs_sent = (int) $wpdb->get_var( $wpdb->prepare(
    "SELECT COUNT(*) FROM {$wpdb->prefix}pbuaiv_documents WHERE doc_type = %s AND status = %s AND doc_date BETWEEN %s AND %s",
    'invoice',
    'sent',
    $pbuaiv_report_from,
    $pbuaiv_report_to
) );

$pbuaiv_report_generated = isset( $_GET['pbuaiv_report_generated'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
?>
<div class="pbuaiv-wrap">
    <div class="pbuaiv-page-header">
        <h1 class="pbuaiv-page-title">🇦🇪 <?php esc_html_e( 'VAT Reports', 'pb-invoicing-system' ); ?></h1>
        <p class="pbuaiv-page-subtitle"><?php esc_html_e( 'Summary for FTA VAT Return filing.', 'pb-invoicing-system' ); ?></p>
    </div>

    <?php if ( $pbuaiv_report_generated ) : ?>
        <div class="notice notice-success inline"><p>
            <?php
            /* translators: 1: report start date, 2: report end date. */
            echo esc_html( sprintf( __( 'Report generated for %1$s to %2$s.', 'pb-invoicing-system' ), $pbuaiv_report_from, $pbuaiv_report_to ) );
            ?>
        </p></div>
    <?php endif; ?>

    <form method="get" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>" style="display:flex;gap:10px;align-items:center;margin-bottom:20px;">
        <input type="hidden" name="page" value="pbuaiv-reports" />
        <label class="pbuaiv-label" style="margin:0;"><?php esc_html_e( 'From:', 'pb-invoicing-system' ); ?></label>
        <input type="date" name="from" value="<?php echo esc_attr( $pbuaiv_report_from ); ?>" class="pbuaiv-input pbuaiv-input--sm" />
        <label class="pbuaiv-label" style="margin:0;"><?php esc_html_e( 'To:', 'pb-invoicing-system' ); ?></label>
        <input type="date" name="to" value="<?php echo esc_attr( $pbuaiv_report_to ); ?>" class="pbuaiv-input pbuaiv-input--sm" />
        <input type="hidden" name="pbuaiv_report_generated" value="1" />
        <button type="submit" class="pbuaiv-btn pbuaiv-btn--primary pbuaiv-btn--sm"><?php esc_html_e( 'Generate Report', 'pb-invoicing-system' ); ?></button>
    </form>

    <div class="pbuaiv-stats-grid">
        <div class="pbuaiv-stat-card"><div class="pbuaiv-stat-card__label"><?php esc_html_e( 'Total VAT Collected', 'pb-invoicing-system' ); ?></div><div class="pbuaiv-stat-card__value"><?php echo esc_html( number_format( $pbuaiv_total_tax, 2 ) ); ?> AED</div></div>
        <div class="pbuaiv-stat-card"><div class="pbuaiv-stat-card__label"><?php esc_html_e( 'Orders in Period', 'pb-invoicing-system' ); ?></div><div class="pbuaiv-stat-card__value"><?php echo esc_html( number_format( $pbuaiv_order_count ) ); ?></div></div>
        <div class="pbuaiv-stat-card"><div class="pbuaiv-stat-card__label"><?php esc_html_e( 'Invoices Issued', 'pb-invoicing-system' ); ?></div><div class="pbuaiv-stat-card__value"><?php echo esc_html( number_format( $pbuaiv_docs_issued ) ); ?></div></div>
        <div class="pbuaiv-stat-card"><div class="pbuaiv-stat-card__label"><?php esc_html_e( 'Invoices Emailed', 'pb-invoicing-system' ); ?></div><div class="pbuaiv-stat-card__value"><?php echo esc_html( number_format( $pbuaiv_docs_sent ) ); ?></div></div>
    </div>

    <?php if ( $pbuaiv_report_generated ) : ?>
        <div class="pbuaiv-card" style="margin-top:20px;">
            <div class="pbuaiv-card__head"><h2><?php esc_html_e( 'Generated VAT Report', 'pb-invoicing-system' ); ?></h2></div>
            <div class="pbuaiv-card__body">
                <table class="pbuaiv-table">
                    <thead>
                        <tr>
                            <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( 'Customer', 'pb-invoicing-system' ); ?></th>
                            <th><?php esc_html_e( 'Status', 'pb-invoicing-system' ); ?></th>
                            <th><?php esc_html_e( 'Subtotal Ex VAT', 'pb-invoicing-system' ); ?></th>
                            <th><?php esc_html_e( 'VAT', 'pb-invoicing-system' ); ?></th>
                            <th><?php esc_html_e( 'Total', 'pb-invoicing-system' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ( empty( $pbuaiv_report_orders ) ) : ?>
                            <tr><td colspan="7" style="text-align:center;padding:24px;color:#64748b;"><?php esc_html_e( 'No WooCommerce orders found for this report period.', 'pb-invoicing-system' ); ?></td></tr>
                        <?php else : ?>
                            <?php foreach ( $pbuaiv_report_orders as $pbuaiv_report_order ) : ?>
                                <tr>
                                    <td>#<?php echo esc_html( $pbuaiv_report_order['number'] ); ?></td>
                                    <td><?php echo esc_html( $pbuaiv_report_order['date'] ); ?></td>
                                    <td><?php echo esc_html( $pbuaiv_report_order['customer'] ); ?></td>
                                    <td><?php echo esc_html( $pbuaiv_report_order['status'] ); ?></td>
                                    <td><?php echo esc_html( number_format( $pbuaiv_report_order['ex_vat'], 2 ) ); ?> AED</td>
                                    <td><?php echo esc_html( number_format( $pbuaiv_report_order['vat'], 2 ) ); ?> AED</td>
                                    <td><strong><?php echo esc_html( number_format( $pbuaiv_report_order['total'], 2 ) ); ?> AED</strong></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                    <tfoot>
                        <tr>
                            <th colspan="4"><?php esc_html_e( 'Report Totals', 'pb-invoicing-system' ); ?></th>
                            <th><?php echo esc_html( number_format( $pbuaiv_total_ex_vat, 2 ) ); ?> AED</th>
                            <th><?php echo esc_html( number_format( $pbuaiv_total_tax, 2 ) ); ?> AED</th>
                            <th><?php echo esc_html( number_format( $pbuaiv_total_sales, 2 ) ); ?> AED</th>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    <?php endif; ?>

    <div class="pbuaiv-card" style="margin-top:20px;">
        <div class="pbuaiv-card__head"><h2><?php esc_html_e( 'Export', 'pb-invoicing-system' ); ?></h2></div>
        <div class="pbuaiv-card__body" style="display:flex;gap:12px;flex-wrap:wrap;">
            <a href="<?php echo esc_url( add_query_arg( [ 'page' => 'pbuaiv-reports', 'pbuaiv_export' => 'csv', 'from' => $pbuaiv_report_from, 'to' => $pbuaiv_report_to, 'nonce' => wp_create_nonce( 'pbuaiv_export' ) ], admin_url( 'admin.php' ) ) ); ?>" class="pbuaiv-btn pbuaiv-btn--secondary"><?php esc_html_e( 'Export VAT Summary CSV', 'pb-invoicing-system' ); ?></a>
            <a href="<?php echo esc_url( add_query_arg( [ 'page' => 'pbuaiv-reports', 'pbuaiv_export' => 'xml_bulk', 'from' => $pbuaiv_report_from, 'to' => $pbuaiv_report_to, 'nonce' => wp_create_nonce( 'pbuaiv_export' ) ], admin_url( 'admin.php' ) ) ); ?>" class="pbuaiv-btn pbuaiv-btn--ghost"><?php esc_html_e( 'Export PINT AE XML (Bulk)', 'pb-invoicing-system' ); ?></a>
        </div>
    </div>
</div>
