<?php
/**
 * Coupon calendar view.
 *
 * @var string $nonce
 * @package SuiteMkt3k
 */

defined( 'ABSPATH' ) || exit;

use SuiteMkt3k\Admin\View_Inline_Assets;
use SuiteMkt3k\Utils\I18n;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
$coupons = \SuiteMkt3k\Modules\Coupons\Coupon_Manager::list( 500 );
$events  = array();

foreach ( $coupons as $c ) {
	if ( ! $c['starts_at'] && ! $c['ends_at'] ) {
		continue;
	}

	$events[] = array(
		'id'    => (int) $c['id'],
		'title' => $c['name'] . ' (' . $c['status'] . ')',
		'start' => $c['starts_at'] ?: gmdate( 'Y-m-d' ),
		'end'   => $c['ends_at'] ?: null,
		'url'   => add_query_arg( array( 'view' => 'edit', 'id' => (int) $c['id'] ), admin_url( 'admin.php?page=suitemkt3k-coupons' ) ),
		'color' => 'active' === $c['status'] ? '#10B981' : ( 'scheduled' === $c['status'] ? '#2AB2E5' : '#94A3B8' ),
	);
}

$cal_js = SUITEMKT3K_PATH . 'assets/admin/js/fullcalendar.min.js';
$has_fc = file_exists( $cal_js );
?>

<div class="wmk-card">
	<div class="wmk-card-header">
		<h3><?php esc_html_e( 'Coupon calendar', 'suitemkt3k' ); ?></h3>
		<a class="wmk-btn wmk-btn-ghost" href="<?php echo esc_url( admin_url( 'admin.php?page=suitemkt3k-coupons' ) ); ?>"><?php esc_html_e( 'Back to list', 'suitemkt3k' ); ?></a>
	</div>
	<div class="wmk-card-body">
		<?php if ( $has_fc ) : ?>
			<div id="wmk-coupon-calendar"></div>
			<?php
			View_Inline_Assets::script_var(
				'SuiteMkt3kCalendar',
				array(
					'events' => $events,
					'locale' => I18n::locale_to_short( I18n::get_active_locale() ),
				)
			);
			?>
		<?php else : ?>
			<div class="wmk-flash wmk-flash-warning"><?php esc_html_e( 'Drop FullCalendar (MIT) at assets/admin/js/fullcalendar.min.js to enable the visual calendar. Meanwhile, here is a fallback list:', 'suitemkt3k' ); ?></div>
			<ul class="wmk-activity">
				<?php foreach ( $events as $ev ) : ?>
					<li><strong><?php echo esc_html( $ev['title'] ); ?></strong> &nbsp; <small><?php echo esc_html( $ev['start'] . ( $ev['end'] ? ' → ' . $ev['end'] : '' ) ); ?></small></li>
				<?php endforeach; ?>
				<?php if ( ! $events ) : ?>
					<li><?php esc_html_e( 'No scheduled campaigns yet.', 'suitemkt3k' ); ?></li>
				<?php endif; ?>
			</ul>
		<?php endif; ?>
	</div>
</div>
