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

/**
 * Dashboard stats for Algo Forms.
 *
 * @return array<string,mixed>
 */
function algo_forms_dashboard_stats()
{
    global $wpdb;
    $forms_table = $wpdb->prefix . 'algo_forms';
    $subs_table = $wpdb->prefix . 'algo_form_submissions';

    $forms_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$forms_table}");
    $subs_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$subs_table}");
    $week_count = (int) $wpdb->get_var(
        $wpdb->prepare(
            "SELECT COUNT(*) FROM {$subs_table} WHERE submission_date >= %s",
            gmdate('Y-m-d H:i:s', time() - WEEK_IN_SECONDS)
        )
    );

    $recent = $wpdb->get_results(
        "SELECT s.id, s.form_id, s.form_data, s.submission_date, f.form_title, f.form_name
         FROM {$subs_table} s
         LEFT JOIN {$forms_table} f ON s.form_id = f.id
         ORDER BY s.submission_date DESC
         LIMIT 6"
    );

    $forms = $wpdb->get_results(
        "SELECT f.*, (
            SELECT COUNT(*) FROM {$subs_table} s WHERE s.form_id = f.id
         ) AS submission_count
         FROM {$forms_table} f
         ORDER BY f.created_at DESC
         LIMIT 8"
    );

    $transport = algo_forms_mail_transport_status();
    $recipients = algo_forms_get_company_recipients();

    return array(
        'forms_count' => $forms_count,
        'subs_count' => $subs_count,
        'week_count' => $week_count,
        'recent' => is_array($recent) ? $recent : array(),
        'forms' => is_array($forms) ? $forms : array(),
        'transport' => $transport,
        'recipients' => $recipients,
    );
}

/**
 * @return void
 */
function algo_forms_dashboard_page()
{
    if (!current_user_can(ALGO_FORMS_CAP)) {
        wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'algo-forms'));
    }

    $stats = algo_forms_dashboard_stats();
    $transport = $stats['transport'];
    $smtp_ready = !empty($transport['ready']);

    algo_forms_admin_shell_start(
        __('Dashboard', 'algo-forms'),
        __('Overview of forms, submissions, and mail delivery for this site.', 'algo-forms'),
        'lavender',
        true
    );
    ?>
        <section class="af-stats" aria-label="<?php esc_attr_e('Overview', 'algo-forms'); ?>">
            <article class="af-stat af-stat--forms">
                <span class="af-stat-icon"><?php echo algo_forms_admin_icon('forms'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
                <div>
                    <p class="af-stat-label"><?php esc_html_e('Forms', 'algo-forms'); ?></p>
                    <p class="af-stat-value"><?php echo esc_html((string) $stats['forms_count']); ?></p>
                </div>
            </article>
            <article class="af-stat af-stat--inbox">
                <span class="af-stat-icon"><?php echo algo_forms_admin_icon('inbox'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
                <div>
                    <p class="af-stat-label"><?php esc_html_e('All submissions', 'algo-forms'); ?></p>
                    <p class="af-stat-value"><?php echo esc_html((string) $stats['subs_count']); ?></p>
                </div>
            </article>
            <article class="af-stat af-stat--week">
                <span class="af-stat-icon"><?php echo algo_forms_admin_icon('clock'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
                <div>
                    <p class="af-stat-label"><?php esc_html_e('This week', 'algo-forms'); ?></p>
                    <p class="af-stat-value"><?php echo esc_html((string) $stats['week_count']); ?></p>
                </div>
            </article>
            <article class="af-stat <?php echo $smtp_ready ? 'af-stat--smtp-ok' : 'af-stat--smtp-warn'; ?>">
                <span class="af-stat-icon"><?php echo algo_forms_admin_icon($smtp_ready ? 'check' : 'warning'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
                <div>
                    <p class="af-stat-label"><?php esc_html_e('Mail delivery', 'algo-forms'); ?></p>
                    <p class="af-stat-value af-stat-value--text"><?php echo esc_html((string) ($transport['label'] ?? '')); ?></p>
                </div>
            </article>
        </section>

        <section class="af-actions" aria-label="<?php esc_attr_e('Quick actions', 'algo-forms'); ?>">
            <a class="af-action af-action--mint" href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-edit')); ?>">
                <span class="af-action-icon"><?php echo algo_forms_admin_icon('plus'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
                <span>
                    <strong><?php esc_html_e('Add new form', 'algo-forms'); ?></strong>
                    <em><?php esc_html_e('Build fields and shortcode', 'algo-forms'); ?></em>
                </span>
            </a>
            <a class="af-action af-action--sky" href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-list')); ?>">
                <span class="af-action-icon"><?php echo algo_forms_admin_icon('forms'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
                <span>
                    <strong><?php esc_html_e('Manage forms', 'algo-forms'); ?></strong>
                    <em><?php esc_html_e('Edit, copy shortcodes, delete', 'algo-forms'); ?></em>
                </span>
            </a>
            <a class="af-action af-action--peach" href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-submissions')); ?>">
                <span class="af-action-icon"><?php echo algo_forms_admin_icon('inbox'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
                <span>
                    <strong><?php esc_html_e('View submissions', 'algo-forms'); ?></strong>
                    <em><?php esc_html_e('Search, export CSV, clean up', 'algo-forms'); ?></em>
                </span>
            </a>
            <a class="af-action af-action--lavender" href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-smtp')); ?>">
                <span class="af-action-icon"><?php echo algo_forms_admin_icon('smtp'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
                <span>
                    <strong><?php esc_html_e('SMTP Setup', 'algo-forms'); ?></strong>
                    <em><?php esc_html_e('Host, auth, and test delivery', 'algo-forms'); ?></em>
                </span>
            </a>
            <a class="af-action af-action--rose" href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-email')); ?>">
                <span class="af-action-icon"><?php echo algo_forms_admin_icon('bell'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
                <span>
                    <strong><?php esc_html_e('Email & notifications', 'algo-forms'); ?></strong>
                    <em><?php esc_html_e('Recipients and visitor copy', 'algo-forms'); ?></em>
                </span>
            </a>
            <a class="af-action af-action--mint" href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-delivery-log')); ?>">
                <span class="af-action-icon"><?php echo algo_forms_admin_icon('smtp'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
                <span>
                    <strong><?php esc_html_e('Delivery log', 'algo-forms'); ?> <?php echo algo_forms_is_pro() ? '' : algo_forms_pro_badge_html(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></strong>
                    <em><?php echo algo_forms_is_pro() ? esc_html__('Inspect sent and failed mail', 'algo-forms') : esc_html__('Pro: full email attempt history', 'algo-forms'); ?></em>
                </span>
            </a>
            <a class="af-action af-action--lavender" href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-pro')); ?>">
                <span class="af-action-icon"><?php echo algo_forms_admin_icon('check'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
                <span>
                    <strong><?php echo algo_forms_is_pro() ? esc_html__('Pro settings', 'algo-forms') : esc_html__('Upgrade to Pro', 'algo-forms'); ?></strong>
                    <em><?php echo algo_forms_is_pro() ? esc_html__('Spam rules and license', 'algo-forms') : esc_html__('Spam, delivery log, inbox tools', 'algo-forms'); ?></em>
                </span>
            </a>
        </section>

        <div class="af-grid-2">
            <section class="af-panel">
                <div class="af-panel-head">
                    <h2><?php esc_html_e('Your forms', 'algo-forms'); ?></h2>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-list')); ?>"><?php esc_html_e('View all', 'algo-forms'); ?></a>
                </div>
                <?php if ($stats['forms']) : ?>
                    <ul class="af-form-list">
                        <?php foreach ($stats['forms'] as $form) : ?>
                            <li>
                                <div class="af-form-list-main">
                                    <span class="af-form-list-icon"><?php echo algo_forms_admin_icon('shortcode'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
                                    <div>
                                        <strong><?php echo esc_html($form->form_title); ?></strong>
                                        <code>[algo_form name="<?php echo esc_attr($form->form_name); ?>"]</code>
                                    </div>
                                </div>
                                <div class="af-form-list-meta">
                                    <span><?php echo esc_html(sprintf(
                                        /* translators: %d: submission count */
                                        _n('%d submission', '%d submissions', (int) $form->submission_count, 'algo-forms'),
                                        (int) $form->submission_count
                                    )); ?></span>
                                    <a class="button button-small" href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-edit&id=' . (int) $form->id)); ?>">
                                        <?php esc_html_e('Edit', 'algo-forms'); ?>
                                    </a>
                                </div>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php else : ?>
                    <div class="af-empty">
                        <p><?php esc_html_e('No forms yet. Create your first form to get started.', 'algo-forms'); ?></p>
                        <a class="button button-primary" href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-edit')); ?>">
                            <?php esc_html_e('Add New Form', 'algo-forms'); ?>
                        </a>
                    </div>
                <?php endif; ?>
            </section>

            <section class="af-panel">
                <div class="af-panel-head">
                    <h2><?php esc_html_e('Recent submissions', 'algo-forms'); ?></h2>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-submissions')); ?>"><?php esc_html_e('Open inbox', 'algo-forms'); ?></a>
                </div>
                <?php if ($stats['recent']) : ?>
                    <ul class="af-recent-list">
                        <?php foreach ($stats['recent'] as $row) :
                            $data = json_decode($row->form_data, true);
                            if (!is_array($data)) {
                                $data = array();
                            }
                            $preview = '';
                            foreach ($data as $key => $value) {
                                if (strtolower((string) $key) === 'page') {
                                    continue;
                                }
                                $preview = (string) $value;
                                break;
                            }
                            ?>
                            <li>
                                <span class="af-recent-icon"><?php echo algo_forms_admin_icon('inbox'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
                                <div>
                                    <strong><?php echo esc_html($row->form_title ?: __('Unknown form', 'algo-forms')); ?></strong>
                                    <p><?php echo esc_html($preview !== '' ? wp_html_excerpt($preview, 72, '…') : '—'); ?></p>
                                    <time><?php echo esc_html((string) $row->submission_date); ?></time>
                                </div>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php else : ?>
                    <div class="af-empty">
                        <p><?php esc_html_e('No submissions yet. Embed a form with the shortcode and submissions will appear here.', 'algo-forms'); ?></p>
                    </div>
                <?php endif; ?>
            </section>
        </div>

        <section class="af-panel af-panel--status">
            <div class="af-panel-head">
                <h2><?php esc_html_e('Delivery & notifications', 'algo-forms'); ?></h2>
            </div>
            <div class="af-status-grid">
                <div class="af-status-card <?php echo $smtp_ready ? 'is-ok' : 'is-warn'; ?>">
                    <span class="af-status-icon"><?php echo algo_forms_admin_icon('smtp'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
                    <div>
                        <strong><?php echo esc_html((string) ($transport['label'] ?? '')); ?></strong>
                        <p><?php echo esc_html((string) ($transport['detail'] ?? '')); ?></p>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-smtp')); ?>">
                            <?php echo $smtp_ready ? esc_html__('Review SMTP Setup', 'algo-forms') : esc_html__('Configure SMTP Setup', 'algo-forms'); ?>
                        </a>
                    </div>
                </div>
                <div class="af-status-card is-info">
                    <span class="af-status-icon"><?php echo algo_forms_admin_icon('users'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
                    <div>
                        <strong><?php esc_html_e('Company recipients', 'algo-forms'); ?></strong>
                        <p>
                            <?php
                            if ($stats['recipients']) {
                                echo esc_html(implode(', ', $stats['recipients']));
                            } else {
                                printf(
                                    /* translators: %s: admin email */
                                    esc_html__('Not set — fallback: %s', 'algo-forms'),
                                    esc_html((string) get_option('admin_email'))
                                );
                            }
                            ?>
                        </p>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=algo-forms-email')); ?>">
                            <?php esc_html_e('Manage notifications', 'algo-forms'); ?>
                        </a>
                    </div>
                </div>
            </div>
        </section>
    <?php
    algo_forms_admin_shell_end();
}
