<?php
/**
 * Admin dashboard for Factur-X invoices.
 *
 * Adds a submenu page under WooCommerce with invoice statistics,
 * filterable invoice list, and monthly summaries.
 *
 * @package FacturX_For_WooCommerce
 */

defined( 'ABSPATH' ) || exit;

class GOFACTOX_Dashboard {

    public static function init(): void {
        // Admin dashboard with statistics is a Pro feature.
        if ( ! self::can_use() ) {
            return;
        }

        add_action( 'admin_menu', [ __CLASS__, 'add_menu' ], 99 );
    }

    /**
     * Premium-code gate, filterable for staging environments or paid customers
     * whose Freemius opt-in cannot complete (e.g. no outgoing SMTP).
     */
    private static function can_use(): bool {
        return class_exists( 'GOFACTOX_License' ) && GOFACTOX_License::is_pro();
    }

    /**
     * Add submenu page under WooCommerce.
     */
    public static function add_menu(): void {
        add_submenu_page(
            'woocommerce',
            __( 'Factur-X Invoices', 'gofactox-e-invoicing-for-woocommerce' ),
            __( 'Factur-X', 'gofactox-e-invoicing-for-woocommerce' ),
            'manage_woocommerce',
            'wfx-dashboard',
            [ __CLASS__, 'render_page' ]
        );
    }

    /**
     * Render the dashboard page.
     */
    public static function render_page(): void {
        $stats = self::get_stats();
        $month_filter = isset( $_GET['month'] ) ? sanitize_text_field( wp_unslash( $_GET['month'] ) ) : current_time( 'Y-m' ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $invoices = self::get_invoices( $month_filter );
        ?>
        <div class="wrap">
            <h1><?php esc_html_e( 'Factur-X Invoices', 'gofactox-e-invoicing-for-woocommerce' ); ?></h1>

            <!-- Stats Cards -->
            <div style="display: flex; gap: 16px; margin: 20px 0;">
                <?php self::render_stat_card( __( 'Total Invoices', 'gofactox-e-invoicing-for-woocommerce' ), $stats['total_count'] ); ?>
                <?php self::render_stat_card( __( 'This Month', 'gofactox-e-invoicing-for-woocommerce' ), $stats['month_count'] ); ?>
                <?php self::render_stat_card(
                    __( 'Monthly Revenue', 'gofactox-e-invoicing-for-woocommerce' ),
                    wc_price( $stats['month_total'] )
                ); ?>
                <?php self::render_stat_card(
                    __( 'Total Revenue', 'gofactox-e-invoicing-for-woocommerce' ),
                    wc_price( $stats['total_amount'] )
                ); ?>
            </div>

            <!-- Month Filter -->
            <form method="get" style="margin-bottom: 16px;">
                <input type="hidden" name="page" value="wfx-dashboard">
                <label for="month"><?php esc_html_e( 'Month:', 'gofactox-e-invoicing-for-woocommerce' ); ?></label>
                <input type="month" id="month" name="month" value="<?php echo esc_attr( $month_filter ); ?>">
                <button type="submit" class="button"><?php esc_html_e( 'Filter', 'gofactox-e-invoicing-for-woocommerce' ); ?></button>
            </form>

            <?php self::render_fec_export(); ?>

            <!-- Invoice Table -->
            <table class="widefat striped">
                <thead>
                    <tr>
                        <th><?php esc_html_e( 'Invoice', 'gofactox-e-invoicing-for-woocommerce' ); ?></th>
                        <th><?php esc_html_e( 'Date', 'gofactox-e-invoicing-for-woocommerce' ); ?></th>
                        <th><?php esc_html_e( 'Order', 'gofactox-e-invoicing-for-woocommerce' ); ?></th>
                        <th><?php esc_html_e( 'Customer', 'gofactox-e-invoicing-for-woocommerce' ); ?></th>
                        <th class="text-right"><?php esc_html_e( 'Total', 'gofactox-e-invoicing-for-woocommerce' ); ?></th>
                        <th><?php esc_html_e( 'Actions', 'gofactox-e-invoicing-for-woocommerce' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ( empty( $invoices ) ) : ?>
                        <tr><td colspan="6"><?php esc_html_e( 'No invoices found for this period.', 'gofactox-e-invoicing-for-woocommerce' ); ?></td></tr>
                    <?php else : ?>
                        <?php foreach ( $invoices as $inv ) : ?>
                        <tr>
                            <td>
                                <strong><?php echo esc_html( $inv['number'] ); ?></strong>
                                <?php if ( ! empty( $inv['is_credit_note'] ) ) : ?>
                                    <span style="display:inline-block; margin-left:4px; padding:1px 6px; background:#fee2e2; color:#b91c1c; border-radius:3px; font-size:10px; font-weight:600;"><?php esc_html_e( 'AVOIR', 'gofactox-e-invoicing-for-woocommerce' ); ?></span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo esc_html( date_i18n( 'd/m/Y', strtotime( $inv['date'] ) ) ); ?></td>
                            <td>
                                <?php if ( $inv['order'] ) : ?>
                                    <a href="<?php echo esc_url( $inv['order']->get_edit_order_url() ); ?>">
                                        #<?php echo esc_html( $inv['order']->get_order_number() ); ?>
                                    </a>
                                <?php else : ?>
                                    -
                                <?php endif; ?>
                            </td>
                            <td><?php echo esc_html( $inv['customer'] ); ?></td>
                            <td style="text-align: right;"><?php echo wp_kses_post( wc_price( $inv['total'] ) ); ?></td>
                            <td>
                                <?php if ( $inv['has_pdf'] ) : ?>
                                    <a href="<?php echo esc_url( $inv['download_url'] ); ?>" class="button button-small" target="_blank">
                                        <?php esc_html_e( 'PDF', 'gofactox-e-invoicing-for-woocommerce' ); ?>
                                    </a>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php
    }

    /**
     * Render the FEC export panel (date range + download button).
     */
    private static function render_fec_export(): void {
        if ( ! class_exists( 'GOFACTOX_FEC_Export' ) ) {
            return;
        }
        // FEC is a Business-tier feature. Show the box to Pro users with an upsell hint.
        if ( ! class_exists( 'GOFACTOX_License' ) || ! GOFACTOX_License::is_business() ) {
            echo '<div style="background:#f6f7f7; border:1px solid #ddd; border-radius:8px; padding:16px 20px; margin-bottom:16px;">';
            echo '<h2 style="margin:0 0 6px; font-size:16px;">' . esc_html__( 'FEC Export (Fichier des Écritures Comptables)', 'gofactox-e-invoicing-for-woocommerce' ) . '</h2>';
            echo '<p style="margin:0; color:#646970; font-size:13px;">' . esc_html__( 'Tax-administration-compliant accounting export (article A47 A-1 LPF). Available on the Business plan.', 'gofactox-e-invoicing-for-woocommerce' ) . '</p>';
            echo '</div>';
            return;
        }
        $first_day = current_time( 'Y' ) . '-01-01';
        $today     = current_time( 'Y-m-d' );
        ?>
        <div style="background:#fff; border:1px solid #ddd; border-radius:8px; padding:16px 20px; margin-bottom:16px;">
            <h2 style="margin:0 0 6px; font-size:16px;"><?php esc_html_e( 'FEC Export (Fichier des Écritures Comptables)', 'gofactox-e-invoicing-for-woocommerce' ); ?></h2>
            <p style="margin:0 0 12px; color:#646970; font-size:13px;"><?php esc_html_e( 'Export your invoices and credit notes in the format required by the French tax administration (article A47 A-1 LPF). Each invoice and credit note produces one accounting entry split across the customer, sales, and VAT accounts.', 'gofactox-e-invoicing-for-woocommerce' ); ?></p>
            <form method="get" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="display:flex; gap:12px; align-items:center;">
                <input type="hidden" name="action" value="gofactox_fec_export">
                <?php wp_nonce_field( 'gofactox_fec_export' ); ?>
                <label><?php esc_html_e( 'From:', 'gofactox-e-invoicing-for-woocommerce' ); ?>
                    <input type="date" name="from" value="<?php echo esc_attr( $first_day ); ?>">
                </label>
                <label><?php esc_html_e( 'To:', 'gofactox-e-invoicing-for-woocommerce' ); ?>
                    <input type="date" name="to" value="<?php echo esc_attr( $today ); ?>">
                </label>
                <button type="submit" class="button button-primary"><?php esc_html_e( 'Download FEC', 'gofactox-e-invoicing-for-woocommerce' ); ?></button>
            </form>
        </div>
        <?php
    }

    /**
     * Render a stat card.
     */
    private static function render_stat_card( string $label, $value ): void {
        ?>
        <div style="background: #fff; border: 1px solid #ddd; border-radius: 8px; padding: 16px 24px; min-width: 150px;">
            <div style="font-size: 24px; font-weight: bold; color: #2563eb;"><?php echo wp_kses_post( $value ); ?></div>
            <div style="color: #64748b; font-size: 13px; margin-top: 4px;"><?php echo esc_html( $label ); ?></div>
        </div>
        <?php
    }

    /**
     * Get dashboard statistics.
     */
    private static function get_stats(): array {
        $current_month = current_time( 'Y-m' );

        $all_invoices = get_posts( [
            'post_type'      => GOFACTOX_Invoice::POST_TYPE,
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'fields'         => 'ids',
        ] );

        $total_amount = 0.0;
        $month_count  = 0;
        $month_total  = 0.0;

        foreach ( $all_invoices as $id ) {
            $ttc  = (float) get_post_meta( $id, '_gofactox_total_ttc', true );
            $date = get_post_meta( $id, '_gofactox_invoice_date', true );

            $total_amount += $ttc;

            if ( $date && str_starts_with( $date, $current_month ) ) {
                $month_count++;
                $month_total += $ttc;
            }
        }

        return [
            'total_count'  => count( $all_invoices ),
            'total_amount' => $total_amount,
            'month_count'  => $month_count,
            'month_total'  => $month_total,
        ];
    }

    /**
     * Get invoices for a given month.
     */
    private static function get_invoices( string $month ): array {
        $posts = get_posts( [
            'post_type'      => GOFACTOX_Invoice::POST_TYPE,
            'post_status'    => 'publish',
            'posts_per_page' => 100,
            'orderby'        => 'date',
            'order'          => 'DESC',
            'meta_query'     => [
                [
                    'key'     => '_gofactox_invoice_date',
                    'value'   => $month,
                    'compare' => 'LIKE',
                ],
            ],
        ] );

        $results = [];
        foreach ( $posts as $post ) {
            $order_id  = (int) get_post_meta( $post->ID, '_gofactox_order_id', true );
            $refund_id = (int) get_post_meta( $post->ID, '_gofactox_refund_id', true );
            $is_cn     = GOFACTOX_Invoice::is_credit_note( $post->ID );
            $order     = $order_id ? wc_get_order( $order_id ) : null;
            $refund    = $refund_id ? wc_get_order( $refund_id ) : null;
            $pdf_path  = GOFACTOX_Invoice::get_pdf_path( $post->ID );

            $customer = '-';
            if ( $order ) {
                $customer = trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() );
                if ( $order->get_billing_company() ) {
                    $customer = $order->get_billing_company() . ' (' . $customer . ')';
                }
            }

            // Credit notes are downloaded via /wfx-credit-note/{refund_id}/{token}/
            // (different route + different token than invoices).
            $download_url = '';
            if ( $is_cn && $refund instanceof \WC_Order_Refund ) {
                $download_url = GOFACTOX_Download::get_credit_note_download_url( $refund );
            } elseif ( ! $is_cn && $order instanceof \WC_Order ) {
                $download_url = GOFACTOX_Download::get_download_url( $order );
            }

            $results[] = [
                'id'             => $post->ID,
                'number'         => get_post_meta( $post->ID, '_gofactox_invoice_number', true ),
                'date'           => get_post_meta( $post->ID, '_gofactox_invoice_date', true ),
                'total'          => (float) get_post_meta( $post->ID, '_gofactox_total_ttc', true ),
                'is_credit_note' => $is_cn,
                'order'          => $order,
                'customer'       => $customer,
                'has_pdf'        => $pdf_path && file_exists( $pdf_path ),
                'download_url'   => $download_url,
            ];
        }

        return $results;
    }
}
