<?php
// pages/components/calendar_subscribe_popover.php
require_once BEEZUI_ROOT . '/components/index.php';

use Components\Base;
use Components\Button;
use Components\ConfigStore;
use Components\Router;
use Components\Ui\CalendarSubscribe;

$token = ConfigStore::getCalendarFeedToken();
$filter = isset($state['filter']) ? $state['filter'] : strtolower((string)mh_get('filter', 'all', 'string'));
$host = $_SERVER['HTTP_HOST'] ?? 'mailbeez.internal';
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$apiBaseUrl = $protocol . '://' . $host . MH_DIR_WS_CATALOG . 'mailhive.php/api/public/v1.0/calendar/feed/';
$rotateUrl = Router::url('calendar_rotate_token', ['partial' => 1]);

$labels = [
    'all' => mh_lng('UI_CALENDAR_FILTER_ALL', 'All'),
    'newsletter' => mh_lng('UI_CALENDAR_FILTER_NEWSLETTER', 'Newsletter'),
    'automations' => mh_lng('UI_CALENDAR_FILTER_AUTOMATIONS', 'Automations'),
];

// If this is an HTMX request for the modal content, return only the component
if (isset($state['partial']) || mh_get('partial')) {
    echo CalendarSubscribe::render([
        'token' => $token,
        'filter' => $filter,
        'baseUrl' => $apiBaseUrl,
        'rotateUrl' => $rotateUrl,
        'labels' => $labels,
    ]);
    return;
}

// Otherwise, render the trigger button that opens the modal
echo Button::render(mh_lng('UI_CALENDAR_SUBSCRIBE', 'Subscribe'), [
    'variant' => 'ghost',
    'size' => 'sm',
    'icon' => Base::SVG_OUTLINE_CALENDAR_ADD,
    'iconPosition' => 'front',
    'attrs' => [
        'command' => 'show-modal',
        'commandfor' => 'config-modal',
        'data-title' => mh_lng('UI_CALENDAR_SUBSCRIBE_TITLE', 'Subscribe to Calendar'),
        'data-size' => 'xl',
        'hx-get' => Router::url('calendar_subscribe_popover', ['partial' => 1, 'filter' => $filter]),
        'hx-target' => '#config-modal-body',
        'hx-swap' => 'innerHTML',
    ]
]);
