<?php

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

/*----------------------------------------
メール送信履歴：管理画面サブメニューを登録
----------------------------------------*/
function immf_add_mail_logs_page() {

    add_submenu_page(
        'edit.php?post_type=im_mail_form',
        __(
            'Mail Logs',
            'im-mail-form'
        ),
        __(
            'Mail Logs',
            'im-mail-form'
        ),
        'manage_options',
        'im-mail-form-mail-logs',
        'immf_render_mail_logs_page'
    );

}

add_action(
    'admin_menu',
    'immf_add_mail_logs_page'
);


/*----------------------------------------
メール送信履歴：管理画面のURLを取得
----------------------------------------*/
function immf_get_mail_logs_page_url($log_id = 0) {

    $url = admin_url(
        'edit.php?post_type=im_mail_form&page=im-mail-form-mail-logs'
    );

    $log_id = absint($log_id);

    if ($log_id > 0) {
        $url = add_query_arg(
            'log_id',
            $log_id,
            $url
        );
    }

    return $url;

}


/*----------------------------------------
メール送信履歴：管理画面を表示
----------------------------------------*/
function immf_render_mail_logs_page() {

    // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only navigation parameter.
    $log_id = isset($_GET['log_id'])
        ? absint(wp_unslash($_GET['log_id']))
        : 0;
    // phpcs:enable WordPress.Security.NonceVerification.Recommended

    ?>

    <div class="wrap">

        <?php immf_render_admin_header(); ?>

        <?php if ($log_id > 0) : ?>

            <div class="im-mail-form-mail-log-detail__header">

                <h1>
                    <?php
                    esc_html_e(
                        'Mail Logs',
                        'im-mail-form'
                    );
                    ?>
                </h1>

                <a
                    href="<?php echo esc_url(immf_get_mail_logs_page_url()); ?>"
                    class="button button-secondary"
                >
                    <?php
                    esc_html_e(
                        '← Back to Mail Logs',
                        'im-mail-form'
                    );
                    ?>
                </a>

            </div>

            <?php immf_render_mail_log_detail_view($log_id); ?>

        <?php else : ?>

            <h1>
                <?php
                esc_html_e(
                    'Mail Logs',
                    'im-mail-form'
                );
                ?>
            </h1>

            <?php immf_render_mail_log_list_view(); ?>

        <?php endif; ?>

    </div>

    <?php
}


/*----------------------------------------
メール送信履歴：一覧ビューを表示
----------------------------------------*/
function immf_render_mail_log_list_view() {

    $per_page = 50;

    // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only pagination parameter.
    $paged = isset($_GET['paged'])
        ? absint(wp_unslash($_GET['paged']))
        : 1;
    // phpcs:enable WordPress.Security.NonceVerification.Recommended

    if ($paged < 1) {
        $paged = 1;
    }

    $total_items = immf_get_mail_logs_count();

    if ($total_items === 0) {

        ?>
        <p>
            <?php
            esc_html_e(
                'No mail logs found.',
                'im-mail-form'
            );
            ?>
        </p>
        <?php

        return;
    }

    $total_pages = (int) ceil($total_items / $per_page);

    /*
    * 現在ページが総ページ数を超えている場合は、
    * 最終ページとして安全に扱う。
    */
    if ($paged > $total_pages) {
        $paged = $total_pages;
    }

    $offset = ($paged - 1) * $per_page;

    $logs = immf_get_mail_logs(
        $per_page,
        $offset
    );

    if (empty($logs)) {

        ?>
        <p>
            <?php
            esc_html_e(
                'No mail logs found.',
                'im-mail-form'
            );
            ?>
        </p>
        <?php

        return;
    }

    immf_render_mail_logs_table($logs);

    immf_render_mail_logs_pagination(
        $paged,
        $total_pages
    );

}


/*----------------------------------------
メール送信履歴：ページネーションを表示
----------------------------------------*/
function immf_render_mail_logs_pagination(
    $current_page,
    $total_pages
) {

    if ($total_pages < 2) {
        return;
    }

    /*
    * 詳細画面用のlog_idはページネーションURLへ含めない。
    */
    $base_url = remove_query_arg(
        'log_id',
        immf_get_mail_logs_page_url()
    );

    $pagination_links = paginate_links([
        'base'    => add_query_arg(
            'paged',
            '%#%',
            $base_url
        ),
        'format'  => '',
        'current' => $current_page,
        'total'   => $total_pages,
    ]);

    if (!$pagination_links) {
        return;
    }

    ?>

    <div class="tablenav">
        <div class="tablenav-pages">
            <?php echo wp_kses_post($pagination_links); ?>
        </div>
    </div>

    <?php
}


/*----------------------------------------
メール送信履歴：詳細ビューを表示
----------------------------------------*/
function immf_render_mail_log_detail_view($log_id) {

    $log = immf_get_mail_log($log_id);

    if (!$log) {

        ?>
        <p>
            <?php
            esc_html_e(
                'The requested mail log could not be found.',
                'im-mail-form'
            );
            ?>
        </p>
        <?php

        return;
    }

    immf_render_mail_log_detail($log);

}



/*----------------------------------------
メール送信履歴：一覧テーブルを表示
----------------------------------------*/
function immf_render_mail_logs_table($logs) {

    ?>

    <table class="widefat fixed striped">

        <thead>
            <tr>
                <th scope="col">
                    <?php
                    esc_html_e(
                        'Sent At',
                        'im-mail-form'
                    );
                    ?>
                </th>
                <th scope="col">
                    <?php
                    esc_html_e(
                        'Form Title',
                        'im-mail-form'
                    );
                    ?>
                </th>
                <th scope="col">
                    <?php
                    esc_html_e(
                        'Admin Email',
                        'im-mail-form'
                    );
                    ?>
                </th>
                <th scope="col">
                    <?php
                    esc_html_e(
                        'Auto-Reply',
                        'im-mail-form'
                    );
                    ?>
                </th>
                <th scope="col">
                    <?php
                    esc_html_e(
                        'Recipient',
                        'im-mail-form'
                    );
                    ?>
                </th>
                <th scope="col">
                    <?php
                    esc_html_e(
                        'Actions',
                        'im-mail-form'
                    );
                    ?>
                </th>
            </tr>
        </thead>

        <tbody>

            <?php foreach ($logs as $log) : ?>
                <?php immf_render_mail_log_row($log); ?>
            <?php endforeach; ?>

        </tbody>

    </table>

    <?php
}


/*----------------------------------------
メール送信履歴：一覧テーブルの1行を表示
----------------------------------------*/
function immf_render_mail_log_row($log) {

    $sent_at_display = get_date_from_gmt(
        $log['sent_at_gmt'],
        'Y-m-d H:i'
    );

    $form_title = $log['form_title'] !== ''
        ? $log['form_title']
        : __('(no title)', 'im-mail-form');

    $admin_status_label =
        immf_get_mail_log_admin_status_label(
            $log['admin_status']
        );

    $reply_status_label =
        immf_get_mail_log_reply_status_label(
            $log['reply_status'],
            $log['reply_skip_reason']
        );

    $recipient_lines =
        immf_get_mail_log_recipient_lines(
            $log
        );

    ?>

    <tr>
        <td><?php echo esc_html($sent_at_display); ?></td>
        <td><?php echo esc_html($form_title); ?></td>
        <td><?php echo esc_html($admin_status_label); ?></td>
        <td><?php echo esc_html($reply_status_label); ?></td>
        <td>
            <?php
            echo wp_kses(
                implode(
                    '<br>',
                    array_map(
                        'esc_html',
                        $recipient_lines
                    )
                ),
                ['br' => []]
            );
            ?>
        </td>
        <td>
            <a href="<?php echo esc_url(immf_get_mail_logs_page_url($log['id'])); ?>">
                <?php
                esc_html_e(
                    'Details',
                    'im-mail-form'
                );
                ?>
            </a>
        </td>
    </tr>

    <?php
}


/*----------------------------------------
管理者メール送信ステータスの表示ラベルを取得
----------------------------------------*/
function immf_get_mail_log_admin_status_label($admin_status) {

    if ($admin_status === 'success') {
        return __('Sent', 'im-mail-form');
    }

    if ($admin_status === 'failed') {
        return __('Failed', 'im-mail-form');
    }

    return __('Unknown', 'im-mail-form');

}


/*----------------------------------------
自動返信の送信結果ラベルを取得
----------------------------------------*/
function immf_get_mail_log_reply_result_label($reply_status) {

    if ($reply_status === 'success') {
        return __('Sent', 'im-mail-form');
    }

    if ($reply_status === 'failed') {
        return __('Failed', 'im-mail-form');
    }

    return __('Not Sent', 'im-mail-form');

}


/*----------------------------------------
自動返信のスキップ理由ラベルを取得
----------------------------------------*/
function immf_get_mail_log_reply_skip_reason_label($reply_skip_reason) {

    if ($reply_skip_reason === 'disabled') {
        return __('Disabled', 'im-mail-form');
    }

    if ($reply_skip_reason === 'no_recipient') {
        return __('No Recipient', 'im-mail-form');
    }

    return '';

}


/*----------------------------------------
自動返信ステータスの表示ラベルを取得（一覧用）
----------------------------------------*/
function immf_get_mail_log_reply_status_label(
    $reply_status,
    $reply_skip_reason
) {

    if (
        $reply_status === 'success' ||
        $reply_status === 'failed'
    ) {
        return immf_get_mail_log_reply_result_label(
            $reply_status
        );
    }

    $skip_reason_label =
        immf_get_mail_log_reply_skip_reason_label(
            $reply_skip_reason
        );

    return $skip_reason_label !== ''
        ? $skip_reason_label
        : immf_get_mail_log_reply_result_label(
            $reply_status
        );

}


/*----------------------------------------
送信先の表示行を取得
----------------------------------------*/
function immf_get_mail_log_recipient_lines($log) {

    $lines = [];

    if ($log['admin_to'] !== '') {
        $lines[] = $log['admin_to'];
    }

    if ($log['reply_to'] !== '') {
        $lines[] = $log['reply_to'];
    }

    return $lines;

}


/*----------------------------------------
空欄項目の表示値を取得
----------------------------------------*/
function immf_get_mail_log_display_value($value) {

    return $value !== ''
        ? $value
        : __('(none)', 'im-mail-form');

}


/*----------------------------------------
送信結果ステータスの表示用クラス名を取得
----------------------------------------*/
function immf_get_mail_log_status_class($status) {

    if ($status === 'success') {
        return 'success';
    }

    if ($status === 'failed') {
        return 'failed';
    }

    return 'not-sent';

}


/*----------------------------------------
メール送信履歴：詳細ビューの中身を表示
----------------------------------------*/
function immf_render_mail_log_detail($log) {

    $sent_at_display = get_date_from_gmt(
        $log['sent_at_gmt'],
        'Y-m-d H:i'
    );

    $admin_status_label =
        immf_get_mail_log_admin_status_label(
            $log['admin_status']
        );

    $reply_result_label =
        immf_get_mail_log_reply_result_label(
            $log['reply_status']
        );

    $reply_skip_reason_label =
        immf_get_mail_log_reply_skip_reason_label(
            $log['reply_skip_reason']
        );

    $admin_status_class =
        immf_get_mail_log_status_class(
            $log['admin_status']
        );

    $reply_status_class =
        immf_get_mail_log_status_class(
            $log['reply_status']
        );

    ?>

    <div class="im-mail-form-mail-log-detail">

        <div class="im-mail-form-mail-log-detail__section">

            <h2>
                <?php
                esc_html_e(
                    'Basic Information',
                    'im-mail-form'
                );
                ?>
            </h2>

            <table class="im-mail-form-mail-log-detail__table">
                <tbody>

                    <tr>
                        <th scope="row">
                            <?php esc_html_e('Sent At', 'im-mail-form'); ?>
                        </th>
                        <td><?php echo esc_html($sent_at_display); ?></td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <?php esc_html_e('Form Title', 'im-mail-form'); ?>
                        </th>
                        <td>
                            <?php
                            echo esc_html(
                                immf_get_mail_log_display_value(
                                    $log['form_title']
                                )
                            );
                            ?>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <?php esc_html_e('Form ID', 'im-mail-form'); ?>
                        </th>
                        <td>
                            <?php
                            echo esc_html(
                                immf_get_mail_log_display_value(
                                    $log['form_id']
                                )
                            );
                            ?>
                        </td>
                    </tr>

                </tbody>
            </table>

        </div>

        <div class="im-mail-form-mail-log-detail__section">

            <h2>
                <?php
                esc_html_e(
                    'Admin Email',
                    'im-mail-form'
                );
                ?>
            </h2>

            <table class="im-mail-form-mail-log-detail__table">
                <tbody>

                    <tr>
                        <th scope="row">
                            <?php esc_html_e('Result', 'im-mail-form'); ?>
                        </th>
                        <td>
                            <span class="im-mail-form-mail-log-detail__status im-mail-form-mail-log-detail__status--<?php echo esc_attr($admin_status_class); ?>">
                                <?php echo esc_html($admin_status_label); ?>
                            </span>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">To</th>
                        <td>
                            <?php
                            echo esc_html(
                                immf_get_mail_log_display_value(
                                    $log['admin_to']
                                )
                            );
                            ?>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">CC</th>
                        <td>
                            <?php
                            echo esc_html(
                                immf_get_mail_log_display_value(
                                    $log['admin_cc']
                                )
                            );
                            ?>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">BCC</th>
                        <td>
                            <?php
                            echo esc_html(
                                immf_get_mail_log_display_value(
                                    $log['admin_bcc']
                                )
                            );
                            ?>
                        </td>
                    </tr>

                </tbody>
            </table>

        </div>

        <div class="im-mail-form-mail-log-detail__section">

            <h2>
                <?php
                esc_html_e(
                    'Auto-Reply Email',
                    'im-mail-form'
                );
                ?>
            </h2>

            <table class="im-mail-form-mail-log-detail__table">
                <tbody>

                    <tr>
                        <th scope="row">
                            <?php esc_html_e('Result', 'im-mail-form'); ?>
                        </th>
                        <td>
                            <span class="im-mail-form-mail-log-detail__status im-mail-form-mail-log-detail__status--<?php echo esc_attr($reply_status_class); ?>">
                                <?php echo esc_html($reply_result_label); ?>
                            </span>
                        </td>
                    </tr>

                    <?php if ($reply_skip_reason_label !== '') : ?>

                        <tr>
                            <th scope="row">
                                <?php esc_html_e('Skip Reason', 'im-mail-form'); ?>
                            </th>
                            <td><?php echo esc_html($reply_skip_reason_label); ?></td>
                        </tr>

                    <?php endif; ?>

                    <tr>
                        <th scope="row">To</th>
                        <td>
                            <?php
                            echo esc_html(
                                immf_get_mail_log_display_value(
                                    $log['reply_to']
                                )
                            );
                            ?>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">BCC</th>
                        <td>
                            <?php
                            echo esc_html(
                                immf_get_mail_log_display_value(
                                    $log['reply_bcc']
                                )
                            );
                            ?>
                        </td>
                    </tr>

                </tbody>
            </table>

        </div>

        <div class="im-mail-form-mail-log-detail__section">

            <h2>
                <?php
                esc_html_e(
                    'Other',
                    'im-mail-form'
                );
                ?>
            </h2>

            <table class="im-mail-form-mail-log-detail__table">
                <tbody>

                    <tr>
                        <th scope="row">
                            <?php esc_html_e('IP Address', 'im-mail-form'); ?>
                        </th>
                        <td>
                            <?php
                            echo esc_html(
                                immf_get_mail_log_display_value(
                                    $log['ip_address']
                                )
                            );
                            ?>
                        </td>
                    </tr>

                </tbody>
            </table>

        </div>

    </div>

    <?php
}
