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

class PBUAIV_Admin {

    private static ?PBUAIV_Admin $instance = null;

    public static function instance() : self {
        if ( null === self::$instance ) self::$instance = new self();
        return self::$instance;
    }

    private function __construct() {
        add_action( 'admin_menu',            [ $this, 'register_menu'  ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue'        ] );
        add_action( 'admin_init',            [ $this, 'maybe_redirect' ] );
        add_action( 'admin_init',            [ $this, 'maybe_export_report' ] );
        // Bulk actions on Orders list
        add_filter( 'bulk_actions-edit-shop_order',             [ $this, 'register_bulk_actions' ] );
        add_filter( 'bulk_actions-woocommerce_page_wc-orders',  [ $this, 'register_bulk_actions' ] );
        add_filter( 'handle_bulk_actions-edit-shop_order',            [ $this, 'handle_bulk_actions' ], 10, 3 );
        add_filter( 'handle_bulk_actions-woocommerce_page_wc-orders', [ $this, 'handle_bulk_actions' ], 10, 3 );
        // Orders list columns
        add_filter( 'manage_edit-shop_order_columns',            [ $this, 'add_order_columns' ] );
        add_filter( 'manage_woocommerce_page_wc-orders_columns', [ $this, 'add_order_columns' ] );
        add_action( 'manage_shop_order_posts_custom_column',         [ $this, 'render_order_column' ], 10, 2 );
        add_action( 'manage_woocommerce_page_wc-orders_custom_column',[ $this, 'render_order_column' ], 10, 2 );
        // Dompdf is bundled — no runtime check needed
    }

    // ── Redirect to onboarding ─────────────────────────────────────────────────

    public function maybe_redirect() : void {
        if ( get_transient( 'pbuaiv_activation_redirect' ) && ! get_option( 'pbuaiv_onboarding_done' ) ) {
            delete_transient( 'pbuaiv_activation_redirect' );
            wp_safe_redirect( admin_url( 'admin.php?page=pbuaiv-setup' ) );
            exit;
        }
    }

    // ── Menu ──────────────────────────────────────────────────────────────────

    public function register_menu() : void {
        $icon = $this->menu_icon();

        add_menu_page(
            __( 'UAE VAT Invoice', 'pb-invoicing-system' ),
            __( 'UAE Invoices', 'pb-invoicing-system' ),
            'manage_woocommerce',
            'pbuaiv-settings',
            [ $this, 'page_settings' ],
            $icon,
            56
        );
        add_submenu_page( 'pbuaiv-settings', __( 'Settings', 'pb-invoicing-system' ),    __( 'Settings', 'pb-invoicing-system' ),    'manage_woocommerce', 'pbuaiv-settings',  [ $this, 'page_settings'  ] );
        add_submenu_page( 'pbuaiv-settings', __( 'Documents', 'pb-invoicing-system' ),   __( 'Documents', 'pb-invoicing-system' ),   'manage_woocommerce', 'pbuaiv-documents', [ $this, 'page_documents' ] );
        add_submenu_page( 'pbuaiv-settings', __( 'Templates', 'pb-invoicing-system' ),   __( 'Templates', 'pb-invoicing-system' ),   'manage_woocommerce', 'pbuaiv-templates', [ $this, 'page_templates' ] );
        add_submenu_page( 'pbuaiv-settings', __( 'VAT Reports', 'pb-invoicing-system' ), __( 'VAT Reports', 'pb-invoicing-system' ), 'manage_woocommerce', 'pbuaiv-reports',   [ $this, 'page_reports'   ] );
        add_submenu_page( 'pbuaiv-settings', __( 'Setup Wizard', 'pb-invoicing-system' ),__( 'Setup Wizard', 'pb-invoicing-system' ),'manage_woocommerce', 'pbuaiv-setup',     [ $this, 'page_setup'     ] );
    }

    // ── Pages ─────────────────────────────────────────────────────────────────

    public function page_settings()  : void { include PBUAIV_PLUGIN_DIR . 'admin/views/settings.php';   }
    public function page_documents() : void { include PBUAIV_PLUGIN_DIR . 'admin/views/documents.php';  }
    public function page_templates() : void { include PBUAIV_PLUGIN_DIR . 'admin/views/templates.php';  }
    public function page_reports()   : void { include PBUAIV_PLUGIN_DIR . 'admin/views/reports.php';    }
    public function page_setup()     : void { include PBUAIV_PLUGIN_DIR . 'admin/views/onboarding.php'; }

    // ── Assets ────────────────────────────────────────────────────────────────

    public function enqueue( string $hook ) : void {
        $our_hooks = [
            'toplevel_page_pbuaiv-settings',
            'uae-invoices_page_pbuaiv-documents',
            'uae-invoices_page_pbuaiv-templates',
            'uae-invoices_page_pbuaiv-reports',
            'uae-invoices_page_pbuaiv-setup',
            'woocommerce_page_wc-orders',
            'edit.php',
            'post.php',
            'post-new.php',
        ];
        $on_our_page = in_array( $hook, $our_hooks, true ) || strpos( $hook, 'wui' ) !== false;
        $on_order    = in_array( $hook, [ 'woocommerce_page_wc-orders', 'edit.php', 'post.php' ] );

        if ( ! $on_our_page && ! $on_order ) return;

        wp_enqueue_style(
            'pbuaiv-admin',
            PBUAIV_PLUGIN_URL . 'admin/css/admin.css',
            [],
            PBUAIV_VERSION
        );

        wp_enqueue_script(
            'pbuaiv-admin',
            PBUAIV_PLUGIN_URL . 'admin/js/admin.js',
            [ 'jquery', 'wp-color-picker' ],
            PBUAIV_VERSION,
            true
        );
        wp_enqueue_style( 'wp-color-picker' );

        wp_localize_script( 'pbuaiv-admin', 'PBUAIV', [
            'ajax_url' => admin_url( 'admin-ajax.php' ),
            'nonce'    => wp_create_nonce( 'pbuaiv_admin' ),
            'i18n'     => [
                'confirm_issue'  => __( 'Issue this document? This will assign a permanent number.', 'pb-invoicing-system' ),
                'confirm_void'   => __( 'Void this document? This cannot be undone.', 'pb-invoicing-system' ),
                'confirm_send'   => __( 'Send this document to the customer by email?', 'pb-invoicing-system' ),
                'issuing'        => __( 'Issuing...', 'pb-invoicing-system' ),
                'sending'        => __( 'Sending...', 'pb-invoicing-system' ),
                'done'           => __( 'Done!', 'pb-invoicing-system' ),
                'error'          => __( 'An error occurred. Please try again.', 'pb-invoicing-system' ),
            ],
        ] );

        // Media uploader for logo
        if ( $on_our_page ) {
            wp_enqueue_media();
        }
    }

    // ── Bulk Actions ──────────────────────────────────────────────────────────

    public function register_bulk_actions( array $actions ) : array {
        $actions['pbuaiv_generate_invoices'] = __( 'Generate Invoices (UAE)', 'pb-invoicing-system' );
        $actions['pbuaiv_generate_receipts'] = __( 'Generate Receipts (UAE)', 'pb-invoicing-system' );
        $actions['pbuaiv_download_invoices'] = __( 'Download Invoices ZIP', 'pb-invoicing-system' );
        return $actions;
    }

    public function handle_bulk_actions( string $redirect, string $action, array $ids ) : string {
        if ( strpos( $action, 'pbuaiv_' ) !== 0 ) return $redirect;

        switch ( $action ) {
            case 'pbuaiv_generate_invoices':
                foreach ( $ids as $id ) {
                    $order   = wc_get_order( (int) $id );
                    if ( ! $order ) continue;
                    $invoice = new PBUAIV_Invoice( $order );
                    if ( ! $invoice->is_issued() ) $invoice->issue();
                }
                $redirect = add_query_arg( 'pbuaiv_bulk_done', 'invoices', $redirect );
                break;

            case 'pbuaiv_generate_receipts':
                foreach ( $ids as $id ) {
                    $order   = wc_get_order( (int) $id );
                    if ( ! $order ) continue;
                    $receipt = new PBUAIV_Receipt( $order );
                    if ( ! $receipt->is_issued() ) $receipt->issue();
                }
                $redirect = add_query_arg( 'pbuaiv_bulk_done', 'receipts', $redirect );
                break;

            case 'pbuaiv_download_invoices':
                $this->bulk_download_zip( $ids, 'invoice' );
                break;
        }
        return $redirect;
    }

    private function bulk_download_zip( array $ids, string $doc_type ) : void {
        if ( ! class_exists( 'ZipArchive' ) ) {
            wp_die( esc_html__( 'ZipArchive PHP extension required for bulk downloads.', 'pb-invoicing-system' ) );
        }

        $zip_file = sys_get_temp_dir() . '/pbuaiv-bulk-' . time() . '.zip';
        $zip      = new ZipArchive();
        $zip->open( $zip_file, ZipArchive::CREATE );

        foreach ( $ids as $id ) {
            $order = wc_get_order( (int) $id );
            if ( ! $order ) continue;
            $doc = PBUAIV_Email_Manager::factory( $doc_type, $order );
            if ( ! $doc || ! $doc->is_issued() ) continue;
            $pdf = $doc->get_pdf();
            if ( $pdf ) {
                $zip->addFromString( $doc->get_pdf_filename(), $pdf );
            }
        }

        $zip->close();

        header( 'Content-Type: application/zip' );
        header( 'Content-Disposition: attachment; filename="pbuaiv-invoices-' . wp_date( 'Ymd' ) . '.zip"' );
        header( 'Content-Length: ' . filesize( $zip_file ) );
        if ( ! function_exists( 'WP_Filesystem' ) ) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }
        WP_Filesystem();
        global $wp_filesystem;
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- binary ZIP streamed to browser
        echo $wp_filesystem->get_contents( $zip_file );
        wp_delete_file( $zip_file );
        exit;
    }

    // ── Order List Columns ────────────────────────────────────────────────────

    public function add_order_columns( array $columns ) : array {
        $new      = [];
        $inserted = false;
        foreach ( $columns as $key => $label ) {
            $new[ $key ] = $label;
            // Insert after order_status (classic) or wc_actions (HPOS fallback)
            if ( ! $inserted && in_array( $key, [ 'order_status', 'wc_actions', 'order_total' ], true ) ) {
                $new['pbuaiv_invoice'] = __( 'Invoice', 'pb-invoicing-system' );
                $new['pbuaiv_receipt'] = __( 'Receipt', 'pb-invoicing-system' );
                $inserted = true;
            }
        }
        // Fallback: append if no anchor column found
        if ( ! $inserted ) {
            $new['pbuaiv_invoice'] = __( 'Invoice', 'pb-invoicing-system' );
            $new['pbuaiv_receipt'] = __( 'Receipt', 'pb-invoicing-system' );
        }
        return $new;
    }

    public function render_order_column( string $column, $post_id_or_order ) : void {
        if ( ! in_array( $column, [ 'pbuaiv_invoice', 'pbuaiv_receipt' ], true ) ) return;

        try {
            $order_id = is_object( $post_id_or_order ) ? $post_id_or_order->get_id() : (int) $post_id_or_order;
            $order    = wc_get_order( $order_id );
            if ( ! $order ) {
                echo '<span class="pbuaiv-doc-badge pbuaiv-doc-badge--none">—</span>';
                return;
            }

            $doc_type = $column === 'pbuaiv_invoice' ? 'invoice' : 'receipt';
            $doc      = PBUAIV_Email_Manager::factory( $doc_type, $order );

            if ( $doc && $doc->is_issued() ) {
                $record = $doc->get_db_record();
                $url    = PBUAIV_Download_Handler::get_url( $order_id, $doc_type, 'view' );
                $number = esc_html( $record->doc_number );
                $status = esc_attr( $record->status ?: 'issued' );
                echo '<a href="' . esc_url( $url ) . '" target="_blank" class="pbuaiv-doc-badge pbuaiv-doc-badge--' . esc_attr( $status ) . '" title="' . esc_attr( $number ) . '">';
                echo '<span class="dashicons dashicons-media-document" style="font-size:12px;width:12px;height:12px;margin-right:2px;"></span> ' . esc_html( $number );
                echo '</a>';
            } else {
                echo '<span class="pbuaiv-doc-badge pbuaiv-doc-badge--none" style="color:#94a3b8;">—</span>';
            }
        } catch ( \Throwable $e ) {
            echo '<span class="pbuaiv-doc-badge pbuaiv-doc-badge--none">—</span>';
        }
    }


    // ── VAT report export ─────────────────────────────────────────────────────

    public function maybe_export_report() : void {
        // phpcs:disable WordPress.Security.NonceVerification.Recommended
        if ( empty( $_GET['pbuaiv_export'] ) ) {
            return;
        }

        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_die( esc_html__( 'You do not have permission to export VAT reports.', 'pb-invoicing-system' ) );
        }

        $nonce = isset( $_GET['nonce'] ) ? sanitize_text_field( wp_unslash( $_GET['nonce'] ) ) : '';
        if ( ! wp_verify_nonce( $nonce, 'pbuaiv_export' ) ) {
            wp_die( esc_html__( 'Invalid export link.', 'pb-invoicing-system' ) );
        }

        $type = sanitize_key( wp_unslash( $_GET['pbuaiv_export'] ) );
        $from = sanitize_text_field( wp_unslash( $_GET['from'] ?? wp_date( 'Y-m-01' ) ) );
        $to   = sanitize_text_field( wp_unslash( $_GET['to'] ?? wp_date( 'Y-m-d' ) ) );
        // phpcs:enable

        if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $from ) ) {
            $from = wp_date( 'Y-m-01' );
        }
        if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $to ) ) {
            $to = wp_date( 'Y-m-d' );
        }

        if ( 'csv' === $type ) {
            $this->export_vat_csv( $from, $to );
        }

        if ( 'xml_bulk' === $type ) {
            $this->export_vat_xml_bulk( $from, $to );
        }
    }

    private function export_vat_csv( string $from, string $to ) : void {
        $orders = wc_get_orders( [
            'limit'        => -1,
            'type'         => 'shop_order',
            'date_created' => $from . ' 00:00:00...' . $to . ' 23:59:59',
            'return'       => 'objects',
            'status'       => array_keys( wc_get_order_statuses() ),
        ] );

        nocache_headers();
        header( 'Content-Type: text/csv; charset=UTF-8' );
        header( 'Content-Disposition: attachment; filename="pbuaiv-vat-summary-' . sanitize_file_name( $from . '-to-' . $to ) . '.csv"' );

        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- streaming CSV to browser output.
        $out = fopen( 'php://output', 'w' );
        if ( false === $out ) {
            wp_die( esc_html__( 'Unable to create CSV export.', 'pb-invoicing-system' ) );
        }

        fputcsv( $out, [ 'Order ID', 'Order Number', 'Order Date', 'Customer', 'Currency', 'Subtotal Ex VAT', 'VAT Amount', 'Total', 'Status' ] );

        foreach ( $orders as $order ) {
            if ( ! $order instanceof WC_Order ) {
                continue;
            }

            $total = (float) $order->get_total();
            $vat   = (float) $order->get_total_tax();

            fputcsv( $out, [
                $order->get_id(),
                $order->get_order_number(),
                $order->get_date_created() ? $order->get_date_created()->date_i18n( 'Y-m-d' ) : '',
                trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() ),
                $order->get_currency(),
                number_format( max( 0, $total - $vat ), 2, '.', '' ),
                number_format( $vat, 2, '.', '' ),
                number_format( $total, 2, '.', '' ),
                $order->get_status(),
            ] );
        }

        // php://output is closed automatically at request end; no fclose() needed for Plugin Check compatibility.
        exit;
    }

    private function export_vat_xml_bulk( string $from, string $to ) : void {
        $orders = wc_get_orders( [
            'limit'        => -1,
            'type'         => 'shop_order',
            'date_created' => $from . ' 00:00:00...' . $to . ' 23:59:59',
            'return'       => 'objects',
            'status'       => array_keys( wc_get_order_statuses() ),
        ] );

        $xml = new SimpleXMLElement( '<pbuaiv_vat_report />' );
        $xml->addChild( 'from', esc_html( $from ) );
        $xml->addChild( 'to', esc_html( $to ) );
        $orders_node = $xml->addChild( 'orders' );

        foreach ( $orders as $order ) {
            if ( ! $order instanceof WC_Order ) {
                continue;
            }
            $order_node = $orders_node->addChild( 'order' );
            $order_node->addChild( 'id', (string) $order->get_id() );
            $order_node->addChild( 'number', esc_html( $order->get_order_number() ) );
            $order_node->addChild( 'date', $order->get_date_created() ? esc_html( $order->get_date_created()->date_i18n( 'Y-m-d' ) ) : '' );
            $order_node->addChild( 'currency', esc_html( $order->get_currency() ) );
            $order_node->addChild( 'vat_amount', number_format( (float) $order->get_total_tax(), 2, '.', '' ) );
            $order_node->addChild( 'total', number_format( (float) $order->get_total(), 2, '.', '' ) );
        }

        nocache_headers();
        header( 'Content-Type: application/xml; charset=UTF-8' );
        header( 'Content-Disposition: attachment; filename="pbuaiv-vat-report-' . sanitize_file_name( $from . '-to-' . $to ) . '.xml"' );
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- XML document output.
        echo $xml->asXML();
        exit;
    }

    // ── Menu icon (invoice SVG) ────────────────────────────────────────────────

    private function menu_icon() : string {
        $svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="none"><rect x="3" y="1" width="11" height="14" rx="1.5" stroke="black" stroke-width="1.5"/><path d="M5 5h7M5 8h7M5 11h4" stroke="black" stroke-width="1.2" stroke-linecap="round"/><rect x="9" y="12" width="8" height="7" rx="1" fill="white" stroke="black" stroke-width="1"/><path d="M11 14h4M11 16h2" stroke="black" stroke-width="1" stroke-linecap="round"/></svg>';
        return 'data:image/svg+xml;base64,' . base64_encode( $svg );
    }
}
