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

add_action( 'admin_menu', 'elementsell_mailing_list_register_menu', 21 );
add_action( 'admin_post_elementsell_mailing_export_csv', 'elementsell_handle_mailing_export_csv' );
add_action( 'admin_post_elementsell_blacklist_add', 'elementsell_handle_blacklist_add' );
add_action( 'admin_post_elementsell_blacklist_remove', 'elementsell_handle_blacklist_remove' );

/**
 * @return void
 */
function elementsell_mailing_list_register_menu() {
    add_submenu_page(
        null,
        'Mailing list',
        'Mailing list',
        'manage_options',
        'elementsell-mailing-list',
        'elementsell_render_mailing_list_page'
    );
}

/**
 * @param array $args
 * @return string
 */
function elementsell_get_mailing_list_admin_url( $args = [] ) {
    return add_query_arg(
        array_merge(
            [ 'page' => 'elementsell-mailing-list' ],
            $args
        ),
        admin_url( 'admin.php' )
    );
}

/**
 * @return array
 */
function elementsell_get_mailing_list_request_filters() {
    $source = array_merge( $_GET, $_POST );

    return elementsell_parse_mailing_list_filters(
        [
            'status_paid'       => array_key_exists( 'status_paid', $source ) ? wp_unslash( $source['status_paid'] ) : null,
            'status_unpaid'     => array_key_exists( 'status_unpaid', $source ) ? wp_unslash( $source['status_unpaid'] ) : null,
            'roles'             => isset( $source['roles'] ) ? (array) wp_unslash( $source['roles'] ) : [],
            'products'          => isset( $source['products'] ) ? (array) wp_unslash( $source['products'] ) : [],
            'date_field'        => isset( $source['date_field'] ) ? wp_unslash( $source['date_field'] ) : 'created_at',
            'date_from'         => isset( $source['date_from'] ) ? wp_unslash( $source['date_from'] ) : '',
            'date_to'           => isset( $source['date_to'] ) ? wp_unslash( $source['date_to'] ) : '',
            'exclude_blacklist' => array_key_exists( 'exclude_blacklist', $source ) ? wp_unslash( $source['exclude_blacklist'] ) : '1',
        ]
    );
}

/**
 * @return array
 */
function elementsell_get_mailing_list_request_columns() {
    return elementsell_parse_mailing_export_columns(
        [
            'email'       => isset( $_REQUEST['col_email'] ) ? wp_unslash( $_REQUEST['col_email'] ) : '1',
            'name'        => isset( $_REQUEST['col_name'] ) ? wp_unslash( $_REQUEST['col_name'] ) : '1',
            'phone'       => isset( $_REQUEST['col_phone'] ) ? wp_unslash( $_REQUEST['col_phone'] ) : '1',
            'address'     => isset( $_REQUEST['col_address'] ) ? wp_unslash( $_REQUEST['col_address'] ) : '1',
            'roles'       => isset( $_REQUEST['col_roles'] ) ? wp_unslash( $_REQUEST['col_roles'] ) : '1',
            'product'     => isset( $_REQUEST['col_product'] ) ? wp_unslash( $_REQUEST['col_product'] ) : '1',
            'last_order'  => isset( $_REQUEST['col_last_order'] ) ? wp_unslash( $_REQUEST['col_last_order'] ) : '1',
            'order_count' => isset( $_REQUEST['col_order_count'] ) ? wp_unslash( $_REQUEST['col_order_count'] ) : '1',
        ]
    );
}

/**
 * @return void
 */
function elementsell_handle_mailing_export_csv() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'Nemáte oprávnění.', 'platebni-formular' ) );
    }

    check_admin_referer( 'elementsell_mailing_export_csv' );

    $filters  = elementsell_get_mailing_list_request_filters();
    $columns  = elementsell_get_mailing_list_request_columns();
    $result   = elementsell_query_mailing_contacts( $filters );
    $csv      = elementsell_build_mailing_contacts_csv( $result['contacts'], $columns );
    $filename = 'elementsell-mailing-list-' . gmdate( 'Y-m-d-His' ) . '.csv';

    nocache_headers();
    header( 'Content-Type: text/csv; charset=utf-8' );
    header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
    echo $csv;
    exit;
}

/**
 * @return void
 */
function elementsell_handle_blacklist_add() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'Nemáte oprávnění.', 'platebni-formular' ) );
    }

    check_admin_referer( 'elementsell_blacklist_add' );

    $email  = isset( $_POST['blacklist_email'] ) ? sanitize_email( wp_unslash( (string) $_POST['blacklist_email'] ) ) : '';
    $result = elementsell_add_email_to_blacklist( $email, 'manual' );
    $args   = [ 'blacklist_notice' => 'added' ];

    if ( is_wp_error( $result ) ) {
        $args = [
            'blacklist_notice' => 'error',
            'blacklist_message' => rawurlencode( $result->get_error_message() ),
        ];
    }

    wp_safe_redirect( elementsell_get_mailing_list_admin_url( $args ) );
    exit;
}

/**
 * @return void
 */
function elementsell_handle_blacklist_remove() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'Nemáte oprávnění.', 'platebni-formular' ) );
    }

    check_admin_referer( 'elementsell_blacklist_remove' );

    $email = isset( $_POST['blacklist_email'] ) ? sanitize_email( wp_unslash( (string) $_POST['blacklist_email'] ) ) : '';

    if ( $email !== '' ) {
        elementsell_remove_email_from_blacklist( $email );
    }

    wp_safe_redirect( elementsell_get_mailing_list_admin_url( [ 'blacklist_notice' => 'removed' ] ) );
    exit;
}

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

    elementsell_render_admin_styles();

    $filters         = elementsell_get_mailing_list_request_filters();
    $columns         = elementsell_get_mailing_list_request_columns();
    $role_options    = elementsell_get_mailing_list_role_options();
    $product_options = elementsell_get_mailing_list_product_options();
    $preview_limit   = 100;
    $result          = elementsell_query_mailing_contacts( $filters );
    $total           = (int) $result['total'];
    $contacts        = array_slice( $result['contacts'], 0, $preview_limit );

    $blacklist = elementsell_get_blacklisted_emails();
    $notice    = '';

    if ( isset( $_GET['blacklist_notice'] ) ) {
        $type = sanitize_key( wp_unslash( (string) $_GET['blacklist_notice'] ) );

        if ( $type === 'added' ) {
            $notice = 'E-mail byl přidán na blacklist.';
        } elseif ( $type === 'removed' ) {
            $notice = 'E-mail byl odebrán z blacklistu.';
        } elseif ( $type === 'error' ) {
            $notice = isset( $_GET['blacklist_message'] )
                ? sanitize_text_field( wp_unslash( rawurldecode( (string) $_GET['blacklist_message'] ) ) )
                : 'Akci se nepodařilo dokončit.';
        }
    }

    ?>
    <div class="wrap elementsell-admin elementsell-mailing-list-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>Mailing list</h1>
        <p class="description">Kontakty z objednávek ElementSell. Stejný e-mail se sloučí do jednoho řádku (deduplikace). Po vyfiltrování stáhnete CSV.</p>

        <?php if ( $notice !== '' ) : ?>
            <div class="notice notice-info is-dismissible"><p><?php echo esc_html( $notice ); ?></p></div>
        <?php endif; ?>

        <div class="elementsell-admin-card elementsell-admin-card--form">
            <h2 class="elementsell-admin-section-title">Filtry</h2>
            <form method="get" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>">
                <input type="hidden" name="page" value="elementsell-mailing-list">

                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row">Stav objednávek</th>
                        <td>
                            <input type="hidden" name="status_paid" value="0">
                            <label><input type="checkbox" name="status_paid" value="1" <?php checked( ! empty( $filters['status_paid'] ) ); ?>> Zaplacené</label><br>
                            <input type="hidden" name="status_unpaid" value="0">
                            <label><input type="checkbox" name="status_unpaid" value="1" <?php checked( ! empty( $filters['status_unpaid'] ) ); ?>> Nezaplacené</label>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">Role</th>
                        <td>
                            <?php if ( empty( $role_options ) ) : ?>
                                <p class="description">Žádné role k výběru.</p>
                            <?php else : ?>
                                <div class="elementsell-mailing-checkbox-list" style="max-height:220px;overflow:auto;padding:4px 0;">
                                    <?php foreach ( $role_options as $role_key => $role_label ) : ?>
                                        <label style="display:block;margin:0 0 6px;">
                                            <input type="checkbox" name="roles[]" value="<?php echo esc_attr( $role_key ); ?>" <?php checked( in_array( $role_key, $filters['roles'], true ) ); ?>>
                                            <?php echo esc_html( $role_label ); ?>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                                <p class="description">Zaškrtněte jednu nebo více rolí. Prázdný výběr = všechny role.</p>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">Produkt / kurz</th>
                        <td>
                            <?php if ( empty( $product_options ) ) : ?>
                                <p class="description">Žádné produkty k výběru.</p>
                            <?php else : ?>
                                <div class="elementsell-mailing-checkbox-list" style="max-height:220px;overflow:auto;padding:4px 0;">
                                    <?php foreach ( $product_options as $product_name ) : ?>
                                        <label style="display:block;margin:0 0 6px;">
                                            <input type="checkbox" name="products[]" value="<?php echo esc_attr( $product_name ); ?>" <?php checked( in_array( $product_name, $filters['products'], true ) ); ?>>
                                            <?php echo esc_html( $product_name ); ?>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                                <p class="description">Zaškrtněte jeden nebo více produktů. Prázdný výběr = všechny produkty.</p>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">Období</th>
                        <td>
                            <select name="date_field">
                                <option value="created_at" <?php selected( $filters['date_field'], 'created_at' ); ?>>Datum objednávky</option>
                                <option value="paid_at" <?php selected( $filters['date_field'], 'paid_at' ); ?>>Datum platby</option>
                            </select>
                            <input type="date" name="date_from" value="<?php echo esc_attr( $filters['date_from'] ); ?>">
                            –
                            <input type="date" name="date_to" value="<?php echo esc_attr( $filters['date_to'] ); ?>">
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">Blacklist</th>
                        <td>
                            <input type="hidden" name="exclude_blacklist" value="0">
                            <label>
                                <input type="checkbox" name="exclude_blacklist" value="1" <?php checked( ! empty( $filters['exclude_blacklist'] ) ); ?>>
                                Vyloučit blacklistované e-maily
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">Sloupce exportu</th>
                        <td>
                            <label><input type="checkbox" name="col_email" value="1" <?php checked( ! empty( $columns['email'] ) ); ?>> E-mail</label><br>
                            <label><input type="checkbox" name="col_name" value="1" <?php checked( ! empty( $columns['name'] ) ); ?>> Jméno</label><br>
                            <label><input type="checkbox" name="col_phone" value="1" <?php checked( ! empty( $columns['phone'] ) ); ?>> Telefon</label><br>
                            <label><input type="checkbox" name="col_address" value="1" <?php checked( ! empty( $columns['address'] ) ); ?>> Adresa</label><br>
                            <label><input type="checkbox" name="col_roles" value="1" <?php checked( ! empty( $columns['roles'] ) ); ?>> Role</label><br>
                            <label><input type="checkbox" name="col_product" value="1" <?php checked( ! empty( $columns['product'] ) ); ?>> Produkt</label><br>
                            <label><input type="checkbox" name="col_last_order" value="1" <?php checked( ! empty( $columns['last_order'] ) ); ?>> Datum poslední objednávky</label><br>
                            <label><input type="checkbox" name="col_order_count" value="1" <?php checked( ! empty( $columns['order_count'] ) ); ?>> Počet objednávek</label>
                        </td>
                    </tr>
                </table>

                <p>
                    <button type="submit" class="button button-primary">Filtrovat</button>
                </p>
            </form>

            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin-top:8px;">
                <?php wp_nonce_field( 'elementsell_mailing_export_csv' ); ?>
                <input type="hidden" name="action" value="elementsell_mailing_export_csv">
                <?php elementsell_render_mailing_hidden_filter_fields( $filters, $columns ); ?>
                <button type="submit" class="button">Stáhnout CSV (<?php echo esc_html( (string) $total ); ?> kontaktů)</button>
            </form>
        </div>

        <div class="elementsell-admin-card">
            <h2 class="elementsell-admin-section-title">Kontakty</h2>
            <p><strong>Počet unikátních kontaktů:</strong> <?php echo esc_html( (string) $total ); ?></p>
            <?php if ( empty( $contacts ) ) : ?>
                <p class="elementsell-admin-empty">Pro zadané filtry nebyly nalezeny žádné kontakty.</p>
            <?php else : ?>
                <?php if ( $total > $preview_limit ) : ?>
                    <p class="description">Zobrazeno prvních <?php echo esc_html( (string) $preview_limit ); ?> z <?php echo esc_html( (string) $total ); ?> — kompletní seznam stáhnete jako CSV.</p>
                <?php endif; ?>
                <table class="widefat striped">
                    <thead>
                        <tr>
                            <th>E-mail</th>
                            <th>Jméno</th>
                            <th>Telefon</th>
                            <th>Adresa</th>
                            <th>Produkty</th>
                            <th>Role</th>
                            <th>Stav</th>
                            <th>Poslední objednávka</th>
                            <th>Počet</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( $contacts as $contact ) : ?>
                            <tr>
                                <td><?php echo esc_html( (string) $contact['email'] ); ?></td>
                                <td><?php echo esc_html( (string) $contact['name'] ); ?></td>
                                <td><?php echo esc_html( (string) $contact['phone'] ); ?></td>
                                <td><?php echo esc_html( (string) ( $contact['address'] ?? '' ) ); ?></td>
                                <td><?php echo esc_html( implode( ', ', (array) $contact['products'] ) ); ?></td>
                                <td><?php echo esc_html( implode( ', ', (array) $contact['roles'] ) ); ?></td>
                                <td><?php echo esc_html( (string) $contact['status'] ); ?></td>
                                <td><?php echo esc_html( $contact['last_order_at'] !== '' ? mysql2date( 'j. n. Y, H:i', $contact['last_order_at'], false ) : '—' ); ?></td>
                                <td><?php echo esc_html( (string) (int) $contact['order_count'] ); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>

        <div class="elementsell-admin-card">
            <h2 class="elementsell-admin-section-title">Blacklist</h2>
            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin-bottom:20px;">
                <?php wp_nonce_field( 'elementsell_blacklist_add' ); ?>
                <input type="hidden" name="action" value="elementsell_blacklist_add">
                <input type="email" name="blacklist_email" class="regular-text" placeholder="email@example.cz" required>
                <button type="submit" class="button">Přidat na blacklist</button>
            </form>

            <?php if ( empty( $blacklist ) ) : ?>
                <p class="elementsell-admin-empty">Blacklist je prázdný.</p>
            <?php else : ?>
                <table class="widefat striped">
                    <thead>
                        <tr>
                            <th>E-mail</th>
                            <th>Důvod</th>
                            <th>Přidáno</th>
                            <th>Akce</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( $blacklist as $row ) : ?>
                            <tr>
                                <td><?php echo esc_html( (string) $row->email ); ?></td>
                                <td><?php echo esc_html( (string) $row->reason === 'unsubscribe' ? 'Odhlášení' : 'Ručně' ); ?></td>
                                <td><?php echo esc_html( mysql2date( 'j. n. Y, H:i', (string) $row->created_at, false ) ); ?></td>
                                <td>
                                    <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
                                        <?php wp_nonce_field( 'elementsell_blacklist_remove' ); ?>
                                        <input type="hidden" name="action" value="elementsell_blacklist_remove">
                                        <input type="hidden" name="blacklist_email" value="<?php echo esc_attr( (string) $row->email ); ?>">
                                        <button type="submit" class="button button-small">Odebrat</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
    <?php
}

/**
 * @param array $filters
 * @param array $columns
 * @return void
 */
function elementsell_render_mailing_hidden_filter_fields( $filters, $columns ) {
    ?>
    <input type="hidden" name="status_paid" value="<?php echo ! empty( $filters['status_paid'] ) ? '1' : '0'; ?>">
    <input type="hidden" name="status_unpaid" value="<?php echo ! empty( $filters['status_unpaid'] ) ? '1' : '0'; ?>">
    <input type="hidden" name="date_field" value="<?php echo esc_attr( (string) $filters['date_field'] ); ?>">
    <input type="hidden" name="date_from" value="<?php echo esc_attr( (string) $filters['date_from'] ); ?>">
    <input type="hidden" name="date_to" value="<?php echo esc_attr( (string) $filters['date_to'] ); ?>">
    <input type="hidden" name="exclude_blacklist" value="<?php echo ! empty( $filters['exclude_blacklist'] ) ? '1' : '0'; ?>">
    <?php foreach ( (array) $filters['roles'] as $role_key ) : ?>
        <input type="hidden" name="roles[]" value="<?php echo esc_attr( (string) $role_key ); ?>">
    <?php endforeach; ?>
    <?php foreach ( (array) $filters['products'] as $product_name ) : ?>
        <input type="hidden" name="products[]" value="<?php echo esc_attr( (string) $product_name ); ?>">
    <?php endforeach; ?>
    <input type="hidden" name="col_email" value="<?php echo ! empty( $columns['email'] ) ? '1' : '0'; ?>">
    <input type="hidden" name="col_name" value="<?php echo ! empty( $columns['name'] ) ? '1' : '0'; ?>">
    <input type="hidden" name="col_phone" value="<?php echo ! empty( $columns['phone'] ) ? '1' : '0'; ?>">
    <input type="hidden" name="col_address" value="<?php echo ! empty( $columns['address'] ) ? '1' : '0'; ?>">
    <input type="hidden" name="col_roles" value="<?php echo ! empty( $columns['roles'] ) ? '1' : '0'; ?>">
    <input type="hidden" name="col_product" value="<?php echo ! empty( $columns['product'] ) ? '1' : '0'; ?>">
    <input type="hidden" name="col_last_order" value="<?php echo ! empty( $columns['last_order'] ) ? '1' : '0'; ?>">
    <input type="hidden" name="col_order_count" value="<?php echo ! empty( $columns['order_count'] ) ? '1' : '0'; ?>">
    <?php
}
