<?php
/**
 * Schedule preview helpers for PDF/image menus (website vs QR).
 *
 * @package Maca_Menu_List_Pro
 */

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

/**
 * Build full preview payload for admin AJAX and initial page render.
 *
 * @param int $timestamp Unix timestamp in site timezone context.
 * @return array<string, mixed>
 */
function maca_menulist_build_schedule_preview($timestamp) {
    $timestamp = (int) $timestamp;
    $mysql = maca_menulist_unix_to_site_mysql($timestamp);
    $diagnostics = maca_menulist_schedule_preview_build_diagnostics($timestamp);

    return array(
        'label' => maca_menulist_format_wp_datetime($mysql),
        'datetime_local' => maca_menulist_wp_timestamp_to_datetime_local($timestamp),
        'schedule_mysql' => $mysql,
        'diagnostics' => $diagnostics,
        'website' => maca_menulist_schedule_preview_render_panel_html($diagnostics['categories'], 'website'),
        'qr' => maca_menulist_schedule_preview_render_panel_html($diagnostics['categories'], 'qr'),
        'preview_mode' => 'files',
    );
}

/**
 * Category visibility rows for a preview moment.
 *
 * @param int $timestamp Unix timestamp.
 * @return array<string, mixed>
 */
function maca_menulist_schedule_preview_build_diagnostics($timestamp) {
    $categories = maca_menulist_db_get_categories(true);
    $rows = array();

    foreach ($categories as $category) {
        $rows[] = maca_menulist_schedule_preview_category_row($category, $timestamp);
    }

    return array(
        'categories' => $rows,
    );
}

/**
 * Explain one category at a preview moment.
 *
 * @param object $category  Category row.
 * @param int    $timestamp Unix timestamp.
 * @return array<string, mixed>
 */
function maca_menulist_schedule_preview_category_row($category, $timestamp) {
    $category_id = (int) $category->id;
    $published = maca_menulist_get_published_menus_for_category($category_id, $timestamp);
    $website_menu = maca_menulist_get_menu_for_website($category_id, $timestamp);
    $qr_menu = maca_menulist_get_active_menu_for_category($category_id, $timestamp);

    if (empty($published)) {
        $website_code = maca_menulist_schedule_preview_hidden_reason($category_id, $timestamp);
        $website_menu_title = '';
    } elseif ($website_menu && maca_menulist_menu_matches_schedule($website_menu, $timestamp)) {
        $website_code = 'visible_live';
        $website_menu_title = (string) $website_menu->title;
    } else {
        $website_code = 'visible_outside_hours';
        $website_menu_title = $website_menu ? (string) $website_menu->title : '';
    }

    if ($qr_menu) {
        $qr_code = 'visible';
        $qr_menu_title = (string) $qr_menu->title;
    } elseif (!empty($published)) {
        $qr_code = 'outside_hours';
        $qr_menu_title = '';
    } else {
        $qr_code = maca_menulist_schedule_preview_hidden_reason($category_id, $timestamp);
        $qr_menu_title = '';
    }

    return array(
        'id' => $category_id,
        'name' => (string) $category->name,
        'website' => $website_code,
        'website_label' => maca_menulist_schedule_preview_reason_label($website_code, 'website', $website_menu, $timestamp),
        'website_menu' => $website_menu_title,
        'qr' => $qr_code,
        'qr_label' => maca_menulist_schedule_preview_reason_label($qr_code, 'qr', $qr_menu, $timestamp),
        'qr_menu' => $qr_menu_title,
    );
}

/**
 * Best-effort reason when no published menu exists at preview time.
 *
 * @param int $category_id Category ID.
 * @param int $timestamp   Unix timestamp.
 * @return string
 */
function maca_menulist_schedule_preview_hidden_reason($category_id, $timestamp) {
    $menus = maca_menulist_db_get_menus_for_category($category_id);

    if (empty($menus)) {
        return 'no_menu';
    }

    $mysql_now = maca_menulist_unix_to_site_mysql((int) $timestamp);
    $has_active = false;
    $all_scheduled = true;
    $all_expired = true;
    $all_inactive = true;

    foreach ($menus as $menu) {
        if (!empty($menu->is_active)) {
            $has_active = true;
            $all_inactive = false;
        }

        if (empty($menu->start_date) || $menu->start_date <= $mysql_now) {
            $all_scheduled = false;
        }

        if (empty($menu->end_date) || $menu->end_date >= $mysql_now) {
            $all_expired = false;
        }
    }

    if ($all_inactive) {
        return 'inactive';
    }

    if ($all_scheduled) {
        return 'scheduled';
    }

    if ($all_expired) {
        return 'expired';
    }

    if (!$has_active) {
        return 'inactive';
    }

    return 'no_menu';
}

/**
 * Human-readable label for a preview status code.
 *
 * @param string      $code      Status code.
 * @param string      $context   website or qr.
 * @param object|null $menu      Menu object when relevant.
 * @param int|null    $timestamp Preview timestamp.
 * @return string
 */
function maca_menulist_schedule_preview_reason_label($code, $context, $menu, $timestamp = null) {
    switch ($code) {
        case 'visible_live':
            return __('Visible — live now', 'maca-restu-pro');
        case 'visible_outside_hours':
            if ($menu && $timestamp !== null) {
                return sprintf(
                    /* translators: %s: schedule summary */
                    __('Visible — serving hours: %s (not live now)', 'maca-restu-pro'),
                    maca_menulist_format_schedule_summary($menu)
                );
            }
            return __('Visible — outside live hours', 'maca-restu-pro');
        case 'visible':
            return __('Visible — live now', 'maca-restu-pro');
        case 'outside_hours':
            return __('Hidden — outside serving hours', 'maca-restu-pro');
        case 'inactive':
            return __('Hidden — no active menus', 'maca-restu-pro');
        case 'scheduled':
            return __('Hidden — scheduled for later', 'maca-restu-pro');
        case 'expired':
            return __('Hidden — past end date', 'maca-restu-pro');
        case 'no_menu':
            return __('Hidden — no menu in this category', 'maca-restu-pro');
        default:
            return $context === 'qr'
                ? __('Hidden', 'maca-restu-pro')
                : __('Hidden — not shown on website', 'maca-restu-pro');
    }
}

/**
 * Render a guest-facing category summary for website or QR preview panels.
 *
 * @param array<int, array<string, mixed>> $rows    Diagnostic rows.
 * @param string                           $context website or qr.
 * @return string
 */
function maca_menulist_schedule_preview_render_panel_html($rows, $context) {
    if (!is_array($rows)) {
        $rows = array();
    }

    $items = array();

    foreach ($rows as $row) {
        if ($context === 'qr') {
            if (($row['qr'] ?? '') !== 'visible' || empty($row['qr_menu'])) {
                continue;
            }

            $items[] = array(
                'name' => (string) ($row['name'] ?? ''),
                'menu' => (string) ($row['qr_menu'] ?? ''),
                'badge' => __('Live', 'maca-restu-pro'),
                'badge_class' => 'live',
            );
            continue;
        }

        $website_code = (string) ($row['website'] ?? '');
        if (!in_array($website_code, array('visible_live', 'visible_outside_hours'), true)) {
            continue;
        }

        $items[] = array(
            'name' => (string) ($row['name'] ?? ''),
            'menu' => (string) ($row['website_menu'] ?? ''),
            'badge' => $website_code === 'visible_live'
                ? __('Live', 'maca-restu-pro')
                : __('Outside hours', 'maca-restu-pro'),
            'badge_class' => $website_code === 'visible_live' ? 'live' : 'outside-hours',
        );
    }

    if (empty($items)) {
        return '<p class="maca-schedule-preview-empty">' . esc_html__('No categories visible at this time.', 'maca-restu-pro') . '</p>';
    }

    ob_start();
    echo '<ul class="maca-schedule-preview-category-list">';
    foreach ($items as $item) {
        echo '<li class="maca-schedule-preview-category-item">';
        echo '<div class="maca-schedule-preview-category-head">';
        echo '<strong class="maca-schedule-preview-category-name">' . esc_html($item['name']) . '</strong>';
        echo '<span class="maca-schedule-preview-badge maca-schedule-preview-badge--' . esc_attr($item['badge_class']) . '">';
        echo esc_html($item['badge']);
        echo '</span>';
        echo '</div>';
        if ($item['menu'] !== '') {
            echo '<p class="maca-schedule-preview-menu-title">' . esc_html($item['menu']) . '</p>';
        }
        echo '</li>';
    }
    echo '</ul>';

    return (string) ob_get_clean();
}
