<?php
$current_plan = (string) ( $state['current_plan'] ?? 'free' );
$current_status = (string) ( $state['current_status'] ?? 'unregistered' );
$is_paid_plan = in_array( $current_plan, array( 'pro', 'enterprise' ), true );
$has_paid_access = $is_paid_plan || ! empty( $state['legacy_paid_license'] );
$v2_enabled = ! empty( $state['enabled'] );
$checkout_available = $v2_enabled
    && ! empty( $state['installation_uuid'] )
    && ! empty( $state['has_api_key'] );
$legacy_api_key = trim( (string) get_option( 'nip_finder_api_key', '' ) );
?>
<div class="wrap nip-finder-admin">
    <h1><?php esc_html_e( 'NIP Finder', 'nip-finder' ); ?></h1>

    <?php if ( ! $v2_enabled ) : ?>
        <div class="notice notice-info">
            <p><?php esc_html_e( 'Nowe API licencyjne v2 zostało wyłączone konfiguracją. Dotychczasowy mechanizm licencji pozostaje aktywny.', 'nip-finder' ); ?></p>
        </div>
    <?php elseif ( ! empty( $checkoutError ) ) : ?>
        <div class="notice notice-error">
            <p><?php echo esc_html( (string) $checkoutError ); ?></p>
        </div>
    <?php elseif ( ! empty( $state['warning_visible'] ) && ! empty( $state['last_error_message'] ) ) : ?>
        <div class="notice notice-error">
            <p><strong><?php esc_html_e( 'Ostatni błąd integracji:', 'nip-finder' ); ?></strong> <?php echo esc_html( $state['last_error_message'] ); ?></p>
        </div>
    <?php endif; ?>

    <div class="nip-finder-admin__grid">
        <section class="nip-finder-admin__card">
            <h2><?php esc_html_e( 'Status instalacji', 'nip-finder' ); ?></h2>

            <table class="widefat striped">
                <tbody>
                <tr>
                    <td><?php esc_html_e( 'Installation UUID', 'nip-finder' ); ?></td>
                    <td><code><?php echo esc_html( (string) $state['installation_uuid'] ); ?></code></td>
                </tr>
                <tr>
                    <td><?php esc_html_e( 'Status', 'nip-finder' ); ?></td>
                    <td><span class="nip-finder-admin__badge nip-finder-admin__badge--<?php echo esc_attr( $statusBadge['class'] ); ?>"><?php echo esc_html( $statusBadge['label'] ); ?></span></td>
                </tr>
                <tr>
                    <td><?php esc_html_e( 'Plan', 'nip-finder' ); ?></td>
                    <td><?php echo esc_html( strtoupper( $current_plan ) ); ?></td>
                </tr>
                <tr>
                    <td><?php esc_html_e( 'Plan aktywny od', 'nip-finder' ); ?></td>
                    <td><?php echo esc_html( $this->format_datetime( (string) $state['plan_started_at'] ) ); ?></td>
                </tr>
                <tr>
                    <td><?php esc_html_e( 'Plan aktywny do', 'nip-finder' ); ?></td>
                    <td><?php echo esc_html( $this->format_datetime( (string) $state['plan_expires_at'] ) ); ?></td>
                </tr>
                <tr>
                    <td><?php esc_html_e( 'Ostatnia synchronizacja', 'nip-finder' ); ?></td>
                    <td><?php echo esc_html( $this->format_datetime( (string) $state['last_heartbeat_at'] ) ); ?></td>
                </tr>
                <tr>
                    <td><?php esc_html_e( 'Ostatni poprawny kontakt z API', 'nip-finder' ); ?></td>
                    <td><?php echo esc_html( $this->format_datetime( (string) $state['last_heartbeat_at'] ) ); ?></td>
                </tr>
            </tbody>
            </table>
        </section>

        <section class="nip-finder-admin__card">
            <h2><?php esc_html_e( 'Rejestracja instalacji', 'nip-finder' ); ?></h2>

            <?php if ( $checkout_available ) : ?>
                <p><?php esc_html_e( 'Instalacja jest poprawnie zarejestrowana i może utworzyć bezpieczną sesję checkoutu.', 'nip-finder' ); ?></p>
            <?php else : ?>
                <p><?php esc_html_e( 'Zakup planu będzie dostępny po zapisaniu identyfikatora instalacji i klucza API.', 'nip-finder' ); ?></p>
            <?php endif; ?>

            <p>
                <strong><?php esc_html_e( 'Klucz API instalacji:', 'nip-finder' ); ?></strong>
                <?php echo ! empty( $state['api_key_masked'] ) ? esc_html( (string) $state['api_key_masked'] ) : esc_html__( 'Brak danych', 'nip-finder' ); ?>
            </p>

            <div class="nip-finder-admin__actions">
                <button type="button" id="btn-nip-finder-refresh-status" class="button button-secondary" <?php disabled( ! $v2_enabled ); ?>><?php esc_html_e( 'Odśwież status', 'nip-finder' ); ?></button>
            </div>
        </section>

        <section class="nip-finder-admin__card nip-finder-admin__card--wide">
            <h2><?php esc_html_e( 'Licencja / Plan', 'nip-finder' ); ?></h2>

            <p><strong><?php esc_html_e( 'Aktualny plan:', 'nip-finder' ); ?></strong> <?php echo esc_html( strtoupper( $current_plan ) ); ?></p>

            <?php if ( $has_paid_access ) : ?>
                <p><button type="button" class="button button-secondary" disabled="disabled"><?php esc_html_e( 'Plan aktywny', 'nip-finder' ); ?></button></p>
            <?php else : ?>
                <p><?php esc_html_e( 'Plan Free pozwala korzystać z podstawowej integracji. Aby włączyć premium dla tej konkretnej instalacji, wybierz plan i przejdź do checkoutu.', 'nip-finder' ); ?></p>
                <?php if ( ! empty( $plans[0]['fallback'] ) ) : ?>
                    <p class="description"><?php esc_html_e( 'Aktualny katalog planów jest chwilowo niedostępny. Wyświetlane są informacje awaryjne bez cen.', 'nip-finder' ); ?></p>
                <?php endif; ?>
                <ul class="nip-finder-admin__feature-list">
                    <?php foreach ( $plans as $plan ) : ?>
                        <?php if ( ! empty( $plan['is_free'] ) ) { continue; } ?>
                        <li>
                            <strong><?php echo esc_html( (string) $plan['name'] ); ?>:</strong>
                            <?php echo esc_html( (string) $plan['description'] ); ?>
                            <?php if ( empty( $plan['fallback'] ) ) : ?>
                                <?php
                                $monthlyPrice = number_format_i18n( (int) $plan['monthly_price'] / 100, 2 );
                                $yearlyPrice = number_format_i18n( (int) $plan['yearly_price'] / 100, 2 );
                                ?>
                                <span>
                                    <?php
                                    echo esc_html(
                                        sprintf(
                                            __( '%1$s %3$s / miesiąc, %2$s %3$s / rok', 'nip-finder' ),
                                            $monthlyPrice,
                                            $yearlyPrice,
                                            (string) $plan['currency']
                                        )
                                    );
                                    ?>
                                </span>
                            <?php endif; ?>
                        </li>
                    <?php endforeach; ?>
                </ul>
                <form
                    id="nip-finder-checkout-form"
                    class="nip-finder-admin__actions"
                    method="post"
                    action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"
                >
                    <input type="hidden" name="action" value="nip_finder_create_checkout" />
                    <?php wp_nonce_field( 'nip_finder_create_checkout', 'nip_finder_checkout_nonce' ); ?>
                    <label for="nip-finder-plan-select" class="screen-reader-text"><?php esc_html_e( 'Wybierz plan premium', 'nip-finder' ); ?></label>
                    <select id="nip-finder-plan-select" name="plan">
                        <?php foreach ( $plans as $plan ) : ?>
                            <?php if ( ! empty( $plan['is_free'] ) ) { continue; } ?>
                            <option value="<?php echo esc_attr( (string) $plan['code'] ); ?>">
                                <?php echo esc_html( (string) $plan['name'] ); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <label for="nip-finder-billing-frequency-select" class="screen-reader-text"><?php esc_html_e( 'Wybierz okres rozliczeniowy', 'nip-finder' ); ?></label>
                    <select id="nip-finder-billing-frequency-select" name="billing_frequency">
                        <option value="MONTHLY"><?php esc_html_e( 'Miesięcznie', 'nip-finder' ); ?></option>
                        <option value="YEARLY"><?php esc_html_e( 'Rocznie', 'nip-finder' ); ?></option>
                    </select>
                    <button
                        type="submit"
                        id="btn-nip-finder-create-checkout"
                        data-default-plan="pro"
                        data-default-billing-frequency="MONTHLY"
                        class="button button-primary"
                        <?php disabled( ! $checkout_available ); ?>
                    ><?php esc_html_e( 'Kup premium', 'nip-finder' ); ?></button>
                </form>
                <?php if ( ! $checkout_available ) : ?>
                    <p class="description"><?php esc_html_e( 'Najpierw zarejestruj instalację, aby aktywować zakup planu.', 'nip-finder' ); ?></p>
                <?php endif; ?>
            <?php endif; ?>

            <?php if ( ! empty( $state['features'] ) ) : ?>
                <table class="widefat striped nip-finder-admin__table">
                    <thead>
                    <tr>
                        <th><?php esc_html_e( 'Feature', 'nip-finder' ); ?></th>
                        <th><?php esc_html_e( 'Wartość', 'nip-finder' ); ?></th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ( $state['features'] as $featureKey => $featureValue ) : ?>
                        <tr>
                            <td><?php echo esc_html( ucwords( str_replace( '_', ' ', (string) $featureKey ) ) ); ?></td>
                            <td><?php echo esc_html( $this->format_feature_value( $featureValue ) ); ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </section>

        <section class="nip-finder-admin__card nip-finder-admin__card--wide">
            <h2><?php esc_html_e( 'Ustawienia i diagnostyka', 'nip-finder' ); ?></h2>

            <form method="post" action="options.php" class="nip-finder-admin__settings-form">
                <?php settings_fields( 'nip_finder_settings_group' ); ?>

                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row"><label for="nip_finder_api_key"><?php esc_html_e( 'Dotychczasowy klucz API', 'nip-finder' ); ?></label></th>
                        <td>
                            <input type="password" class="regular-text" id="nip_finder_api_key" name="nip_finder_api_key" value="" autocomplete="new-password" placeholder="<?php echo '' !== $legacy_api_key ? esc_attr__( 'Klucz zapisany - wpisz nowy, aby go zmienić', 'nip-finder' ) : ''; ?>" />
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="nip_finder_getting_nip"><?php esc_html_e( 'Pobieranie danych po NIP', 'nip-finder' ); ?></label></th>
                        <td>
                            <select id="nip_finder_getting_nip" name="nip_finder_getting_nip">
                                <option value="1" <?php selected( get_option( 'nip_finder_getting_nip', '0' ), '1' ); ?>><?php esc_html_e( 'Tak', 'nip-finder' ); ?></option>
                                <option value="0" <?php selected( get_option( 'nip_finder_getting_nip', '0' ), '0' ); ?>><?php esc_html_e( 'Nie', 'nip-finder' ); ?></option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="nip_finder_nip_fetch_mode"><?php esc_html_e( 'Tryb pobierania danych NIP', 'nip-finder' ); ?></label></th>
                        <td>
                            <select id="nip_finder_nip_fetch_mode" name="nip_finder_nip_fetch_mode">
                                <option value="auto" <?php selected( get_option( 'nip_finder_nip_fetch_mode', 'manual' ), 'auto' ); ?>><?php esc_html_e( 'Automatycznie', 'nip-finder' ); ?></option>
                                <option value="manual" <?php selected( get_option( 'nip_finder_nip_fetch_mode', 'manual' ), 'manual' ); ?>><?php esc_html_e( 'Ręcznie', 'nip-finder' ); ?></option>
                            </select>
                        </td>
                    </tr>
                </table>

                <?php submit_button( __( 'Zapisz ustawienia', 'nip-finder' ) ); ?>
            </form>

            <table class="widefat striped nip-finder-admin__table">
                <tbody>
                <tr>
                    <td><?php esc_html_e( 'Ostatni błąd', 'nip-finder' ); ?></td>
                    <td>
                        <?php
                        if ( ! empty( $state['last_error_message'] ) ) {
                            echo esc_html( (string) $state['last_error_message'] );
                        } else {
                            esc_html_e( 'Brak danych', 'nip-finder' );
                        }
                        ?>
                    </td>
                </tr>
                <tr>
                    <td><?php esc_html_e( 'API key', 'nip-finder' ); ?></td>
                    <td><?php echo ! empty( $state['api_key_masked'] ) ? esc_html( (string) $state['api_key_masked'] ) : esc_html__( 'Brak danych', 'nip-finder' ); ?></td>
                </tr>
                </tbody>
            </table>

            <div class="nip-finder-admin__actions">
                <button type="button" id="btn-nip-finder-register-installation" class="button button-secondary" <?php disabled( ! $v2_enabled ); ?>><?php esc_html_e( 'Zarejestruj instalację ponownie', 'nip-finder' ); ?></button>
                <button type="button" id="btn-nip-finder-check-status" class="button button-secondary"><?php esc_html_e( 'Test połączenia GUS', 'nip-finder' ); ?></button>
            </div>
        </section>
    </div>
</div>
