<?php
/**
 * Daily manager report — data collection, HTML email, and scheduled delivery.
 *
 * @package Maca_Menu_List
 */

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

if (!defined('MACA_MENULIST_DAILY_REPORT_CRON_HOOK')) {
    define('MACA_MENULIST_DAILY_REPORT_CRON_HOOK', 'maca_menulist_daily_report');
}

require_once MACA_MENULIST_PLUGIN_DIR . 'includes/dashboard-data.php';

/**
 * Whether daily report is available (active Pro subscription).
 *
 * @return bool
 */
function maca_menulist_daily_report_is_available() {
    return function_exists('maca_menulist_pro_has_feature')
        && maca_menulist_pro_has_feature('daily_report');
}

/**
 * Switch gettext to the site language (so cron emails match Settings → General).
 *
 * @return bool Whether locale was switched.
 */
function maca_menulist_daily_report_switch_to_site_locale() {
    if (!function_exists('switch_to_locale') || !function_exists('maca_menulist_get_site_locale')) {
        return false;
    }

    $locale = maca_menulist_get_site_locale();

    if ($locale === '' || $locale === 'en_US' || $locale === 'en') {
        return false;
    }

    return (bool) switch_to_locale($locale);
}

/**
 * Restore locale after maca_menulist_daily_report_switch_to_site_locale().
 *
 * @param bool $switched Return value from switch helper.
 * @return void
 */
function maca_menulist_daily_report_restore_locale($switched) {
    if ($switched && function_exists('restore_previous_locale')) {
        restore_previous_locale();
    }
}

/**
 * Build localized report payload (data, HTML, subject).
 *
 * @param string $date Y-m-d.
 * @return array{data: array<string, mixed>, html: string, subject: string}
 */
function maca_menulist_daily_report_render($date) {
    $switched = maca_menulist_daily_report_switch_to_site_locale();
    $data = maca_menulist_daily_report_collect($date);
    $html = maca_menulist_daily_report_build_html($data);
    $subject = maca_menulist_daily_report_build_subject($data);
    maca_menulist_daily_report_restore_locale($switched);

    return array(
        'data' => $data,
        'html' => $html,
        'subject' => $subject,
    );
}

/**
 * Whether automatic daily report email is enabled.
 *
 * @return bool
 */
function maca_menulist_daily_report_is_enabled() {
    return get_option('maca_menulist_daily_report_enabled', '0') === '1';
}

/**
 * Configured send time (HH:MM, site timezone).
 *
 * @return string
 */
function maca_menulist_daily_report_get_send_time() {
    $time = get_option('maca_menulist_daily_report_send_time', '22:00');

    return is_string($time) && preg_match('/^\d{2}:\d{2}$/', $time) ? $time : '22:00';
}

/**
 * Report date mode: same_day or previous_day.
 *
 * @return string
 */
function maca_menulist_daily_report_get_date_mode() {
    $mode = get_option('maca_menulist_daily_report_date_mode', 'auto');

    if (!in_array($mode, array('auto', 'same_day', 'previous_day'), true)) {
        return 'auto';
    }

    return $mode;
}

/**
 * Parse configured recipient list.
 *
 * @return array<int, string>
 */
function maca_menulist_daily_report_get_recipients() {
    $raw = get_option('maca_menulist_daily_report_recipients', '');

    if (!is_string($raw) || trim($raw) === '') {
        $admin = get_option('admin_email');
        return is_email($admin) ? array($admin) : array();
    }

    $parts = preg_split('/[\s,;]+/', $raw);
    $emails = array();

    if (!is_array($parts)) {
        return $emails;
    }

    foreach ($parts as $part) {
        $email = sanitize_email(trim((string) $part));
        if (is_email($email)) {
            $emails[] = $email;
        }
    }

    return array_values(array_unique($emails));
}

/**
 * Resolve which calendar day the automated report should cover.
 *
 * @param string $send_time Optional HH:MM override.
 * @return string Y-m-d
 */
function maca_menulist_daily_report_resolve_report_date($send_time = '') {
    $mode = maca_menulist_daily_report_get_date_mode();

    if ($mode === 'same_day') {
        return wp_date('Y-m-d');
    }

    if ($mode === 'previous_day') {
        return wp_date('Y-m-d', strtotime('-1 day', current_time('timestamp')));
    }

    if ($send_time === '' || !preg_match('/^\d{2}:\d{2}$/', $send_time)) {
        $send_time = maca_menulist_daily_report_get_send_time();
    }

    $hour = (int) explode(':', $send_time)[0];

    if ($hour < 12) {
        return wp_date('Y-m-d', strtotime('-1 day', current_time('timestamp')));
    }

    return wp_date('Y-m-d');
}

/**
 * Next cron timestamp for configured send time.
 *
 * @return int
 */
function maca_menulist_daily_report_next_run_timestamp() {
    $time = maca_menulist_daily_report_get_send_time();
    $timezone = wp_timezone();
    $now = new DateTime('now', $timezone);
    $parts = explode(':', $time);
    $scheduled = clone $now;
    $scheduled->setTime((int) $parts[0], (int) $parts[1], 0);

    if ($scheduled <= $now) {
        $scheduled->modify('+1 day');
    }

    return $scheduled->getTimestamp();
}

/**
 * Schedule daily report cron when enabled.
 *
 * @return void
 */
function maca_menulist_daily_report_schedule_cron() {
    maca_menulist_daily_report_unschedule_cron();

    if (!maca_menulist_daily_report_is_available() || !maca_menulist_daily_report_is_enabled()) {
        return;
    }

    wp_schedule_event(
        maca_menulist_daily_report_next_run_timestamp(),
        'daily',
        MACA_MENULIST_DAILY_REPORT_CRON_HOOK
    );
}

/**
 * Clear scheduled daily report cron.
 *
 * @return void
 */
function maca_menulist_daily_report_unschedule_cron() {
    wp_clear_scheduled_hook(MACA_MENULIST_DAILY_REPORT_CRON_HOOK);
}

/**
 * Ensure cron exists when enabled.
 *
 * @return void
 */
function maca_menulist_daily_report_maybe_schedule_cron() {
    if (!maca_menulist_daily_report_is_available() || !maca_menulist_daily_report_is_enabled()) {
        maca_menulist_daily_report_unschedule_cron();
        return;
    }

    if (!wp_next_scheduled(MACA_MENULIST_DAILY_REPORT_CRON_HOOK)) {
        maca_menulist_daily_report_schedule_cron();
    }
}

/**
 * Tips total for paid orders in a date range.
 *
 * @param string $date_from Y-m-d.
 * @param string $date_to   Y-m-d.
 * @return float
 */
function maca_menulist_daily_report_tips_for_range($date_from, $date_to) {
    if (!maca_menulist_is_dishes_mode() || !maca_menulist_table_order_enabled()) {
        return 0.0;
    }

    global $wpdb;

    maca_menulist_db_ensure_table_order_tables();

    $range = maca_menulist_normalize_stats_date_range($date_from, $date_to);
    $orders_table = maca_menulist_db_table_orders_table();

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $sum = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT COALESCE(SUM(COALESCE(tip_amount, 0)), 0)
            FROM $orders_table
            WHERE COALESCE(payment_amount, 0) > 0
            AND (
                (payment_status = %s AND (
                    (paid_at IS NOT NULL AND paid_at >= %s AND paid_at <= %s)
                    OR (paid_at IS NULL AND created_at >= %s AND created_at <= %s)
                ))
                OR (payment_status = %s AND status_updated_at >= %s AND status_updated_at <= %s)
            )",
            'paid',
            $range['date_from'] . ' 00:00:00',
            $range['date_to'] . ' 23:59:59',
            $range['date_from'] . ' 00:00:00',
            $range['date_to'] . ' 23:59:59',
            'partial',
            $range['date_from'] . ' 00:00:00',
            $range['date_to'] . ' 23:59:59'
        )
    );

    return round((float) $sum, 2);
}

/**
 * Average handling time in minutes for orders handled on a date.
 *
 * @param string $date Y-m-d.
 * @return int|null
 */
function maca_menulist_daily_report_avg_order_minutes($date) {
    if (!maca_menulist_is_dishes_mode() || !maca_menulist_table_order_enabled()) {
        return null;
    }

    global $wpdb;

    maca_menulist_db_ensure_table_order_tables();

    $orders_table = maca_menulist_db_table_orders_table();

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $avg = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT AVG(TIMESTAMPDIFF(MINUTE, created_at, handled_at))
            FROM $orders_table
            WHERE handled_at IS NOT NULL
            AND handled_at >= %s AND handled_at <= %s",
            $date . ' 00:00:00',
            $date . ' 23:59:59'
        )
    );

    if ($avg === null) {
        return null;
    }

    return max(0, (int) round((float) $avg));
}

/**
 * Order counts grouped by service mode for a date.
 *
 * @param string $date Y-m-d.
 * @return array<string, array{count: int, revenue: float}>
 */
function maca_menulist_daily_report_service_mode_breakdown($date) {
    if (!maca_menulist_is_dishes_mode() || !maca_menulist_table_order_enabled()) {
        return array();
    }

    global $wpdb;

    maca_menulist_db_ensure_table_order_tables();

    $orders_table = maca_menulist_db_table_orders_table();

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $rows = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT
                CASE WHEN service_mode = 'takeaway' THEN 'takeaway' ELSE 'dine_in' END AS mode_key,
                COUNT(*) AS order_count,
                COALESCE(SUM(COALESCE(payment_amount, 0) + COALESCE(tip_amount, 0)), 0) AS revenue
            FROM $orders_table
            WHERE created_at >= %s AND created_at <= %s
            GROUP BY mode_key",
            $date . ' 00:00:00',
            $date . ' 23:59:59'
        )
    );

    $out = array(
        'dine_in' => array('count' => 0, 'revenue' => 0.0),
        'takeaway' => array('count' => 0, 'revenue' => 0.0),
    );

    foreach ($rows as $row) {
        $key = (string) $row->mode_key;
        if (!isset($out[$key])) {
            continue;
        }
        $out[$key]['count'] = (int) $row->order_count;
        $out[$key]['revenue'] = round((float) $row->revenue, 2);
    }

    return $out;
}

/**
 * Orders per hour for a single date (0–23).
 *
 * @param string $date Y-m-d.
 * @return array<int, int>
 */
function maca_menulist_daily_report_hourly_orders($date) {
    if (!maca_menulist_is_dishes_mode() || !maca_menulist_table_order_enabled()) {
        return array();
    }

    global $wpdb;

    maca_menulist_db_ensure_table_order_tables();

    $orders_table = maca_menulist_db_table_orders_table();

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $rows = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT HOUR(created_at) AS hour_key, COUNT(*) AS total
            FROM $orders_table
            WHERE created_at >= %s AND created_at <= %s
            GROUP BY HOUR(created_at)
            ORDER BY hour_key ASC",
            $date . ' 00:00:00',
            $date . ' 23:59:59'
        )
    );

    $map = array();
    foreach ($rows as $row) {
        $map[ (int) $row->hour_key ] = (int) $row->total;
    }

    return $map;
}

/**
 * Collect all metrics for a daily report.
 *
 * @param string $date Y-m-d.
 * @return array<string, mixed>
 */
function maca_menulist_daily_report_collect($date) {
    $date = preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) ? $date : wp_date('Y-m-d');
    $history = maca_menulist_get_dashboard_history($date, $date);
    $period_args = array(
        'date_from' => $date,
        'date_to' => $date,
    );

    $revenue = maca_menulist_dashboard_revenue_for_range($date, $date);
    $tips = maca_menulist_daily_report_tips_for_range($date, $date);
    $sales = max(0, round($revenue - $tips, 2));
    $order_count = maca_menulist_is_dishes_mode() && maca_menulist_table_order_enabled()
        ? maca_menulist_db_count_table_orders($period_args)
        : 0;
    $avg_ticket = $order_count > 0 ? round($revenue / $order_count, 2) : 0.0;
    $payment_summary = maca_menulist_get_payment_history_summary($period_args);
    $avg_minutes = maca_menulist_daily_report_avg_order_minutes($date);

    $data = array(
        'date' => $date,
        'date_label' => wp_date(get_option('date_format'), strtotime($date . ' 12:00:00')),
        'generated_at' => wp_date(get_option('date_format') . ' ' . get_option('time_format')),
        'restaurant' => maca_menulist_get_restaurant_name_from_settings(),
        'dishes_mode' => maca_menulist_is_dishes_mode(),
        'orders_enabled' => maca_menulist_is_dishes_mode() && maca_menulist_table_order_enabled(),
        'bookings_enabled' => maca_menulist_table_booking_enabled(),
        'dashboard_url' => admin_url('admin.php?page=maca-restu-dashboard'),
        'payment_history_url' => admin_url('admin.php?page=maca-restu-payment-history'),
        'orders' => array(
            'count' => $order_count,
            'revenue' => $revenue,
            'revenue_label' => maca_menulist_format_price($revenue),
            'sales' => $sales,
            'sales_label' => maca_menulist_format_price($sales),
            'tips' => $tips,
            'tips_label' => maca_menulist_format_price($tips),
            'avg_ticket' => $avg_ticket,
            'avg_ticket_label' => maca_menulist_format_price($avg_ticket),
            'avg_minutes' => $avg_minutes,
            'avg_minutes_label' => $avg_minutes !== null
                ? sprintf(
                    /* translators: %d: minutes */
                    _n('%d min', '%d min', $avg_minutes, 'maca-restu-pro'),
                    $avg_minutes
                )
                : '—',
            'payment_summary' => $payment_summary,
            'service_modes' => maca_menulist_daily_report_service_mode_breakdown($date),
            'hourly' => maca_menulist_daily_report_hourly_orders($date),
        ),
        'bookings' => null,
        'top_dishes' => isset($history['top_dishes']) ? $history['top_dishes'] : array(),
        'total_clicks' => isset($history['total_clicks']) ? (int) $history['total_clicks'] : 0,
    );

    if (maca_menulist_table_booking_enabled()) {
        $day_stats = maca_menulist_db_get_booking_day_stats($date);
        $occupancy = function_exists('maca_menulist_get_date_day_occupancy_display')
            ? maca_menulist_get_date_day_occupancy_display($date)
            : array(
                'percent' => 0,
                'booked_seats' => 0,
                'peak_capacity' => 0,
                'label' => '—',
            );

        $data['bookings'] = array(
            'count' => maca_menulist_db_count_bookings(
                array_merge($period_args, array('status' => 'all'))
            ),
            'confirmed_guests' => (int) $day_stats['confirmed_guests'],
            'pending' => (int) $day_stats['pending_guests'],
            'occupancy' => $occupancy,
        );
    }

    /**
     * Filter daily report payload before rendering.
     *
     * @param array<string, mixed> $data Report data.
     * @param string               $date Y-m-d.
     */
    return apply_filters('maca_menulist_daily_report_data', $data, $date);
}

/**
 * Escape text for HTML email output.
 *
 * @param string $text Text.
 * @return string
 */
function maca_menulist_daily_report_esc($text) {
    return esc_html((string) $text);
}

/**
 * Build KPI card cell HTML (email-safe table layout).
 *
 * @param string $label KPI label.
 * @param string $value KPI value.
 * @param string $accent Optional accent color.
 * @return string
 */
function maca_menulist_daily_report_kpi_cell($label, $value, $accent = '#2271b1') {
    return '<td width="25%" style="padding:8px;vertical-align:top;">
        <table width="100%" cellpadding="0" cellspacing="0" role="presentation" style="background:#f8fafc;border-radius:10px;border:1px solid #e8edf2;">
            <tr>
                <td style="padding:16px 14px;">
                    <div style="font-size:11px;font-weight:600;letter-spacing:0.04em;text-transform:uppercase;color:#64748b;margin-bottom:8px;">'
        . maca_menulist_daily_report_esc($label)
        . '</div>
                    <div style="font-size:22px;font-weight:700;color:' . esc_attr($accent) . ';line-height:1.2;">'
        . maca_menulist_daily_report_esc($value)
        . '</div>
                </td>
            </tr>
        </table>
    </td>';
}

/**
 * Render hourly order bars as an HTML table.
 *
 * @param array<int, int> $hourly Hour => count.
 * @return string
 */
function maca_menulist_daily_report_render_hourly_bars($hourly) {
    if (empty($hourly)) {
        return '<p style="margin:0;color:#64748b;font-size:14px;">'
            . esc_html__('No orders recorded for this day.', 'maca-restu-pro')
            . '</p>';
    }

    $max = max($hourly);
    if ($max < 1) {
        $max = 1;
    }

    $rows = '';
    foreach ($hourly as $hour => $count) {
        $width = max(4, (int) round(($count / $max) * 100));
        $label = sprintf('%02d:00', (int) $hour);
        $rows .= '<tr>
            <td style="padding:4px 12px 4px 0;font-size:12px;color:#64748b;white-space:nowrap;width:48px;">'
            . esc_html($label)
            . '</td>
            <td style="padding:4px 0;">
                <table width="100%" cellpadding="0" cellspacing="0" role="presentation"><tr>
                    <td width="' . (int) $width . '%" style="background:linear-gradient(90deg,#2271b1,#3b82f6);height:18px;border-radius:4px;font-size:11px;color:#fff;padding:0 8px;line-height:18px;">'
            . ($width > 12 ? esc_html((string) $count) : '')
            . '</td>
                    <td style="font-size:12px;color:#334155;padding-left:8px;">'
            . ($width <= 12 ? esc_html((string) $count) : '')
            . '</td>
                </tr></table>
            </td>
        </tr>';
    }

    return '<table width="100%" cellpadding="0" cellspacing="0" role="presentation">' . $rows . '</table>';
}

/**
 * Build HTML email body for the daily report.
 *
 * @param array<string, mixed> $data Report data from maca_menulist_daily_report_collect().
 * @return string
 */
function maca_menulist_daily_report_build_html($data) {
    $restaurant = maca_menulist_daily_report_esc($data['restaurant']);
    $date_label = maca_menulist_daily_report_esc($data['date_label']);
    $generated = maca_menulist_daily_report_esc($data['generated_at']);

    $kpi_row = '';
    if (!empty($data['orders_enabled'])) {
        $orders = $data['orders'];
        $kpi_row = '<tr>'
            . maca_menulist_daily_report_kpi_cell(__('Revenue', 'maca-restu-pro'), $orders['revenue_label'], '#0f766e')
            . maca_menulist_daily_report_kpi_cell(__('Orders', 'maca-restu-pro'), (string) $orders['count'], '#2271b1')
            . maca_menulist_daily_report_kpi_cell(__('Avg. ticket', 'maca-restu-pro'), $orders['avg_ticket_label'], '#7c3aed')
            . maca_menulist_daily_report_kpi_cell(__('Tips', 'maca-restu-pro'), $orders['tips_label'], '#ea580c')
            . '</tr>';
    }

    $orders_section = '';
    if (!empty($data['orders_enabled'])) {
        $orders = $data['orders'];
        $summary = $orders['payment_summary'];

        $service_rows = '';
        foreach ($orders['service_modes'] as $mode_key => $mode_data) {
            if ((int) $mode_data['count'] < 1) {
                continue;
            }
            $mode_label = $mode_key === 'takeaway'
                ? __('Takeaway', 'maca-restu-pro')
                : __('Dine-in (eat on premises)', 'maca-restu-pro');
            $service_rows .= '<tr>
                <td style="padding:10px 0;border-bottom:1px solid #eef2f6;color:#334155;">' . esc_html($mode_label) . '</td>
                <td style="padding:10px 0;border-bottom:1px solid #eef2f6;text-align:right;color:#334155;">' . esc_html((string) $mode_data['count']) . '</td>
                <td style="padding:10px 0;border-bottom:1px solid #eef2f6;text-align:right;font-weight:600;color:#0f172a;">'
                . esc_html(maca_menulist_format_price((float) $mode_data['revenue']))
                . '</td>
            </tr>';
        }

        $orders_section = '
        <tr><td style="padding:28px 32px 8px;">
            <h2 style="margin:0 0 16px;font-size:18px;color:#0f172a;">' . esc_html__('Orders & payments', 'maca-restu-pro') . '</h2>
            <table width="100%" cellpadding="0" cellspacing="0" role="presentation" style="margin-bottom:20px;">
                <tr>
                    <td style="padding:12px 16px;background:#f8fafc;border-radius:8px;width:33%;">
                        <div style="font-size:12px;color:#64748b;">' . esc_html__('Paid online', 'maca-restu-pro') . '</div>
                        <div style="font-size:18px;font-weight:700;color:#15803d;">' . esc_html((string) $summary['paid_online']) . '</div>
                    </td>
                    <td width="8"></td>
                    <td style="padding:12px 16px;background:#f8fafc;border-radius:8px;width:33%;">
                        <div style="font-size:12px;color:#64748b;">' . esc_html__('Paid manually', 'maca-restu-pro') . '</div>
                        <div style="font-size:18px;font-weight:700;color:#1d4ed8;">' . esc_html((string) $summary['paid_manual']) . '</div>
                    </td>
                    <td width="8"></td>
                    <td style="padding:12px 16px;background:#f8fafc;border-radius:8px;width:33%;">
                        <div style="font-size:12px;color:#64748b;">' . esc_html__('Avg. handling time', 'maca-restu-pro') . '</div>
                        <div style="font-size:18px;font-weight:700;color:#7c2d12;">' . esc_html($orders['avg_minutes_label']) . '</div>
                    </td>
                </tr>
            </table>'
            . ($service_rows !== ''
                ? '<h3 style="margin:0 0 10px;font-size:14px;color:#475569;">' . esc_html__('By service mode', 'maca-restu-pro') . '</h3>
                <table width="100%" cellpadding="0" cellspacing="0" role="presentation" style="margin-bottom:24px;">
                    <tr>
                        <th align="left" style="padding:0 0 8px;font-size:12px;color:#94a3b8;text-transform:uppercase;letter-spacing:0.04em;">' . esc_html__('Mode', 'maca-restu-pro') . '</th>
                        <th align="right" style="padding:0 0 8px;font-size:12px;color:#94a3b8;text-transform:uppercase;letter-spacing:0.04em;">' . esc_html__('Orders', 'maca-restu-pro') . '</th>
                        <th align="right" style="padding:0 0 8px;font-size:12px;color:#94a3b8;text-transform:uppercase;letter-spacing:0.04em;">' . esc_html__('Revenue', 'maca-restu-pro') . '</th>
                    </tr>'
                . $service_rows
                . '</table>'
                : '')
            . '<h3 style="margin:0 0 10px;font-size:14px;color:#475569;">' . esc_html__('Orders by hour', 'maca-restu-pro') . '</h3>'
            . maca_menulist_daily_report_render_hourly_bars($orders['hourly'])
            . '</td></tr>';
    }

    $bookings_section = '';
    if (!empty($data['bookings_enabled']) && is_array($data['bookings'])) {
        $bookings = $data['bookings'];
        $bookings_section = '
        <tr><td style="padding:8px 32px 28px;">
            <h2 style="margin:0 0 16px;font-size:18px;color:#0f172a;">' . esc_html__('Table bookings', 'maca-restu-pro') . '</h2>
            <table width="100%" cellpadding="0" cellspacing="0" role="presentation">
                <tr>
                    <td style="padding:12px 16px;background:#fdf4ff;border-radius:8px;width:25%;">
                        <div style="font-size:12px;color:#64748b;">' . esc_html__('Bookings', 'maca-restu-pro') . '</div>
                        <div style="font-size:18px;font-weight:700;color:#86198f;">' . esc_html((string) $bookings['count']) . '</div>
                    </td>
                    <td width="8"></td>
                    <td style="padding:12px 16px;background:#fdf4ff;border-radius:8px;width:25%;">
                        <div style="font-size:12px;color:#64748b;">' . esc_html__('Confirmed guests', 'maca-restu-pro') . '</div>
                        <div style="font-size:18px;font-weight:700;color:#86198f;">' . esc_html((string) $bookings['confirmed_guests']) . '</div>
                    </td>
                    <td width="8"></td>
                    <td style="padding:12px 16px;background:#fdf4ff;border-radius:8px;width:25%;">
                        <div style="font-size:12px;color:#64748b;">' . esc_html__('Pending guests', 'maca-restu-pro') . '</div>
                        <div style="font-size:18px;font-weight:700;color:#86198f;">' . esc_html((string) $bookings['pending']) . '</div>
                    </td>
                    <td width="8"></td>
                    <td style="padding:12px 16px;background:#fdf4ff;border-radius:8px;width:25%;">
                        <div style="font-size:12px;color:#64748b;">' . esc_html__('Occupancy', 'maca-restu-pro') . '</div>
                        <div style="font-size:18px;font-weight:700;color:#86198f;">' . esc_html((string) $bookings['occupancy']['label']) . '</div>
                    </td>
                </tr>
            </table>
        </td></tr>';
    }

    $dishes_section = '';
    if (!empty($data['dishes_mode']) && !empty($data['top_dishes'])) {
        $dish_rows = '';
        foreach ($data['top_dishes'] as $index => $dish) {
            $title = isset($dish->title) ? (string) $dish->title : '';
            $clicks = isset($dish->clicks) ? (int) $dish->clicks : 0;
            $dish_rows .= '<tr>
                <td style="padding:10px 0;border-bottom:1px solid #eef2f6;color:#64748b;width:28px;">' . esc_html((string) ($index + 1)) . '.</td>
                <td style="padding:10px 0;border-bottom:1px solid #eef2f6;color:#334155;">' . esc_html($title) . '</td>
                <td style="padding:10px 0;border-bottom:1px solid #eef2f6;text-align:right;font-weight:600;color:#0f172a;">' . esc_html((string) $clicks) . '</td>
            </tr>';
        }

        $dishes_section = '
        <tr><td style="padding:8px 32px 28px;">
            <h2 style="margin:0 0 12px;font-size:18px;color:#0f172a;">' . esc_html__('Top dishes (menu clicks)', 'maca-restu-pro') . '</h2>
            <table width="100%" cellpadding="0" cellspacing="0" role="presentation">' . $dish_rows . '</table>
            <p style="margin:12px 0 0;font-size:13px;color:#64748b;">'
            . esc_html(
                sprintf(
                    /* translators: %d: total menu clicks */
                    __('Total menu clicks: %d', 'maca-restu-pro'),
                    (int) $data['total_clicks']
                )
            )
            . '</p>
        </td></tr>';
    }

    $dashboard_url = esc_url($data['dashboard_url']);
    $payment_url = esc_url($data['payment_history_url']);
    $html_lang = function_exists('maca_menulist_get_site_locale')
        ? maca_menulist_get_site_locale()
        : get_locale();

    $html = '<!DOCTYPE html>
<html lang="' . esc_attr(str_replace('_', '-', $html_lang)) . '">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>' . esc_html__('Daily report', 'maca-restu-pro') . '</title>
</head>
<body style="margin:0;padding:0;background:#eef2f7;font-family:-apple-system,BlinkMacSystemFont,\'Segoe UI\',Roboto,Helvetica,Arial,sans-serif;color:#0f172a;">
<table width="100%" cellpadding="0" cellspacing="0" role="presentation" style="background:#eef2f7;padding:24px 12px;">
<tr><td align="center">
<table width="100%" cellpadding="0" cellspacing="0" role="presentation" style="max-width:640px;background:#ffffff;border-radius:16px;overflow:hidden;box-shadow:0 10px 30px rgba(15,23,42,0.08);">
    <tr>
        <td style="padding:32px;background:linear-gradient(135deg,#0f172a 0%,#1e3a5f 55%,#2271b1 100%);color:#ffffff;">
            <div style="font-size:12px;letter-spacing:0.12em;text-transform:uppercase;opacity:0.85;margin-bottom:8px;">' . esc_html__('Daily report', 'maca-restu-pro') . '</div>
            <div style="font-size:28px;font-weight:700;line-height:1.2;margin-bottom:6px;">' . $restaurant . '</div>
            <div style="font-size:16px;opacity:0.92;">' . $date_label . '</div>
        </td>
    </tr>'
    . ($kpi_row !== ''
        ? '<tr><td style="padding:24px 24px 8px;"><table width="100%" cellpadding="0" cellspacing="0" role="presentation"><tr>' . $kpi_row . '</tr></table></td></tr>'
        : '')
    . $orders_section
    . $bookings_section
    . $dishes_section
    . '<tr>
        <td style="padding:8px 32px 32px;">
            <table width="100%" cellpadding="0" cellspacing="0" role="presentation" style="background:#f8fafc;border-radius:12px;">
                <tr><td style="padding:20px;text-align:center;">
                    <p style="margin:0 0 14px;font-size:14px;color:#475569;">' . esc_html__('Open the dashboard for live details and charts.', 'maca-restu-pro') . '</p>
                    <a href="' . $dashboard_url . '" style="display:inline-block;background:#2271b1;color:#ffffff;text-decoration:none;font-weight:600;font-size:14px;padding:12px 20px;border-radius:8px;margin:0 6px 8px;">'
                    . esc_html__('Open dashboard', 'maca-restu-pro')
                    . '</a>
                    <a href="' . $payment_url . '" style="display:inline-block;background:#ffffff;color:#2271b1;text-decoration:none;font-weight:600;font-size:14px;padding:11px 19px;border-radius:8px;border:1px solid #cbd5e1;margin:0 6px 8px;">'
                    . esc_html__('Payment history', 'maca-restu-pro')
                    . '</a>
                </td></tr>
            </table>
        </td>
    </tr>
    <tr>
        <td style="padding:0 32px 28px;text-align:center;font-size:12px;color:#94a3b8;">
            ' . esc_html(
                sprintf(
                    /* translators: %s: generation date/time */
                    __('Generated %s · maca Restu', 'maca-restu-pro'),
                    $generated
                )
            ) . '
        </td>
    </tr>
</table>
</td></tr>
</table>
</body>
</html>';

    /**
     * Filter daily report HTML before sending.
     *
     * @param string               $html Email HTML.
     * @param array<string, mixed> $data Report data.
     */
    return apply_filters('maca_menulist_daily_report_html', $html, $data);
}

/**
 * Build email subject for a report date.
 *
 * @param array<string, mixed> $data Report data.
 * @return string
 */
function maca_menulist_daily_report_build_subject($data) {
    return sprintf(
        /* translators: 1: restaurant name, 2: report date */
        __('Daily report – %1$s (%2$s)', 'maca-restu-pro'),
        (string) $data['restaurant'],
        (string) $data['date_label']
    );
}

/**
 * Send daily report HTML email to recipients.
 *
 * @param string               $date        Y-m-d.
 * @param array<int, string>   $recipients  Email addresses.
 * @param bool                 $force_resend Allow sending even if already sent for this date.
 * @return bool|WP_Error
 */
function maca_menulist_daily_report_send($date, $recipients = array(), $force_resend = false) {
    if (!maca_menulist_daily_report_is_available()) {
        return new WP_Error('pro_required', __('Daily report requires an active Pro subscription.', 'maca-restu-pro'));
    }

    if (empty($recipients)) {
        $recipients = maca_menulist_daily_report_get_recipients();
    }

    if (empty($recipients)) {
        return new WP_Error('no_recipients', __('No valid email recipients configured.', 'maca-restu-pro'));
    }

    if (!$force_resend) {
        $last_date = get_option('maca_menulist_daily_report_last_sent_date', '');
        if ($last_date === $date) {
            return new WP_Error('already_sent', __('Report for this date was already sent.', 'maca-restu-pro'));
        }
    }

    $rendered = maca_menulist_daily_report_render($date);
    $html = $rendered['html'];
    $subject = $rendered['subject'];
    $headers = array('Content-Type: text/html; charset=UTF-8');

    $all_ok = true;
    foreach ($recipients as $email) {
        if (!is_email($email)) {
            continue;
        }
        if (!maca_menulist_wp_mail_as_restaurant($email, $subject, $html, $headers)) {
            $all_ok = false;
        }
    }

    if (!$all_ok) {
        return new WP_Error('send_failed', __('One or more report emails could not be sent.', 'maca-restu-pro'));
    }

    update_option('maca_menulist_daily_report_last_sent_date', $date, false);
    update_option('maca_menulist_daily_report_last_run', time(), false);
    update_option('maca_menulist_daily_report_last_report_date', $date, false);

    return true;
}

/**
 * Cron handler: send report for resolved date.
 *
 * @return void
 */
function maca_menulist_daily_report_run_cron() {
    if (!maca_menulist_daily_report_is_available() || !maca_menulist_daily_report_is_enabled()) {
        return;
    }

    $date = maca_menulist_daily_report_resolve_report_date();
    $result = maca_menulist_daily_report_send($date);

    if (is_wp_error($result) && $result->get_error_code() === 'already_sent') {
        return;
    }
}

add_action(MACA_MENULIST_DAILY_REPORT_CRON_HOOK, 'maca_menulist_daily_report_run_cron');
