<?php
$optres['js'][] = $path . 'amodules/events_ext/js/infinite_past.js';
$is_json = (isset($_GET['type']) && $_GET['type'] == "json") ? true : false;
if($is_json) {
    ob_end_clean();
    ob_start();
}
require_once(dirname(__FILE__) . "/../classes/Paginator.php");

$webpage_title_en = "Past Cyprus Events";
$meta['description'] = "Check out previous Cyprus events. See what was happening in Cyprus before.";
$meta['keywords'] = "Cyprus past events, Limassol past events, Nicosia past events, Larnaca past events, Paphos past events, Famagusta past events";

// Set breadcrumbs
$breadcrumbs [] = array(
    'link' => '',
    'title' => "Find Cyprus Past Events"
);

$optres['css'][] = $module_css_path . "amodules/events_ext/css/paginator.css";
$optres['css'][] = $module_css_path . "amodules/events_ext/css/events.css";
$optres['js'][] = $path . "amodules/events_ext/js/events_main.js";
function namesToCapital($str) {
    $ret = array();
    $str = explode(" ", $str);
    if(is_array($str) && count($str)>0) {
        foreach ($str as $i=>$s) {
            if(trim($s) != "") {
                $ret [] = ucfirst(trim(strtolower($s)));
            }
        }
    }

    if(count($ret) > 0) return implode(" ", $ret);
    return $str;
}

$have_filters = true;
$total_records = 0;

//echo '<pre>$_POST = ', var_export($_POST, true), '</pre>';
$search = array(
    'event_category' => "",
    'event_location' => "",
    'event_period' => "",
    'event_keyword' => "",
    'display' => "yes",
    'i_from' => 0,
    'i_limit' => 20
);

if(isset($_POST['event_srch']) && isset($_POST['event_srch']['display']) && $_POST['event_srch']['display'] == "yes") {
    $have_filters = true;
    $event_srch = $_POST['event_srch'];
    $search = array_merge($search, $event_srch);
    //echo '<pre>$search = ', var_export($search, true), '</pre>';
}

if(isset($_REQUEST['filter'])) {
    $filter = (trim($_REQUEST['filter']) != "") ? base64_decode($_REQUEST['filter']) : "";
    //var_dump($filter);
    if($filter != "") {
        $qs = array();
        parse_str($filter, $qs);
        //var_dump($qs);
        $search = array_merge($search, $qs);
        $event_srch = $search;
    }
}

ob_start();
$past_events = true;
require(dirname(__FILE__) . "/events_search_form.php");
$events_search_form_html = ob_get_contents();
$past_events = false;
unset($past_events);
ob_end_clean();

$m_category = 'Events';
$m_location = 'Cyprus';
$m_title = "<location> Past Events";
$m_description = 'Check out past <category> in <location>. ';

if($m_category != "Events") {
    $m_title = "<location> Past Events | <category>";
    $m_description = 'Check out past <location> <category>. ';
}

$m_keywords = array();

// Get Meta Category
$all_event_categs = $events_config['categories'];
foreach ($all_event_categs as $gr_id => $gr_data){
    $found = false;
    $categ_code = $gr_id;
    if(intval($event_srch['event_category']) == intval($categ_code)) {
        if(stripos($gr_data['title'], 'festivals') === false) {
            $m_category = $gr_data['title'];
            $m_title = "<location> Past Events | <category>";
            $m_description = 'Check out past <location> <category> events. ';
        }
        else {
            $m_category = $gr_data['title'];
            $m_title = "Past <location> <category>";
            $m_description = 'Check out past <location> <category>. ';
        }
    };
    if(count($gr_data['subs']) > 0) {
        foreach($gr_data['subs'] as $cat_id=>$cat_title) {
            $categ_code = $gr_id . '-' . $cat_id;
            if($event_srch['event_category'] == $categ_code) {
                if(stripos($gr_data['title'], 'festivals') === false) {
                    $m_category = $cat_title;
                    $m_title = "<location> Past Events | <category>";
                    $m_description = 'Check out past <location> <category> events. ';
                }
                else {
                    $m_category = $cat_title;
                    $m_title = "Past <location> <category>";
                    $m_description = 'Check out past <location> <category>. ';
                }
            };
        }
    }


}

// Get Meta Location
$locations = $events_config['locations'];
foreach ($locations as $dcode=>$loc) {
    if($event_srch['event_location'] == $dcode) {
        $m_location = $loc['title'];
    };
}

if($m_location == 'All Cyprus') $m_location = 'Cyprus';

if($m_location == "Cyprus") {
    $m_description .= 'Filter through Limassol past events, Nicosia past events, Larnaca past events, Paphos past events or Famagusta past events. ';
}
elseif($m_category == "Events") {
    $m_description .= 'Be informed about cultural, social, sport and musical past events. ';
}
else {
    if(stripos($m_category, 'festivals') === false) {
        $m_description .= 'Be informed about the past <category> events. See what was happening in <location>.';
    }
    else {
        $m_description .= 'Be informed about the past <category> in <location>. See what was happening in <location>.';
    }
}

//echo '<pre>', var_export($all_event_categs, true), '</pre>';
//echo '$m_category = ' . $m_category;
//echo '<br>$m_title = ' . htmlentities($m_title) . '<br>';

$m_title = str_replace('<category>', $m_category, $m_title);
$m_title = str_replace('<location>', $m_location, $m_title);

if(stripos($m_title, 'festivals') === false) {

    if($m_category != "Events") {
        $m_description = str_replace('<category>', $m_category . ' Events', $m_description);
        $m_description = str_replace('<location>', $m_location, $m_description);

        $m_keywords [] = $m_category . ' past events in ' . $m_location;
        $m_keywords [] = $m_location . ' ' . $m_category . ' past events';
    }
    else {

        $m_description = str_replace('<category>', $m_category . '', $m_description);
        $m_description = str_replace('<location>', $m_location, $m_description);

        $m_keywords [] = 'Past ' . $m_category . ' in ' . $m_location;
        $m_keywords [] = $m_location . ' Past ' . $m_category;
    }
}
else {
    $m_description = str_replace('<category>', $m_category . '', $m_description);
    $m_description = str_replace('<location>', $m_location, $m_description);


    $m_keywords [] = $m_category . ' in ' . $m_location;
    $m_keywords [] = $m_location . ' ' . $m_category . '';
}

$meta['title'] = $m_title;
$meta['description'] = $m_description;
$meta['keywords'] = implode(", ", $m_keywords);

$webpage_title_en = $m_title;
$m_title = str_replace(' |', ':', $m_title);
$m_title = str_replace('|', ':', $m_title);


if($have_filters) {

    $past = array();

    $today_date = date("Y-m-d", time());
    $today_value = date("d/m/Y", time());
    $today_text = 'Today';
    $today_date_str = ' (' . date("F jS, Y", time()) . ')';

    foreach($search as $k=>$v) {
        ${$k} = mysql_real_escape_string($v);
    }


    $q = "SELECT * FROM events WHERE active='1' AND crawled='1'";

    if($event_srch['event_category'] != '') {
        $ev_cats = explode("-", $event_srch['event_category']);
        if(count($ev_cats) == 2 && intval($ev_cats['1']) > 0 ) {
            $q .= " AND category_group_id='{$ev_cats['0']}' AND category_id='{$ev_cats['1']}' ";
        }
        else {
            $q .= " AND category_group_id='{$ev_cats['0']}' ";
        }
    }

    // Location
    if($event_srch['event_location'] != "") {
        $q .= " AND dcode = '{$event_srch['event_location']}'";
    }

    // Keyword
    if($event_srch['event_keyword'] != "") {
        $keyword = mysql_real_escape_string(trim(stripslashes($event_srch['event_keyword'])));
        $q .= " AND (title like '%$keyword%' OR description like '%$keyword%') ";
    }

    // Period
    $event_period = '';
    $_date = new DateTime(date('Y-m-d'));
    if($event_srch['event_period'] != "") {
        $event_period = $event_srch['event_period'];
        switch (strval($event_period)) {
            case "past":
                $today = $_date->format('Y-m-d');
                $q .= " AND date_to <'$today'";
                break;
            case "today":
                $today = $_date->format('Y-m-d');
                $q .= " AND date_from <='$today' AND date_to >='$today'";
                break;
            case "tomorrow":
                $tomorrow = $_date->add(new DateInterval('P1D'))->format('Y-m-d');

                $today_date = date("Y-m-d", strtotime($tomorrow));
                $today_value = date("d/m/Y", strtotime($tomorrow));
                $today_text = 'Tomorrow';
                $today_date_str = ' (' . date("F jS, Y", strtotime($tomorrow)) . ')';

                $q .= " AND date_from <='$tomorrow' AND date_to >='$tomorrow'";
                break;
            case "next7days":
                $interval_start = $_date->add(new DateInterval('P1D'))->format('Y-m-d');
                $interval_end = $_date->add(new DateInterval('P6D'))->format('Y-m-d');

                $q .= " AND (";
                $q .= " '$interval_start' <= date_to AND '$interval_end' >= date_from ";
                $q .= ") ";

                break;
            case "next30days":
                $interval_start = $_date->add(new DateInterval('P1D'))->format('Y-m-d');
                $interval_end = $_date->add(new DateInterval('P30D'))->format('Y-m-d');

                $q .= " AND (";
                $q .= " '$interval_start' <= date_to AND '$interval_end' >= date_from ";
                $q .= ") ";
                break;
            case "next60days":
                $interval_start = $_date->add(new DateInterval('P1D'))->format('Y-m-d');
                $interval_end = $_date->add(new DateInterval('P60D'))->format('Y-m-d');

                $q .= " AND (";
                $q .= " '$interval_start' <= date_to AND '$interval_end' >= date_from ";
                $q .= ") ";
                break;
        }
    }
    else {
        $today = $_date->format('Y-m-d');
        $q .= " AND date_to <'$today'";
    }

    if($event_srch['event_period'] != "") {
        if($event_srch['event_period'] == "past") {
            $q .= " ORDER BY date_to DESC, date_from DESC";
        }
    }
    else {
        $q .= " ORDER BY date_from ASC, date_to ASC ";
    }

    $r_total = @mysql_query($q);
    if($r_total) {
        $total_records = mysql_num_rows($r_total);
    }

    //echo $q;

    //print_r($event_srch);


    if($total_records > 0) {
        $i_from = intval($event_srch['i_from']);
        $i_limit = intval($event_srch['i_limit']);

        $paginator = new Paginator(array(
            "base_url"  => "past-events/",
            "request_parameter_name" => "filter",
            "records_per_page" => $event_srch['i_limit'],
            "show_all" => 0
        ));
        $search = array_map('stripslashes', $search);

        //echo '<pre>$search = ', var_export($search, true), '</pre>';
        $json = $paginator->get_json($total_records, $search);
        $json['content'] = array();

       // echo '<pre>$json = ', var_export($json, true), '</pre>';

        $q .= "	LIMIT $i_from, $i_limit;";

        //echo $q;

        $r = @mysql_query($q);
        if($r) {
            $today = date("d/m/Y", time());
            while($row = mysql_fetch_assoc($r)) {
                $date_from_timestamp = strtotime($row['date_from']);
                $date_to_timestamp = strtotime($row['date_to']);
                $date_from = date("d/m/Y", $date_from_timestamp);
                $date_to = date("d/m/Y", $date_to_timestamp);

                //echo '<br>$today_date = ' . $today_date . ' | ' . strtotime($today_date);


                $past [$row['id']] = array_map('stripslashes', $row);

            }
        }
    }

}

//echo '<pre>$event_srch = ', var_export($event_srch, true), '</pre>';

?>
    <section class="article cyprus">
        <header>
            <h1><?=$m_title;?></h1>
            <!--[/SocialShareButtons/]-->
        </header>
        <div class="article-body cyprus">
            <?php

            if($gads_show && $def_ads == "yes" && $def_ad_id != "") {
                $adsense_container_class = "no-margin";
                echo '<div style="margin-bottom: 6px;">';
                include(dirname(__FILE__) . "/../gads_content/gads_content_default.php");
                echo '</div>';
                unset($adsense_container_class);
            }

            echo $events_search_form_html;

            if($total_records > 0) {
                ?>
                <div class="container-fluid no-padding" id="scrollingcontent">
                    <?php
                    if(count($past) > 0) {
                        ?>
                        <h2 class="events-subtitle ongoing"><?php echo 'Past Events (' . $total_records . ')';?></h2>

                        <div class="listitems" id="infinite-content">
                            <?php
                            if($is_json) {
                                ob_start();
                            }
                            ?>
                            <div class='listitempage' data-url="<?=$json['current_url'];?>">
                                <div class="listpagination">Page <?=$json['current_page'];?></div>

                                    <?php
                                    $cnt = 1;
                                    foreach ($past as $event_id => $row) {
                                        $row = array_map('stripslashes', $row);
                                        //$name = (($row['Genre'] == "m") ? "Mr." : "Ms.") . " " . stripslashes(trim($row['FirstName'])) . " " . stripslashes(trim($row['LastName']));
                                        $event_title = trim(stripslashes($row['title']));
                                        $friendly_url = $row['friendly_url'];


                                        $location = trim($row['region']);
                                        if (trim($row['city']) != '') $location .= ' / ' . trim($row['city']);
                                        if ($location == '') $location = "Cyprus";

                                        $id = intval($row['id']);
                                        $category_group_id = intval($row['category_group_id']);
                                        $category_id = intval($row['category_id']);
                                        $categ_code = $category_group_id . '-' . $category_id;
                                        if($category_id == 0) {
                                            $categ_code = $category_group_id;
                                        }

                                        $category_group_title = trim($row['category_group_title']);
                                        $category_title = trim($row['category_title']);
                                        $date_from = date("d/m/Y", strtotime($row['date_from']));
                                        $date_to = date("d/m/Y", strtotime($row['date_to']));

                                        $event_link = 'event/' . $friendly_url;

                                        $description = tokenTruncate(strip_tags($row['description']), 250) . '...';
                                        $description .= '<a href="' . $event_link . '" class="event-readmore">[Read more]</a>';

                                        // Category
                                        $category_group_link = '';
                                        $category_link = '';
                                        $category_group_link_title = '';
                                        $category_link_title = '';
                                        if ($category_group_title != '') {
                                            $category_group_link_title = $category_group_title;
                                        }
                                        if ($category_title != '') {
                                            $category_link_title = $category_title;
                                        }

                                        $category_group_link = "events/" . $events_config['cats_ids'][$category_group_id]['friendly_url'];
                                        if($category_id > 0) {
                                            $category_link = "events/" . $events_config['cats_ids'][$category_group_id]['friendly_url'] . '/' . $events_config['cats_ids'][$category_id]['friendly_url'];
                                        }
                                        if (isset($def_location) && $def_location != "") {
                                            $location_title = $events_config['locations'][$def_location]['title'];
                                            $category_group_link = "events/" . url_slug("$location_title") . "/" . $events_config['cats_ids'][$category_group_id]['friendly_url'];
                                            if($category_id > 0) {
                                                $category_link = "events/" . url_slug("$location_title") . "/" . $events_config['cats_ids'][$category_group_id]['friendly_url'] . '/' . $events_config['cats_ids'][$category_id]['friendly_url'];
                                            }
                                        }


                                        $image = '';
                                        if ($row['image'] != "") {
                                            $image = $path . 'images/events/' . $id . '/' . $row['image'];
                                        }

                                        /*if($is_json) {
                                            ob_start();
                                        }*/
                                        ?>
                                        <div class="box event-box ongoing listitem" data-page-url="<?=$json['current_url'];?>">
                                            <div class="box-header with-border">
                                                <a href="<?= $event_link; ?>" class="event-title"><?= $event_title; ?></a>
                                                <?php
                                                if(isset($_SESSION['user_id']) && intval($_SESSION['user_id']) > 0) {
                                                    echo '<div class="user-action-container event-action"><a class="user-action-inline" href="/admin/index.php?plugin=events&amp;action=events_item&amp;id=' . $id . '" target="_blank">e</a></div>';
                                                }
                                                ?>
                                            </div>
                                            <div class="box-body">
                                                <div class="row">
                                                    <div class="col-sm-3">
                                                        <div class="image-holder">
                                                            <a href="<?= $event_link; ?>" class="image-container">
                                                                <img src="<?= $image ?>" alt="<?php echo htmlspecialchars('Cyprus Event: ' . $event_title, ENT_QUOTES);?>" class="event-image">
                                                            </a>
                                                        </div>
                                                    </div>
                                                    <div class="col-sm-7 no-padding">
                                                        <p class="event-description"><?= $description; ?></p>

                                                        <div class="event-details">
                                                            <div class="row">
                                                                <div class="col col-sm-3 col-xs-3"><span class="event-d"><i
                                                                            class="fa fa-map-marker fa-fw"></i> Location:</span>
                                                                </div>
                                                                <div class="col col-sm-7 col-xs-7">
                                                                    <strong><?= $location; ?></strong></div>
                                                            </div>
                                                            <div class="row">
                                                                <div class="col col-sm-3 col-xs-3"><span class="event-d"><i
                                                                            class="fa fa-calendar fa-fw"></i> Date(s):</span></div>
                                                                <div class="col col-sm-7 col-xs-7">
                                                                    <b><?= $date_from . (strcmp($date_to, $date_from) != 0 ? ' - ' . $date_to : ''); ?></b>
                                                                </div>
                                                            </div>
                                                            <div class="row">
                                                                <div class="col col-sm-3 col-xs-3"><span class="event-d"><i
                                                                            class="fa fa-tag fa-fw"></i>Category:</span></div>
                                                                <div class="col col-sm-7 col-xs-7">
                                                                    <?php
                                                                    if($category_group_id > 0) {
                                                                        ?>
                                                                        <a href="<?= $category_group_link; ?>"><?= $category_group_link_title; ?></a>
                                                                        <?php
                                                                        if($category_id > 0) {
                                                                            ?>
                                                                            / <a href="<?= $category_link; ?>"><?= $category_link_title; ?></a>
                                                                            <?php
                                                                        }
                                                                    }
                                                                    else {
                                                                        echo 'N/A';
                                                                    }
                                                                    ?>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <?php
                                        /*if($is_json) {
                                            $json['content'][] = ob_get_contents();
                                            ob_end_clean();
                                        }*/

                                        if ($cnt - $i_from == 1) {
                                            // Show Adsense
                                            if ($gads_show && $def_ads == "yes" && $def_ad_id != "") {
                                                $adsense_container_class = "no-margin";
                                                echo '<div style="margin-top: 9px;margin-bottom: 6px; margin-left: -15px!important;margin-right: -15px!important;">';
                                                include(dirname(__FILE__) . "/../gads_content/gads_content_default.php");
                                                echo '</div>';
                                                unset($adsense_container_class);
                                            }
                                        }

                                        $cnt++;
                                    }
                                    ?>
                                </div>
                            </div>
                        <?php
                        if($is_json) {
                            $json['response'] = ob_get_contents();
                            ob_end_clean();
                        }
                    }



                    ?>
                </div>
                <?php
            }
            else {
                echo '<br><div class="alert alert-danger"><p class="text-white"><b><i class="fa fa-warning"></i> Sorry!</b></span><br/>There are no events matching your criteria.</p></div>';
            }
            ?>


        </div>

    </section>
<script>
    next_data_url = '<?=$json['next_data_url']?>';
    prev_data_url = '<?=$json['prev_data_url']?>';
</script>
<?php
if($is_json) {
    ob_end_clean();
    //echo '<pre>', var_export($json, true), '</pre>';
    echo json_encode($json);
    die();
}
?>


