<?php
/**
 * Metrics and action items for the admin management dashboard.
 *
 * @package Maca_Menu_List
 */

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

require_once MACA_MENULIST_PLUGIN_DIR . 'includes/db-dish-stats.php';
require_once MACA_MENULIST_PLUGIN_DIR . 'includes/dashboard-charts.php';
require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-dish-list-filters.php';

/**
 * Today's date (site timezone) as Y-m-d.
 *
 * @return string
 */
function maca_menulist_dashboard_today_date() {
    return wp_date('Y-m-d');
}

/**
 * Revenue from paid table orders today (payment_amount + tip when paid).
 *
 * @return float
 */
function maca_menulist_dashboard_revenue_today() {
    if (!maca_menulist_is_dishes_mode() || !maca_menulist_table_order_enabled()) {
        return 0.0;
    }

    global $wpdb;

    maca_menulist_db_ensure_table_order_tables();

    $orders_table = maca_menulist_db_table_orders_table();
    $today = maca_menulist_dashboard_today_date();

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $sum = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT COALESCE(SUM(COALESCE(payment_amount, 0) + 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',
            $today . ' 00:00:00',
            $today . ' 23:59:59',
            $today . ' 00:00:00',
            $today . ' 23:59:59',
            'partial',
            $today . ' 00:00:00',
            $today . ' 23:59:59'
        )
    );

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

/**
 * Average minutes from order creation to handled_at for orders handled today.
 *
 * @return int|null Null when no samples.
 */
function maca_menulist_dashboard_avg_order_minutes_today() {
    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();
    $today = maca_menulist_dashboard_today_date();

    // 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",
            $today . ' 00:00:00',
            $today . ' 23:59:59'
        )
    );

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

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

/**
 * Count active (in-progress) table orders.
 *
 * @return int
 */
function maca_menulist_dashboard_active_orders_count() {
    if (!maca_menulist_is_dishes_mode() || !maca_menulist_table_order_enabled()) {
        return 0;
    }

    return maca_menulist_db_count_table_orders(
        array(
            'status_filter' => 'active',
        )
    );
}

/**
 * Count unpaid active table orders (payment_status = unpaid group).
 *
 * @return int
 */
function maca_menulist_dashboard_unpaid_active_orders_count() {
    if (!maca_menulist_is_dishes_mode() || !maca_menulist_table_order_enabled()) {
        return 0;
    }

    return maca_menulist_db_count_table_orders(
        array(
            'status_filter' => 'active',
            'payment_status_filter' => 'incomplete',
        )
    );
}

/**
 * Build dashboard metrics payload for AJAX and initial render.
 *
 * @return array<string, mixed>
 */
function maca_menulist_get_dashboard_metrics() {
    $today = maca_menulist_dashboard_today_date();
    $dishes_mode = maca_menulist_is_dishes_mode();
    $orders_enabled = $dishes_mode && maca_menulist_table_order_enabled();
    $bookings_enabled = maca_menulist_table_booking_enabled();

    $metrics = array(
        'updated_at' => wp_date('Y-m-d H:i:s'),
        'updated_at_label' => wp_date(get_option('time_format')),
        'dishes_mode' => $dishes_mode,
        'orders_enabled' => $orders_enabled,
        'bookings_enabled' => $bookings_enabled,
    );

    if ($dishes_mode && function_exists('maca_menulist_get_primary_active_campaign')) {
        $active_campaign = maca_menulist_get_primary_active_campaign(
            array(
                'qr_schedule' => false,
            )
        );

        if ($active_campaign) {
            $metrics['campaign'] = array(
                'title' => maca_menulist_get_campaign_display_name($active_campaign),
                'url' => admin_url('admin.php?page=maca-restu-campaigns&action=edit&campaign_id=' . (int) $active_campaign->id),
            );
        }
    }

    if ($orders_enabled) {
        $today_args = array(
            'date_from' => $today,
            'date_to' => $today,
        );
        $payment_summary = maca_menulist_get_payment_history_summary($today_args);
        $revenue = maca_menulist_dashboard_revenue_today();
        $avg_minutes = maca_menulist_dashboard_avg_order_minutes_today();

        $metrics['orders'] = array(
            'count_today' => maca_menulist_db_count_table_orders_today(),
            'active' => maca_menulist_dashboard_active_orders_count(),
            'unpaid_active' => maca_menulist_dashboard_unpaid_active_orders_count(),
            'revenue' => $revenue,
            'revenue_label' => maca_menulist_format_price($revenue),
            '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
                )
                : '—',
            'paid_today' => (int) $payment_summary['paid'],
            'partial_today' => (int) $payment_summary['partial'],
            'pending_payment' => (int) $payment_summary['pending'],
        );
    }

    if ($bookings_enabled) {
        $day_stats = maca_menulist_db_get_booking_day_stats($today);
        $day_occupancy = function_exists('maca_menulist_get_date_day_occupancy_display')
            ? maca_menulist_get_date_day_occupancy_display($today)
            : array(
                'percent'       => 0,
                'booked_seats'  => 0,
                'peak_capacity' => 0,
                'level'         => 'low',
                'label'         => '—',
            );

        $metrics['bookings'] = array(
            'day_occupancy'    => $day_occupancy,
            'confirmed_guests' => (int) $day_stats['confirmed_guests'],
            'pending_today'    => (int) $day_stats['pending_guests'],
            'pending_all'      => maca_menulist_db_count_bookings(
                array(
                    'status' => 'pending',
                )
            ),
            'today_total'      => maca_menulist_db_count_bookings(
                array(
                    'date_from' => $today,
                    'date_to'   => $today,
                    'status'    => 'all',
                )
            ),
        );
    }

    return $metrics;
}

/**
 * Count active dishes missing an image.
 *
 * @return int
 */
function maca_menulist_dashboard_count_dishes_without_image() {
    if (!maca_menulist_is_dishes_mode()) {
        return 0;
    }

    global $wpdb;

    $table = maca_menulist_db_dishes_table();

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    return (int) $wpdb->get_var(
        "SELECT COUNT(*) FROM $table WHERE is_active = 1 AND (image_url IS NULL OR image_url = '')"
    );
}

/**
 * Count active dishes with no allergen links (only when allergens exist).
 *
 * @return int
 */
function maca_menulist_dashboard_count_dishes_without_allergens() {
    if (!maca_menulist_is_dishes_mode()) {
        return 0;
    }

    $allergens = maca_menulist_db_get_allergens();
    if (empty($allergens)) {
        return 0;
    }

    global $wpdb;

    $dishes_table = maca_menulist_db_dishes_table();
    $link_table = maca_menulist_db_dish_allergens_table();

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    return (int) $wpdb->get_var(
        "SELECT COUNT(*) FROM $dishes_table d
        WHERE d.is_active = 1
        AND NOT EXISTS (SELECT 1 FROM $link_table da WHERE da.dish_id = d.id)"
    );
}

/**
 * Count active dishes missing required title fields.
 *
 * @return int
 */
function maca_menulist_dashboard_count_dishes_missing_title() {
    if (!maca_menulist_is_dishes_mode()) {
        return 0;
    }

    global $wpdb;

    $table = maca_menulist_db_dishes_table();

    if (maca_menulist_admin_show_local_content_fields()) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        return (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM $table
            WHERE is_active = 1
            AND TRIM(COALESCE(title, '')) = ''
            AND TRIM(COALESCE(title_en, '')) = ''"
        );
    }

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    return (int) $wpdb->get_var(
        "SELECT COUNT(*) FROM $table
        WHERE is_active = 1
        AND TRIM(COALESCE(title, '')) = ''"
    );
}

/**
 * Count active dishes without a price.
 *
 * @return int
 */
function maca_menulist_dashboard_count_dishes_without_price() {
    if (!maca_menulist_is_dishes_mode()) {
        return 0;
    }

    global $wpdb;

    $table = maca_menulist_db_dishes_table();

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    return (int) $wpdb->get_var(
        "SELECT COUNT(*) FROM $table
        WHERE is_active = 1
        AND (price IS NULL OR price <= 0)"
    );
}

/**
 * Action items / todos for the dashboard.
 *
 * @return array<int, array<string, mixed>>
 */
function maca_menulist_get_dashboard_action_items() {
    $items = array();

    if (maca_menulist_is_dishes_mode()) {
        $no_image = maca_menulist_dashboard_count_dishes_without_image();
        if ($no_image > 0) {
            $items[] = array(
                'key' => 'dishes_no_image',
                'severity' => 'warning',
                'count' => $no_image,
                'label' => sprintf(
                    /* translators: %d: dish count */
                    _n('%d aktiv rätt saknar bild', '%d aktiva rätter saknar bild', $no_image, 'maca-restu-pro'),
                    $no_image
                ),
                'url' => maca_menulist_admin_dishes_list_url('no_image'),
            );
        }

        $no_allergens = maca_menulist_dashboard_count_dishes_without_allergens();
        if ($no_allergens > 0) {
            $items[] = array(
                'key' => 'dishes_no_allergens',
                'severity' => 'warning',
                'count' => $no_allergens,
                'label' => sprintf(
                    /* translators: %d: dish count */
                    _n('%d rätt saknar allergeninfo', '%d rätter saknar allergeninfo', $no_allergens, 'maca-restu-pro'),
                    $no_allergens
                ),
                'url' => maca_menulist_admin_dishes_list_url('no_allergens'),
            );
        }

        $no_title = maca_menulist_dashboard_count_dishes_missing_title();
        if ($no_title > 0) {
            $items[] = array(
                'key' => 'dishes_no_title',
                'severity' => 'error',
                'count' => $no_title,
                'label' => sprintf(
                    /* translators: %d: dish count */
                    _n('%d rätt saknar namn', '%d rätter saknar namn', $no_title, 'maca-restu-pro'),
                    $no_title
                ),
                'url' => maca_menulist_admin_dishes_list_url('no_title'),
            );
        }

        $no_price = maca_menulist_dashboard_count_dishes_without_price();
        if ($no_price > 0) {
            $items[] = array(
                'key' => 'dishes_no_price',
                'severity' => 'warning',
                'count' => $no_price,
                'label' => sprintf(
                    /* translators: %d: dish count */
                    _n('%d rätt saknar pris', '%d rätter saknar pris', $no_price, 'maca-restu-pro'),
                    $no_price
                ),
                'url' => maca_menulist_admin_dishes_list_url('no_price'),
            );
        }
    }

    if (maca_menulist_table_booking_enabled()) {
        $pending_bookings = maca_menulist_db_count_bookings(array('status' => 'pending'));
        if ($pending_bookings > 0) {
            $items[] = array(
                'key' => 'bookings_pending',
                'severity' => 'info',
                'count' => $pending_bookings,
                'label' => sprintf(
                    /* translators: %d: booking count */
                    _n('%d bokning väntar på bekräftelse', '%d bokningar väntar på bekräftelse', $pending_bookings, 'maca-restu-pro'),
                    $pending_bookings
                ),
                'url' => admin_url('admin.php?page=maca-restu-bookings'),
            );
        }
    }

    if (maca_menulist_is_dishes_mode() && maca_menulist_table_order_enabled()) {
        $unpaid = maca_menulist_db_count_table_orders(
            array(
                'status_filter' => 'active',
                'payment_status_filter' => 'incomplete',
            )
        );
        if ($unpaid > 0) {
            $items[] = array(
                'key' => 'orders_unpaid',
                'severity' => 'info',
                'count' => $unpaid,
                'label' => sprintf(
                    /* translators: %d: order count */
                    _n('%d aktiv order är inte betald ännu', '%d aktiva ordrar är inte betalda ännu', $unpaid, 'maca-restu-pro'),
                    $unpaid
                ),
                'url' => admin_url('admin.php?page=maca-restu-orders&status_filter=active'),
            );
        }

        if (
            function_exists('maca_menulist_table_order_waiter_page_enabled')
            && maca_menulist_table_order_waiter_page_enabled()
            && function_exists('maca_menulist_has_configured_waiters')
            && !maca_menulist_has_configured_waiters()
        ) {
            $items[] = array(
                'key' => 'waiters_setup',
                'severity' => 'info',
                'count' => 0,
                'label' => __('Lägg till servitörer och tilldela bord (valfritt filter på servitörsskärmen)', 'maca-restu-pro'),
                'url' => function_exists('maca_menulist_personal_admin_url') ? maca_menulist_personal_admin_url(array('tab' => 'waiters')) : admin_url('admin.php?page=maca-restu-personal&tab=waiters'),
            );
        }
    }

    return $items;
}

/**
 * Quick-action buttons for the dashboard.
 *
 * @return array<int, array<string, string>>
 */
function maca_menulist_get_dashboard_quick_actions() {
    $actions = array();

    if (maca_menulist_is_dishes_mode()) {
        $actions[] = array(
            'key' => 'add_dish',
            'label' => __('Lägg till rätt', 'maca-restu-pro'),
            'url' => admin_url('admin.php?page=maca-restu-dishes&action=add'),
            'class' => 'button button-primary',
        );
        $actions[] = array(
            'key' => 'dishes',
            'label' => __('Alla rätter', 'maca-restu-pro'),
            'url' => admin_url('admin.php?page=maca-restu-dishes'),
            'class' => 'button',
        );
        $actions[] = array(
            'key' => 'dish_categories',
            'label' => __('Menykategorier', 'maca-restu-pro'),
            'url' => admin_url('admin.php?page=maca-restu-dish-categories'),
            'class' => 'button',
        );
        $actions[] = array(
            'key' => 'campaign_menus',
            'label' => __('Kampanjmenyer', 'maca-restu-pro'),
            'url' => admin_url('admin.php?page=maca-restu-campaigns'),
            'class' => 'button',
        );
        $actions[] = array(
            'key' => 'allergens',
            'label' => __('Allergener', 'maca-restu-pro'),
            'url' => admin_url('admin.php?page=maca-restu-allergens'),
            'class' => 'button',
        );
        $actions[] = array(
            'key' => 'dish_stats',
            'label' => __('Rättstatistik', 'maca-restu-pro'),
            'url' => admin_url('admin.php?page=maca-restu-dish-stats'),
            'class' => 'button',
        );
    } else {
        $actions[] = array(
            'key' => 'add_menu',
            'label' => __('Lägg till menyfil', 'maca-restu-pro'),
            'url' => admin_url('admin.php?page=maca-restu-menus&action=add'),
            'class' => 'button button-primary',
        );
        $actions[] = array(
            'key' => 'menus',
            'label' => __('Menyer', 'maca-restu-pro'),
            'url' => admin_url('admin.php?page=maca-restu-menus'),
            'class' => 'button',
        );
        $actions[] = array(
            'key' => 'categories',
            'label' => __('Kategorier', 'maca-restu-pro'),
            'url' => admin_url('admin.php?page=maca-restu'),
            'class' => 'button',
        );
    }

    if (maca_menulist_is_dishes_mode() && maca_menulist_table_order_enabled()) {
        $actions[] = array(
            'key' => 'orders',
            'label' => __('Beställningar', 'maca-restu-pro'),
            'url' => admin_url('admin.php?page=maca-restu-orders'),
            'class' => 'button',
        );

        if (function_exists('maca_menulist_table_order_waiter_page_enabled') && maca_menulist_table_order_waiter_page_enabled()) {
            $actions[] = array(
                'key' => 'waiter_board',
                'label' => __('Servitörsskärm', 'maca-restu-pro'),
                'url' => maca_menulist_get_waiter_order_url(),
                'class' => 'button',
                'target' => '_blank',
            );
        }

        if (function_exists('maca_menulist_waiters_feature_available') && maca_menulist_waiters_feature_available()) {
            $actions[] = array(
                'key' => 'waiters',
                'label' => __('Servitörer', 'maca-restu-pro'),
                'url' => function_exists('maca_menulist_personal_admin_url') ? maca_menulist_personal_admin_url(array('tab' => 'waiters')) : admin_url('admin.php?page=maca-restu-personal&tab=waiters'),
                'class' => 'button',
            );
        }

        if (function_exists('maca_menulist_table_order_kitchen_page_enabled') && maca_menulist_table_order_kitchen_page_enabled()) {
            $actions[] = array(
                'key' => 'kitchen_board',
                'label' => __('Köksskärm', 'maca-restu-pro'),
                'url' => maca_menulist_get_kitchen_order_url(),
                'class' => 'button',
                'target' => '_blank',
            );
        }
    }

    if (maca_menulist_table_booking_enabled()) {
        $actions[] = array(
            'key' => 'bookings',
            'label' => __('Bokningar', 'maca-restu-pro'),
            'url' => admin_url('admin.php?page=maca-restu-bookings'),
            'class' => 'button',
        );
        $actions[] = array(
            'key' => 'bookings_floor',
            'label' => __('Salongsöversikt', 'maca-restu-pro'),
            'url' => admin_url('admin.php?page=maca-restu-bookings&tab=floor'),
            'class' => 'button',
        );
    }

    $actions[] = array(
        'key' => 'qr',
        'label' => __('QR-koder', 'maca-restu-pro'),
        'url' => admin_url('admin.php?page=maca-restu-qr'),
        'class' => 'button',
    );

    $actions[] = array(
        'key' => 'settings',
        'label' => __('Inställningar', 'maca-restu-pro'),
        'url' => admin_url('admin.php?page=maca-restu-settings'),
        'class' => 'button',
    );

    return $actions;
}

/**
 * Revenue from 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_dashboard_revenue_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(payment_amount, 0) + 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);
}

/**
 * History / period stats for the dashboard.
 *
 * @param string $date_from Start date Y-m-d.
 * @param string $date_to   End date Y-m-d.
 * @return array<string, mixed>
 */
function maca_menulist_get_dashboard_history($date_from = '', $date_to = '') {
    $range = maca_menulist_normalize_stats_date_range($date_from, $date_to);
    $history = array(
        'date_from' => $range['date_from'],
        'date_to' => $range['date_to'],
        'period_label' => $range['label'],
        'dishes_mode' => maca_menulist_is_dishes_mode(),
    );

    if (maca_menulist_is_dishes_mode()) {
        $history['top_dishes'] = maca_menulist_db_get_top_dishes_by_clicks(
            $range['date_from'],
            $range['date_to'],
            5
        );
        $history['total_clicks'] = maca_menulist_db_count_dish_clicks_in_range(
            $range['date_from'],
            $range['date_to']
        );
        $history['stats_url'] = add_query_arg(
            array(
                'page' => 'maca-restu-dish-stats',
                'date_from' => $range['date_from'],
                'date_to' => $range['date_to'],
            ),
            admin_url('admin.php')
        );
    }

    if (maca_menulist_is_dishes_mode() && maca_menulist_table_order_enabled()) {
        $period_args = array(
            'date_from' => $range['date_from'],
            'date_to' => $range['date_to'],
        );
        $summary = maca_menulist_get_payment_history_summary($period_args);
        $revenue = maca_menulist_dashboard_revenue_for_range($range['date_from'], $range['date_to']);

        $history['orders'] = array(
            'count' => maca_menulist_db_count_table_orders($period_args),
            'revenue' => $revenue,
            'revenue_label' => maca_menulist_format_price($revenue),
            'paid' => (int) $summary['paid'],
        );
    }

    if (maca_menulist_table_booking_enabled()) {
        $history['bookings'] = array(
            'count' => maca_menulist_db_count_bookings(
                array(
                    'date_from' => $range['date_from'],
                    'date_to' => $range['date_to'],
                    'status' => 'all',
                )
            ),
            'pending' => maca_menulist_db_count_bookings(
                array(
                    'date_from' => $range['date_from'],
                    'date_to' => $range['date_to'],
                    'status' => 'pending',
                )
            ),
        );
    }

    $history['charts'] = maca_menulist_get_dashboard_charts($range['date_from'], $range['date_to']);

    return $history;
}

/**
 * Full dashboard payload for AJAX refresh.
 *
 * @param string $date_from Optional history start date.
 * @param string $date_to   Optional history end date.
 * @return array<string, mixed>
 */
function maca_menulist_get_dashboard_payload($date_from = '', $date_to = '') {
    if ($date_from === '' && $date_to === '') {
        $today = maca_menulist_dashboard_today_date();
        $date_from = $today;
        $date_to = $today;
    }

    return array(
        'metrics' => maca_menulist_get_dashboard_metrics(),
        'actions' => maca_menulist_get_dashboard_action_items(),
        'history' => maca_menulist_get_dashboard_history($date_from, $date_to),
    );
}
