<?php
/**
 * Pro email delivery log.
 *
 * @package AlgoForms
 */

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

/**
 * @return string
 */
function algo_forms_mail_log_table()
{
    global $wpdb;
    return $wpdb->prefix . 'algo_forms_mail_log';
}

/**
 * Create / upgrade mail log table.
 *
 * @return void
 */
function algo_forms_install_mail_log_table()
{
    global $wpdb;
    $table = algo_forms_mail_log_table();
    $charset = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE {$table} (
        id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
        created_at datetime NOT NULL,
        form_id bigint(20) unsigned NULL,
        submission_id bigint(20) unsigned NULL,
        to_email varchar(255) NOT NULL DEFAULT '',
        subject varchar(255) NOT NULL DEFAULT '',
        status varchar(20) NOT NULL DEFAULT 'failed',
        detail text NULL,
        context varchar(191) NOT NULL DEFAULT '',
        PRIMARY KEY  (id),
        KEY created_at (created_at),
        KEY form_id (form_id),
        KEY submission_id (submission_id),
        KEY status (status)
    ) {$charset};";

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta($sql);
}

/**
 * Append a delivery log row when Pro is active.
 *
 * @param array<string,mixed> $entry Log entry.
 * @return void
 */
function algo_forms_delivery_log_write(array $entry)
{
    if (!algo_forms_pro_feature('delivery_log')) {
        return;
    }

    global $wpdb;
    $table = algo_forms_mail_log_table();

    // Soft-fail if table missing (e.g. before upgrade ran).
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($table)));
    if ($exists !== $table) {
        algo_forms_install_mail_log_table();
    }

    $wpdb->insert(
        $table,
        array(
            'created_at' => current_time('mysql'),
            'form_id' => isset($entry['form_id']) ? (int) $entry['form_id'] : null,
            'submission_id' => isset($entry['submission_id']) ? (int) $entry['submission_id'] : null,
            'to_email' => isset($entry['to_email']) ? sanitize_text_field((string) $entry['to_email']) : '',
            'subject' => isset($entry['subject']) ? sanitize_text_field((string) $entry['subject']) : '',
            'status' => !empty($entry['ok']) ? 'sent' : 'failed',
            'detail' => isset($entry['detail']) ? sanitize_textarea_field((string) $entry['detail']) : '',
            'context' => isset($entry['context']) ? sanitize_text_field((string) $entry['context']) : '',
        ),
        array('%s', '%d', '%d', '%s', '%s', '%s', '%s', '%s')
    );
}

/**
 * Parse form / submission ids from mail context string.
 *
 * @param string $context Context from algo_forms_wp_mail_send.
 * @return array{form_id:int,submission_id:int}
 */
function algo_forms_parse_mail_context($context)
{
    $form_id = 0;
    $submission_id = 0;
    if (preg_match('/form id\s+(\d+)/i', (string) $context, $m)) {
        $form_id = (int) $m[1];
    }
    if (preg_match('/submission id\s+(\d+)/i', (string) $context, $m)) {
        $submission_id = (int) $m[1];
    }
    return array(
        'form_id' => $form_id,
        'submission_id' => $submission_id,
    );
}
