<?php

if (!defined('ABSPATH')) { exit; }
if (!class_exists('AIEO_Competition_CPT')) { return; }

$cpt = AIEO_Competition_CPT::POST_TYPE;

$pid = isset($attributes['competitionId']) ? (int) $attributes['competitionId'] : 0;
if ($pid <= 0 && isset($block) && is_object($block) && !empty($block->context['postId'])) {
    $pid = (int) $block->context['postId'];
}
if ($pid <= 0 && function_exists('is_singular') && is_singular($cpt)) {
    $pid = (int) get_queried_object_id();
}
if ($pid <= 0 || get_post_type($pid) !== $cpt) { return; }

$state = AIEO_Competition_CPT::schedule_state($pid);
$start = (string) get_post_meta($pid, AIEO_Competition_CPT::META_START, true);
$end   = (string) get_post_meta($pid, AIEO_Competition_CPT::META_END, true);

$df = get_option('date_format');
$tz = new DateTimeZone('UTC');
$end_disp   = $end   !== '' ? wp_date($df, strtotime($end), $tz)   : '';
$start_disp = $start !== '' ? wp_date($df, strtotime($start), $tz) : '';

if ($state === 'ended') {
    $mod   = 'ended';
    $badge = __('Ended', 'ai-eshop-optimizer');
    $line  = ($end_disp !== '') ? sprintf(__('Ended %s', 'ai-eshop-optimizer'), $end_disp) : '';
} elseif ($state === 'before') {
    $mod   = 'before';
    $badge = __('Coming soon', 'ai-eshop-optimizer');
    $line  = ($start_disp !== '') ? sprintf(__('Starts %s', 'ai-eshop-optimizer'), $start_disp) : '';
} else {
    $mod   = 'live';
    $badge = __('Active', 'ai-eshop-optimizer');
    $line  = ($end_disp !== '') ? sprintf(__('Until %s', 'ai-eshop-optimizer'), $end_disp) : '';
}

$wrapper = function_exists('get_block_wrapper_attributes')
    ? get_block_wrapper_attributes(array('class' => 'aieo-comp-status aieo-comp-status--' . $mod))
    : 'class="aieo-comp-status aieo-comp-status--' . esc_attr($mod) . '"';

if (empty($GLOBALS['aieo_comp_badge_vars_done'])) {
    $GLOBALS['aieo_comp_badge_vars_done'] = true;
    $cs = (array) get_option('aieo_competitions_settings', array());
    $cl = sanitize_hex_color((string) (isset($cs['color_live'])   ? $cs['color_live']   : ''));
    $ce = sanitize_hex_color((string) (isset($cs['color_ended'])  ? $cs['color_ended']  : ''));
    $cb = sanitize_hex_color((string) (isset($cs['color_before']) ? $cs['color_before'] : ''));
    $vars = '';
    if ($cl) { $vars .= '--aieo-comp-badge-live:' . $cl . ';'; }
    if ($ce) { $vars .= '--aieo-comp-badge-ended:' . $ce . ';'; }
    if ($cb) { $vars .= '--aieo-comp-badge-before:' . $cb . ';'; }
    if ($vars !== '') {
        echo '<style id="aieo-comp-badge-vars">:root{' . $vars . '}</style>'; 
    }
}

echo '<div ' . $wrapper . '>'; 
echo '<span class="aieo-comp-status__badge">' . esc_html($badge) . '</span>';
if ($line !== '') {
    echo '<span class="aieo-comp-status__date">' . esc_html($line) . '</span>';
}
echo '</div>';
