<?php

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;


/**
 * Sanitizes the values of an array recursivelly
 *
 * @param array $array
 *
 * @return array
 *
 */
function _wpsbc_array_sanitize_text_field( $array = array() ) {

    if( empty( $array ) || ! is_array( $array ) )
        return array();

    foreach( $array as $key => $value ) {

        if( is_array( $value ) )
            $array[$key] = _wpsbc_array_sanitize_text_field( $value );

        else
            $array[$key] = sanitize_text_field( $value );

    }

    return $array;

}


/**
 * Sanitizes the values of an array recursivelly and allows HTML tags
 *
 * @param array $array
 *
 * @return array
 *
 */
function _wpsbc_array_wp_kses_post( $array = array() ) {

    if( empty( $array ) || ! is_array( $array ) )
        return array();

    foreach( $array as $key => $value ) {

        if( is_array( $value ) )
            $array[$key] = _wpsbc_array_wp_kses_post( $value );

        else
            $array[$key] = wp_kses_post( $value );

    }

    return $array;

}

/**
 * Returns the current locale
 *
 * @return string
 *
 */
function wpsbc_get_locale() {

    return substr( get_locale(), 0, 2 );

}

/**
 * Helper function to convert the php date format to jQuery UI compatible date format
 * 
 */
function wpsbc_convert_php_to_jqueryui_format($php_format)
{
    $symbols = array(
        // Day
        'd' => 'dd',
        'D' => 'D',
        'j' => 'd',
        'l' => 'DD',
        'N' => '',
        'S' => '',
        'w' => '',
        'z' => 'o',
        // Week
        'W' => '',
        // Month
        'F' => 'MM',
        'm' => 'mm',
        'M' => 'M',
        'n' => 'm',
        't' => '',
        // Year
        'L' => '',
        'o' => '',
        'Y' => 'yy',
        'y' => 'y',
        // Time
        'a' => '',
        'A' => '',
        'B' => '',
        'g' => '',
        'G' => '',
        'h' => '',
        'H' => '',
        'i' => '',
        's' => '',
        'u' => '',
    );
    $jqueryui_format = "";
    $escaping = false;
    for ($i = 0; $i < strlen($php_format); $i++) {
        $char = $php_format[$i];
        if ($char === '\\') // PHP date format escaping character
        {
            $i++;
            if ($escaping) {
                $jqueryui_format .= $php_format[$i];
            } else {
                $jqueryui_format .= '\'' . $php_format[$i];
            }

            $escaping = true;
        } else {
            if ($escaping) {$jqueryui_format .= "'";
                $escaping = false;}
            if (isset($symbols[$char])) {
                $jqueryui_format .= $symbols[$char];
            } else {
                $jqueryui_format .= $char;
            }

        }
    }
    return $jqueryui_format;
}

/**
 * Replace date_i18n with wp_date, but fallback to date_i18n if WP < 5.3
 *
 * @param string $format
 * @param string $timestamp
 * @param string $language
 *
 * @return string
 *
 */
function wpsbc_date_i18n($format, $timestamp, $language = false)
{

    if ($language !== false) {
        $original_locale = get_locale();
        switch_to_locale(wpsbc_language_to_locale($language));
    }

    if (function_exists('wp_date')) {
        $zone = apply_filters('wpsbc_date_timezone', new DateTimeZone('UTC'));
        $date = wp_date($format, $timestamp, $zone);
    } else {
        $date = date_i18n($format, $timestamp);
    }

    if ($language !== false) {
        switch_to_locale($original_locale);
    }

    return $date;
}

/**
 * Refresh an icalendar feed
 * 
 * @param int $calendar_id
 * 
 */
add_action('init', function () {
    if (!isset($_GET['wpsbc-refresh-ical'])) {
        return;
    }

    $start = microtime(true);

    echo "<pre>";

    echo 'Refreshing icalendar feeds.' . PHP_EOL . PHP_EOL;

    $calendars = wpsbc_get_calendars(['status' => 'active']);

    $num_calendars = 0;
    $num_feeds = 0;

    foreach ($calendars as $calendar) {
        $calendar_id = $calendar->get('id');
        
        // Get iCal feeds
        $ical_feeds = wpsbc_get_calendar_meta_ical_feeds($calendar_id);

        echo 'Refreshing feeds for calendar #' . $calendar_id . '.' . PHP_EOL;

        if (empty($ical_feeds)) {
            echo '- no feeds found.' . PHP_EOL . PHP_EOL;
            continue;
        }

        $num_calendars++;

        // Fetch new feeds
        foreach ($ical_feeds as $ical_feed) {

            if (empty($ical_feed['id']))
                continue;

            if (empty($ical_feed['url']))
                continue;

            $num_feeds++;

            echo '- refreshing <strong>' . $ical_feed['name'] . '</strong> (' . $ical_feed['url'] . ') for calendar #' . $calendar_id . '.' . PHP_EOL;

            $ical_contents = wp_remote_get($ical_feed['url'], array('timeout' => 30, 'user-agent' => 'Mozilla/5.0 ( Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0'));

            if (wp_remote_retrieve_response_code($ical_contents) != 200)
                continue;

            $ical_contents = wp_remote_retrieve_body($ical_contents);

            $ical_contents = trim($ical_contents);

            if (0 !== strpos($ical_contents, 'BEGIN:VCALENDAR') || false === strpos($ical_contents, 'END:VCALENDAR'))
                continue;

            $ical_contents = addslashes($ical_contents);

            $ical_feed['file_contents'] = $ical_contents;
            $ical_feed['last_updated']  = current_time('Y-m-d H:i:s');

            wpsbc_update_calendar_meta($calendar_id, 'ical_feed_' . $ical_feed['id'], $ical_feed);
        }

        echo PHP_EOL;
    }

    $end = microtime(true);

    $time = $end - $start;

    echo "Refreshing icalendar feeds completed in " . round($time, 2) . " seconds. " . PHP_EOL . $num_feeds . " feeds were updated for " . $num_calendars . " calendars." . PHP_EOL;
    echo "</pre>";



    die();
});
