<?php
/**
 * FirewallCountryBlocking — Page scheme for the Country Blocking admin screen.
 *
 * Changes vs. original:
 *  - Added "Blocked / Listed Countries" table card showing every listed country
 *    with its active/disabled status and per-row Enable, Disable, Delete actions.
 *  - Fixed the third stat card to show "Active Entries" (counts only non-disabled).
 *  - Passes 'multiple' => true explicitly to country-selector.
 *  - get_country_names() loads the full 249-entry bundled JSON for table display.
 *
 * @package UltraguardPro\modules\firewall\pages
 */

namespace UltraguardPro\modules\firewall\pages;

use UltraguardPro\Plugin;
use UltraguardPro\modules\core\BasePage;

if ( ! defined( 'ABSPATH' ) ) { exit; }

class FirewallCountryBlocking extends BasePage {

    public function __construct( Plugin $plugin ) {
        parent::__construct( $plugin );
    }

    public function get_scheme( $context ): array {
        $mode      = \UltraguardPro\ultraguard_pro()->get_option( 'country_blocking_mode', 'none' );
        $countries = (array) \UltraguardPro\ultraguard_pro()->get_option( 'blocked_countries', [] );
        $disabled  = (array) \UltraguardPro\ultraguard_pro()->get_option( 'disabled_countries', [] );

        $mode_text = $mode === 'blacklist'
            ? __( 'Blacklist Mode', 'ultraguard-security-suite' )
            : ( $mode === 'whitelist'
                ? __( 'Whitelist Mode', 'ultraguard-security-suite' )
                : __( 'Disabled', 'ultraguard-security-suite' ) );

        $mode_badge = $mode === 'blacklist' ? 'danger' : ( $mode === 'whitelist' ? 'success' : 'secondary' );

        $country_names = $this->get_country_names();
        $country_rows  = $this->build_country_rows( $countries, $disabled, $country_names );

        $active_count = count( array_diff( $countries, $disabled ) );

        return apply_filters( 'ultraguard_country_blocking_scheme', [
            'type'      => 'page',
            'id'        => 'ultraguard-country-blocking',
            'page_slug' => 'firewall-country-blocking',
            'class'     => 'ultraguard-country-blocking-page',

            // ── Page header ──────────────────────────────────────────────────
            'header' => [
                'title'    => __( 'Country Blocking', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Block or allow traffic based on geographic location', 'ultraguard-security-suite' ),
                'badge'    => [ 'text' => $mode_text, 'badge_type' => $mode_badge ],
                'actions'  => [
                    $this->create_ajax_button( __( 'Refresh Stats', 'ultraguard-security-suite' ), 'ultraguard_refresh_country_stats', [], 'secondary', 'dashicons-update'   ),
                    $this->create_ajax_button( __( 'Test Blocking',  'ultraguard-security-suite' ), 'ultraguard_test_country_blocking',  [], 'secondary', 'dashicons-yes'      ),
                    $this->create_ajax_button( __( 'Export List',    'ultraguard-security-suite' ), 'ultraguard_export_country_list',    [], 'secondary', 'dashicons-download' ),
                ],
            ],

            'data' => [

                // ── Stat cards ───────────────────────────────────────────────
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [
                            'span'      => 4,
                            'component' => [
                                'type'   => 'stat-card',
                                'title'  => __( 'Blocking Mode', 'ultraguard-security-suite' ),
                                'value'  => $mode_text,
                                'format' => 'text',
                                'icon'   => 'dashicons-location-alt',
                                'class'  => $mode !== 'none' ? 'warning' : 'secondary',
                            ],
                        ],
                        [
                            'span'      => 4,
                            'component' => [
                                'type'   => 'stat-card',
                                'title'  => __( 'Countries Listed', 'ultraguard-security-suite' ),
                                'value'  => count( $countries ),
                                'format' => 'number',
                                'icon'   => 'dashicons-admin-site',
                                'class'  => 'info',
                            ],
                        ],
                        [
                            'span'      => 4,
                            'component' => [
                                'type'   => 'stat-card',
                                'title'  => __( 'Active Entries', 'ultraguard-security-suite' ),
                                'value'  => $active_count,
                                'format' => 'number',
                                'icon'   => 'dashicons-shield',
                                'class'  => $active_count > 0 ? 'success' : 'secondary',
                            ],
                        ],
                    ],
                ],

                // ── Blocking Configuration + Bulk Add ───────────────────────
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '20px',
                    'items'   => [
                        [
                            'span'      => 7,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Blocking Configuration', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-admin-site-alt3',
                                'data'  => [
                                    [
                                        'type'    => 'select',
                                        'name'    => 'blocking_mode',
                                        'label'   => __( 'Blocking Mode', 'ultraguard-security-suite' ),
                                        'options' => [
                                            'none'      => __( 'Disabled', 'ultraguard-security-suite' ),
                                            'blacklist' => __( 'Blacklist (block listed countries)', 'ultraguard-security-suite' ),
                                            'whitelist' => __( 'Whitelist (only allow listed countries)', 'ultraguard-security-suite' ),
                                        ],
                                        'default' => $mode,
                                    ],
                                    [
                                        'type'        => 'country-selector',
                                        'name'        => 'countries',
                                        'label'       => __( 'Countries', 'ultraguard-security-suite' ),
                                        'description' => __( 'Select countries to block or allow depending on the mode above.', 'ultraguard-security-suite' ),
                                        'default'     => $countries,
                                        'multiple'    => true,
                                        'size'        => 10,
                                    ],
                                ],
                                'footer' => [
                                    'type'      => 'button-group',
                                    'alignment' => 'right',
                                    'buttons'   => [
                                        $this->create_ajax_button(
                                            __( 'Save Country Settings', 'ultraguard-security-suite' ),
                                            'ultraguard_save_country_settings',
                                            [ 'module' => 'country' ],
                                            'primary',
                                            'dashicons-saved'
                                        ),
                                    ],
                                ],
                            ],
                        ],
                        [
                            'span'      => 5,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Bulk Add by Region', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-admin-site',
                                'data'  => [ [
                                    'type'      => 'button-group',
                                    'alignment' => 'center',
                                    'buttons'   => [
                                        $this->create_ajax_button(
                                            __( 'Add Europe', 'ultraguard-security-suite' ),
                                            'ultraguard_bulk_add_countries',
                                            [ 'region' => 'eu' ],
                                            'secondary',
                                            'dashicons-location',
                                            __( 'Add all EU countries to the list?', 'ultraguard-security-suite' )
                                        ),
                                        $this->create_ajax_button(
                                            __( 'Add APAC', 'ultraguard-security-suite' ),
                                            'ultraguard_bulk_add_countries',
                                            [ 'region' => 'apac' ],
                                            'secondary',
                                            'dashicons-location',
                                            __( 'Add all APAC countries to the list?', 'ultraguard-security-suite' )
                                        ),
                                        $this->create_ajax_button(
                                            __( 'Add Americas', 'ultraguard-security-suite' ),
                                            'ultraguard_bulk_add_countries',
                                            [ 'region' => 'americas' ],
                                            'secondary',
                                            'dashicons-location',
                                            __( 'Add all Americas countries to the list?', 'ultraguard-security-suite' )
                                        ),
                                        $this->create_ajax_button(
                                            __( 'Add Africa', 'ultraguard-security-suite' ),
                                            'ultraguard_bulk_add_countries',
                                            [ 'region' => 'africa' ],
                                            'secondary',
                                            'dashicons-location',
                                            __( 'Add all Africa countries to the list?', 'ultraguard-security-suite' )
                                        ),
                                    ],
                                ] ],
                            ],
                        ],
                    ],
                ],

                // ── Blocked / Listed Countries Table ─────────────────────────
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '20px',
                    'items'   => [
                        [
                            'span'      => 12,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Blocked / Listed Countries', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-shield-alt',
                                'data'  => [ $this->blocked_countries_table( $country_rows ) ],
                            ],
                        ],
                    ],
                ],

            ],

            'form' => [ 'enable' => false ],
        ], $context );
    }

    // =========================================================================
    // PRIVATE HELPERS
    // =========================================================================

    /**
     * Build the table component or an empty-state notice.
     *
     * @param  array $rows  Pre-built row data from build_country_rows().
     * @return array        A 'data-table' or 'notice' component scheme.
     */
    private function blocked_countries_table( array $rows ): array {
        return [
            'type'       => 'data-table',
            'id'         => 'blocked-countries-table',
            'columns'    => [
                'country_code' => [ 'title' => __( 'Code',    'ultraguard-security-suite' ), 'sortable' => true  ],
                'country_name' => [ 'title' => __( 'Country', 'ultraguard-security-suite' ), 'sortable' => true  ],
                'status'       => [ 'title' => __( 'Status',  'ultraguard-security-suite' ), 'sortable' => false ],
                'actions'      => [ 'title' => __( 'Actions', 'ultraguard-security-suite' ), 'width'    => '160px' ],
            ],
            'data'       => $rows,
            'searchable' => true,
            'pagination' => [ 'enabled' => true, 'page_size' => 20 ],
            'empty_state' => [
                'title'       => __( 'No countries listed', 'ultraguard-security-suite' ),
                'description' => __( 'Use the configuration above to add countries, then save.', 'ultraguard-security-suite' ),
            ],
        ];
    }

    /**
     * Convert the raw $countries array into table row data.
     *
     * @param  string[] $countries     All country codes in the list.
     * @param  string[] $disabled      Subset of codes that are currently disabled.
     * @param  array    $country_names Map of code => display name.
     * @return array[]
     */
    private function build_country_rows( array $countries, array $disabled, array $country_names ): array {
        $rows = [];

        foreach ( $countries as $raw_code ) {
            $code      = strtoupper( (string) $raw_code );
            $is_active = ! in_array( $code, $disabled, true );

            $rows[] = [
                'country_code' => $code,
                'country_name' => $country_names[ $code ] ?? $code,
                'status'       => $is_active
                    ? __( 'Active',   'ultraguard-security-suite' )
                    : __( 'Disabled', 'ultraguard-security-suite' ),
                'is_active'    => $is_active,
                'actions'      => $this->row_actions( ['code'=>$code,'toggle'=>$is_active] ),
            ];
        }

        return $rows;
    }

    /**
     * Build per-row action buttons (Enable/Disable toggle + Delete).
     *
     * @param  string $code       ISO 3166-1 alpha-2 country code.
     * @param  bool   $is_active  Whether the entry is currently enforced.
     * @return array              button-group component scheme.
     */
    protected function row_actions(array $data ): array {
        $code = $data['code'];
        $toggle_btn = $data['toggle']
            ? $this->create_ajax_button(
                __( 'Disable', 'ultraguard-security-suite' ),
                'ultraguard_toggle_country_status',
                [ 'country_code' => $code, 'set_active' => 0 ],
                'secondary',
                'dashicons-hidden',
                sprintf(
                    /* translators: Placeholder values are inserted into this string. */
                    __( 'Temporarily disable %s? It stays in the list but will not be enforced.', 'ultraguard-security-suite' ),
                    $code
                )
              )
            : $this->create_ajax_button(
                __( 'Enable', 'ultraguard-security-suite' ),
                'ultraguard_toggle_country_status',
                [ 'country_code' => $code, 'set_active' => 1 ],
                'success',
                'dashicons-visibility'
              );

        $delete_btn = $this->create_ajax_button(
            __( 'Delete', 'ultraguard-security-suite' ),
            'ultraguard_unblock_country',
            [ 'country_code' => $code ],
            'danger',
            'dashicons-trash',
            /* translators: %s: string */
            sprintf( __( 'Permanently remove %s from the list?', 'ultraguard-security-suite' ), $code )
        );

        return parent::row_actions( [ $toggle_btn, $delete_btn ] );
    }

    /**
     * Load the full ISO 3166-1 country name map from the bundled JSON file.
     *
     * Falls back gracefully to WooCommerce or a minimal hard-coded list if the
     * JSON file is not present (e.g. during development / unit tests).
     *
     * @return array<string,string>  [ 'US' => 'United States', … ]
     */
    private function get_country_names(): array {
        $json_path = defined( 'ULTRAGUARD_PRO_DIR' )
            ? trailingslashit( ULTRAGUARD_PRO_DIR ) . 'assets/json/country-codes.json'
            : '';

        if ( $json_path && file_exists( $json_path ) ) {
            $raw  = json_decode( file_get_contents( $json_path ), true ); // phpcs:ignore
            $map  = [];
            foreach ( $raw['countries'] ?? [] as $entry ) {
                $map[ strtoupper( (string) $entry['code'] ) ] = (string) $entry['name'];
            }
            if ( ! empty( $map ) ) {
                return $map;
            }
        }

        if ( function_exists( 'WC' ) && class_exists( 'WC_Countries' ) ) {
            return ( new \WC_Countries() )->get_countries();
        }

        // Minimal fallback — enough for the table to render without the JSON file.
        return [
            'US' => 'United States', 'GB' => 'United Kingdom', 'CA' => 'Canada',
            'AU' => 'Australia',     'IN' => 'India',          'DE' => 'Germany',
            'FR' => 'France',        'JP' => 'Japan',          'CN' => 'China',
            'BR' => 'Brazil',        'RU' => 'Russia',         'NG' => 'Nigeria',
            'ZA' => 'South Africa',  'EG' => 'Egypt',          'KE' => 'Kenya',
        ];
    }
}
