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

add_action( 'admin_menu', 'elementsell_record_search_register_menu', 21 );

/**
 * @return void
 */
function elementsell_record_search_register_menu() {
    add_submenu_page(
        null,
        'Vyhledat záznam',
        'Vyhledat záznam',
        'manage_options',
        'elementsell-record-search',
        'elementsell_render_record_search_page'
    );
}

/**
 * @param string $query
 * @return string
 */
function elementsell_get_record_search_admin_url( $query = '' ) {
    $url = admin_url( 'admin.php?page=elementsell-record-search' );

    if ( $query !== '' ) {
        $url = add_query_arg( 'q', rawurlencode( $query ), $url );
    }

    return $url;
}

/**
 * Kompaktní vyhledávací pole (stejná logika jako stránka vyhledávání).
 *
 * @param array $args {
 *     @type string $placeholder Placeholder textu.
 *     @type string $class       Dodatečná CSS třída.
 * }
 * @return void
 */
function elementsell_render_record_search_field( $args = [] ) {
    $args = wp_parse_args(
        $args,
        [
            'placeholder' => '',
            'class'       => '',
        ]
    );

    $class    = trim( 'elementsell-record-search ' . (string) $args['class'] );
    $field_id = 'elementsell-record-search-field-' . wp_unique_id();
    ?>
    <form class="<?php echo esc_attr( $class ); ?>" method="get" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>" role="search">
        <input type="hidden" name="page" value="elementsell-record-search">
        <div class="elementsell-record-search__control">
            <button type="submit" class="elementsell-record-search__submit" aria-label="Hledat prodej, fakturu nebo e-mail">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                    <circle cx="11" cy="11" r="7" stroke="currentColor" stroke-width="2"/>
                    <path d="M20 20L16.5 16.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                </svg>
            </button>
            <label class="screen-reader-text" for="<?php echo esc_attr( $field_id ); ?>">Hledat prodej, fakturu nebo e-mail</label>
            <input
                type="search"
                id="<?php echo esc_attr( $field_id ); ?>"
                class="elementsell-record-search__input"
                name="q"
                value=""
                <?php if ( (string) $args['placeholder'] !== '' ) : ?>
                    placeholder="<?php echo esc_attr( (string) $args['placeholder'] ); ?>"
                <?php endif; ?>
                autocomplete="off"
            >
        </div>
    </form>
    <?php
}

/**
 * @param string $query
 * @param int    $limit
 * @return array{sales: array<int, object>, emails: array<int, object>}
 */
function elementsell_search_all_records( $query, $limit = 50 ) {
    $sales  = elementsell_search_sales_records( $query, $limit );
    $emails = function_exists( 'elementsell_search_email_log_records' )
        ? elementsell_search_email_log_records( $query, $limit )
        : [];

    return [
        'sales'  => $sales,
        'emails' => $emails,
    ];
}

/**
 * @return void
 */
function elementsell_render_record_search_page() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    elementsell_render_admin_styles();

    $query    = isset( $_GET['q'] ) ? sanitize_text_field( wp_unslash( (string) $_GET['q'] ) ) : '';
    $results  = $query !== '' ? elementsell_search_all_records( $query, 50 ) : [ 'sales' => [], 'emails' => [] ];
    $sales    = (array) $results['sales'];
    $emails   = (array) $results['emails'];
    $has_hits = ! empty( $sales ) || ! empty( $emails );

    ?>
    <div class="wrap elementsell-admin elementsell-record-search-page">
        <p style="margin-bottom:16px;">
            <a href="<?php echo esc_url( admin_url( 'admin.php?page=elementsell' ) ); ?>">&larr; Zpět na ElementSell</a>
        </p>

        <h1>Vyhledávání</h1>
        <p class="description">Hledejte podle e-mailu, jména, čísla faktury, ID objednávky, produktu, VS, platebního UID nebo textu v odeslaných e-mailech. Najdete i starší záznamy v archivu.</p>

        <div class="elementsell-admin-card elementsell-admin-card--form" style="max-width:720px;">
            <form method="get" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>">
                <input type="hidden" name="page" value="elementsell-record-search">
                <p>
                    <label class="screen-reader-text" for="elementsell-record-search-input">Hledaný výraz</label>
                    <input type="search" class="large-text" id="elementsell-record-search-input" name="q" value="<?php echo esc_attr( $query ); ?>" placeholder="např. email@example.cz, 202600123, Jan Novák">
                </p>
                <p><button type="submit" class="button button-primary">Hledat</button></p>
            </form>
        </div>

        <?php if ( $query !== '' ) : ?>
            <div class="elementsell-admin-card" style="margin-top:20px;">
                <?php if ( ! $has_hits ) : ?>
                    <p class="elementsell-admin-empty">Pro výraz „<?php echo esc_html( $query ); ?>“ nic nebylo nalezeno.</p>
                <?php else : ?>
                    <?php if ( ! empty( $sales ) ) : ?>
                        <h2 class="elementsell-admin-section-title">Prodeje a faktury</h2>
                        <p class="description">Nalezeno <?php echo esc_html( (string) count( $sales ) ); ?> záznamů.</p>
                        <table class="widefat striped">
                            <thead>
                                <tr>
                                    <th>Datum</th>
                                    <th>Zákazník</th>
                                    <th>Produkt</th>
                                    <th>Částka</th>
                                    <th>Faktura</th>
                                    <th>Stav</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ( $sales as $row ) : ?>
                                    <?php
                                    $customer    = trim( (string) $row->first_name . ' ' . (string) $row->surname );
                                    $is_archived = ! empty( $row->is_archived );
                                    ?>
                                    <tr>
                                        <td><?php echo esc_html( mysql2date( 'j. n. Y, H:i', $row->created_at, false ) ); ?></td>
                                        <td>
                                            <?php echo esc_html( $customer !== '' ? $customer : '—' ); ?><br>
                                            <span class="description"><?php echo esc_html( (string) $row->email ); ?></span>
                                        </td>
                                        <td><?php echo esc_html( (string) $row->product_name ); ?></td>
                                        <td><?php echo esc_html( elementsell_format_sales_stat_amount( (float) $row->amount ) ); ?></td>
                                        <td>
                                            <?php if ( ! empty( $row->invoice_id ) ) : ?>
                                                <a href="<?php echo esc_url( elementsell_get_invoice_admin_url( (int) $row->invoice_id ) ); ?>"><?php echo esc_html( (string) $row->invoice_number ); ?></a>
                                            <?php else : ?>
                                                —
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ( $is_archived ) : ?>
                                                <span class="description">Archiv</span>
                                            <?php else : ?>
                                                Aktivní
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>

                    <?php if ( ! empty( $emails ) ) : ?>
                        <h2 class="elementsell-admin-section-title"<?php echo ! empty( $sales ) ? ' style="margin-top:28px;"' : ''; ?>>Odeslané e-maily</h2>
                        <p class="description">Nalezeno <?php echo esc_html( (string) count( $emails ) ); ?> e-mailů.</p>
                        <table class="widefat striped">
                            <thead>
                                <tr>
                                    <th>Datum</th>
                                    <th>Stav</th>
                                    <th>Příjemce</th>
                                    <th>Předmět</th>
                                    <th>Objednávka</th>
                                    <th>Akce</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ( $emails as $mail ) : ?>
                                    <?php
                                    $mail_id   = (int) $mail->id;
                                    $status    = isset( $mail->status ) ? (string) $mail->status : 'sent';
                                    $is_failed = $status === 'failed';
                                    ?>
                                    <tr>
                                        <td><?php echo esc_html( mysql2date( 'j. n. Y, H:i', $mail->created_at, false ) ); ?></td>
                                        <td>
                                            <?php if ( $is_failed ) : ?>
                                                <span style="color:#b32d2e;font-weight:600;">Selhalo</span>
                                            <?php else : ?>
                                                <span style="color:#1d7a46;font-weight:600;">Odesláno</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo esc_html( (string) $mail->email ); ?></td>
                                        <td><?php echo esc_html( (string) $mail->subject ); ?></td>
                                        <td>
                                            <?php if ( ! empty( $mail->order_id ) ) : ?>
                                                #<?php echo esc_html( (string) (int) $mail->order_id ); ?>
                                            <?php else : ?>
                                                —
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <button type="button" class="button button-small elementsell-toggle-email" data-email="<?php echo esc_attr( (string) $mail_id ); ?>">Zobrazit</button>
                                        </td>
                                    </tr>
                                    <tr id="elementsell-email-<?php echo esc_attr( (string) $mail_id ); ?>" style="display:none;">
                                        <td colspan="6" style="background:#fff;padding:20px 25px;">
                                            <?php echo wp_kses_post( (string) $mail->body ); ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                <?php endif; ?>
            </div>

            <script>
            document.querySelectorAll('.elementsell-toggle-email').forEach(function(button) {
                button.addEventListener('click', function() {
                    const id = this.dataset.email;
                    const row = document.getElementById('elementsell-email-' + id);
                    if (!row) return;

                    if (row.style.display === 'none') {
                        row.style.display = 'table-row';
                        this.textContent = 'Skrýt';
                    } else {
                        row.style.display = 'none';
                        this.textContent = 'Zobrazit';
                    }
                });
            });
            </script>
        <?php endif; ?>
    </div>
    <?php
}
