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

/**
 * @param int                  $order_id
 * @param string               $email
 * @param string               $subject
 * @param string               $body
 * @param array<string, mixed> $args
 * @return int|false
 */
function elementsell_log_email_attempt( $order_id, $email, $subject, $body, $args = [] ) {
    global $wpdb;

    $status = isset( $args['status'] ) ? sanitize_key( (string) $args['status'] ) : 'sent';

    if ( ! in_array( $status, [ 'sent', 'failed' ], true ) ) {
        $status = 'sent';
    }

    $row = [
        'order_id'      => (int) $order_id,
        'email'         => sanitize_email( $email ),
        'subject'       => sanitize_text_field( $subject ),
        'body'          => wp_kses_post( $body ),
        'status'        => $status,
        'transport'     => sanitize_key( (string) ( $args['transport'] ?? '' ) ),
        'from_email'    => sanitize_email( (string) ( $args['from_email'] ?? '' ) ),
        'error_message' => sanitize_textarea_field( (string) ( $args['error_message'] ?? '' ) ),
        'created_at'    => current_time( 'mysql' ),
    ];

    $formats = [ '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ];

    elementsell_ensure_email_log_table_columns();

    $inserted = $wpdb->insert(
        $wpdb->prefix . 'elementsell_email_log',
        $row,
        $formats
    );

    if ( false === $inserted ) {
        error_log(
            'ElementSell email log: insert selhal pro objednávku ' . (int) $order_id . ': ' . (string) $wpdb->last_error
        );
    }

    return $inserted;
}

/**
 * @param int    $order_id
 * @param string $email
 * @param string $subject
 * @param string $body
 * @return int|false
 */
function elementsell_log_sent_email( $order_id, $email, $subject, $body ) {
    $meta = function_exists( 'elementsell_get_last_email_send_meta' )
        ? elementsell_get_last_email_send_meta()
        : [];

    return elementsell_log_email_attempt(
        $order_id,
        $email,
        $subject,
        $body,
        [
            'status'        => 'sent',
            'transport'     => (string) ( $meta['transport'] ?? '' ),
            'from_email'    => (string) ( $meta['from_email'] ?? '' ),
            'error_message' => '',
        ]
    );
}

/**
 * @param int    $order_id
 * @param string $email
 * @param string $subject
 * @param string $body
 * @return int|false
 */
function elementsell_log_failed_email( $order_id, $email, $subject, $body ) {
    $meta = function_exists( 'elementsell_get_last_email_send_meta' )
        ? elementsell_get_last_email_send_meta()
        : [];

    $error = trim( (string) ( $meta['error'] ?? '' ) );

    if ( $error === '' && ! empty( $meta['deliverability_warning'] ) ) {
        $error = (string) $meta['deliverability_warning'];
    }

    return elementsell_log_email_attempt(
        $order_id,
        $email,
        $subject,
        $body,
        [
            'status'        => 'failed',
            'transport'     => (string) ( $meta['transport'] ?? '' ),
            'from_email'    => (string) ( $meta['from_email'] ?? '' ),
            'error_message' => $error,
        ]
    );
}

/**
 * @param string $transport
 * @return string
 */
function elementsell_format_email_log_transport_label( $transport ) {
    $transport = sanitize_key( (string) $transport );

    if ( $transport === 'wp_mail' ) {
        return 'WordPress (wp_mail)';
    }

    if ( $transport === 'smtp' ) {
        return 'SMTP záloha ElementSell';
    }

    if ( $transport === 'smtp_gmail' ) {
        return 'Gmail SMTP (admin)';
    }

    if ( $transport === '' ) {
        return '—';
    }

    return $transport;
}

/**
 * @param string $query
 * @param int    $limit
 * @return array<int, object>
 */
function elementsell_search_email_log_records( $query, $limit = 50 ) {
    global $wpdb;

    $query = trim( (string) $query );
    $limit = max( 1, min( 100, (int) $limit ) );
    $table = $wpdb->prefix . 'elementsell_email_log';

    if ( $query === '' ) {
        return [];
    }

    if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) {
        return [];
    }

    $like         = '%' . $wpdb->esc_like( $query ) . '%';
    $search_parts = [
        'email LIKE %s',
        'subject LIKE %s',
        'body LIKE %s',
        'from_email LIKE %s',
        'error_message LIKE %s',
    ];
    $params       = [ $like, $like, $like, $like, $like ];

    if ( ctype_digit( $query ) ) {
        $search_parts[] = 'order_id = %d';
        $search_parts[] = 'id = %d';
        $params[]       = (int) $query;
        $params[]       = (int) $query;
    }

    $params[] = $limit;

    return (array) $wpdb->get_results(
        $wpdb->prepare(
            'SELECT *
             FROM ' . $table . '
             WHERE ' . implode( ' OR ', $search_parts ) . '
             ORDER BY created_at DESC
             LIMIT %d',
            ...$params
        )
    );
}
