<?php
$pdo = new PDO("mysql:host=".$GLOBALS['myservername'].";dbname=".$GLOBALS['mydb'].';charset=utf8', $GLOBALS['mylogin'], $GLOBALS['mypass']);
$GLOBALS["pdo_conn"] = $pdo;

$select_collection = $GLOBALS['pdo_conn']->prepare("SELECT * FROM main_collection WHERE main_collection_setup_id = :main_collection_setup_id ORDER BY sorting ASC");
$select_collection->execute(array(':main_collection_setup_id' => '47'));
$res_collection = $select_collection->fetchALL(PDO::FETCH_ASSOC);
$GLOBALS['array'] = array();

$weekday = array("Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag");
$GLOBALS['weekday_en'] = array("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday");
$month = array("Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember");
$GLOBALS['month_en'] = array("january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december");
$ordinal = array("ersten", "zweiten", "dritten", "vierten", "letzten");
$repeating_type_en= array("daily", "weekly", "monthly", "yearly");
$repeating_type = array("Tächlich", "Wöchentlich", "Monatlich", "Jährlich");

foreach ($res_collection as $key => $value) {
    $serial = selectCalendarSerial($value['id']);
    $start_date = new DateTime($value['validity_from']);
    $end_date = new DateTime($value['validity_to']);
    switch ($serial['repeating_type']) {
        case 'daily':
            setDailyEvent($serial, $start_date, $end_date, $value['id']);
            break;
        case 'weekly':
            setWeeklyEvent($serial, $start_date, $end_date, $value['id']);
            break;
        case 'monthly':
            setMonthlyEvent($serial, $start_date, $end_date, $value['id']);
            break;
        case 'yearly':
            setYearlyEvent($serial, $start_date, $end_date, $value['id']);
            break;
        default:
            break;
    }
}

function setDailyEvent($serial, $start_date, $end_date, $collection_id){
    $date = new DateTime($start_date->format('Y-m-d'));
    while ($date <= $end_date) {
        buildArray($collection_id, $date);
        if($serial == 0){
            $date->modify('+1 days');
        }else{
            $date->modify('+'.$serial['day_nr'].' days');
        }
    }
}

function setWeeklyEvent($serial, $start_date, $end_date, $collection_id){
    $date = new DateTime($start_date->format('Y-m-d'));
    while ($date <= $end_date) {
        foreach ($GLOBALS['weekday_en'] as $weekday_key => $weekday_value) {
            if($serial[$weekday_value] != 0){
                $real_date = new DateTime(date("d.m.Y", strtotime($weekday_value, $date->getTimestamp())));
                buildArray($collection_id, $real_date);
            }
        }
        $date->modify('+'.$serial['week_nr'].' weeks');
    }
}

function setMonthlyEvent($serial, $start_date, $end_date, $collection_id){
    switch ($serial['repeating_radio']) {
        case '1':
            $date = new DateTime($start_date->format('Y-m-').$serial['day_nr']);
            while ($date <= $end_date) {
                buildArray($collection_id, $date);
                $date->modify('+'.$serial['month_nr'].' months');
            }
            break;
        case '2':
            $date = new DateTime($start_date->format('Y-m-').'1');
            while ($date <= $end_date) {
                $real_date = new DateTime(date("d.m.Y", strtotime($serial['day_nr'] . $GLOBALS['weekday_en'][$serial['week_nr']-1], $date->getTimestamp())));
                buildArray($collection_id, $real_date);
                $date->modify('+'.$serial['month_nr'].' months');
            }   
            break;
        default:
            break;
    }
}

function setYearlyEvent($serial, $start_date, $end_date, $collection_id){
    switch ($serial['repeating_radio']) {
        case '1':
            $date = new DateTime($start_date->format('Y-').$serial['month_nr'].'-'.$serial['day_nr']);
            while ($date <= $end_date) {
                buildArray($collection_id, $date);
                $date->modify('+'.$serial['year_nr'].' years');
            }
            break;
        case '2':
            $date = new DateTime($start_date->format('Y-m-').'1');
            while ($date <= $end_date) {
                $real_date = new DateTime(date("d.m.Y", strtotime($serial['day_nr'] . $GLOBALS['weekday_en'][$serial['week_nr']-1] . $GLOBALS['month_en'][$serial['month_nr']-1], $date->getTimestamp())));
                buildArray($collection_id, $real_date);
                $date->modify('+'.$serial['year_nr'].' years');
            }   
            break;
        default:
            break;
    }
}

function buildArray($collection_id, $date){
    $select_collection = $GLOBALS['pdo_conn']->prepare("SELECT * FROM main_collection WHERE id = :id LIMIT 1");
    $select_collection->execute(array(':id' => $collection_id));
    $res_collection = $select_collection->fetch(PDO::FETCH_ASSOC);

    $title = selectCollectionData($collection_id, 199);
    $description = selectCollectionData($collection_id, 199);

    $fullviewLinkEvent = get_link_to_navigation($GLOBALS["navigation"]['id']) . get_collection_rewrite($res_collection['description'], $res_collection['id']);
    $linkTitle = 'Mehr erfahren'; 

    $GLOBALS['array'][] = [
        'id'    => "event-".$collection_id,
        'name'    => $title,
        'description' => $description,
        'link' =>  $fullviewLinkEvent,
        'link_title' => $linkTitle,
        'date' =>  $date->format('Y.m.d'),
        'type' => "event",
        'color' => "gray",
        'everyYear' => false
    ];
}

function selectCalendarSerial($collection_id){
    $select_collection = $GLOBALS['pdo_conn']->prepare("SELECT * FROM calendar_serial WHERE main_collection_id = :main_collection_id");
    $select_collection->execute(array(':main_collection_id' => $collection_id));
    $res_collection = $select_collection->fetch(PDO::FETCH_ASSOC);
    return $res_collection;
}

function selectCollectionData($collection_id, $main_collection_setup_content_id){
    $select_collection = $GLOBALS['pdo_conn']->prepare("SELECT * FROM main_collection_link WHERE main_collection_id = :main_collection_id AND main_collection_setup_content_id = :main_collection_setup_content_id");
    $select_collection->execute(array(':main_collection_id' => $collection_id, ':main_collection_setup_content_id' => $main_collection_setup_content_id));
    $res_collection = $select_collection->fetch(PDO::FETCH_ASSOC);
    return $res_collection['data'];
}
?>

<div class='calendar'>
    <div id="calendar"></div>
</div>
<link rel="stylesheet" type="text/css" href="/plugins/evo-calendar/css/evo-calendar.min.css">
<script type="text/javascript" src="/plugins/evo-calendar/js/evo-calendar.min.js?time=<?= filemtime($_SERVER['DOCUMENT_ROOT'] . '/plugins/evo-calendar/js/evo-calendar.js')?>"></script>  
<script>
    var evoCalendar = [];
     $('#calendar').evoCalendar({
         todayHighlight: true,
         sidebarDisplayDefault: false,
         eventDisplayDefault: false,
         firstDayOfWeek: 1,
         'eventHeaderFormat': 'dd. MM yyyy',
         language: 'de'
     });
</script>

<?php foreach($GLOBALS['array'] as $key => $val){?>
    <script>
        evoCalendar.push(<? echo json_encode($val); ?>);
        </script> 
<?php } ?>
<script>
    // console.log(evoCalendar);
    $("#calendar").evoCalendar('addCalendarEvent', evoCalendar);
</script> 