<?php

//Include the common file
require '../common.php';

//Check if the user is logged in
if (!$authentication->loggedIn() || !$authentication->isAdmin()) header("Location: login.php");

//Returns the number of rows
$rowCount = $db->rowCount("SELECT event_id FROM " . cfg('base', 'table_events'). "");

//Pagination
if (isset($_GET['page']))
    $current_page = trim($_GET['page']);
else
    $current_page = 1;

$start = ($current_page -1 ) * cfg('base', 'per_page_admin');

$sql = "SELECT * FROM " . cfg('base', 'table_events') . " e, " . cfg('base', 'table_event_translations') . " t WHERE e.event_id = t.event_id AND t.language_code = '" . cfg('language', 'site_language') . "'";

$implode = array();

if (isset($_POST['search']) && !empty($_POST['filter_event_title']))
    $implode[] = " LCASE(t.event_title) LIKE '%" . strtolower($_POST['filter_event_title']) . "%'";

if ($implode)
    $sql .= " AND " . implode(" AND ", $implode);

$sql .= " ORDER BY e.event_id DESC LIMIT " . $start . ", " . cfg('base', 'per_page_admin') . "";

$pages = ceil($db->rowCount("SELECT event_id FROM " . cfg('base', 'table_events') . "") / cfg('base', 'per_page_admin'));

//events
$events = array();

foreach ($db->query($sql) as $row) {

    $events[] = array(
        'event_id'               => $row['event_id'],
        'event_title'            => $row['event_title'],
        'event_poster'           => $row['event_poster'],
        'event_date'             => $row['event_date'],
        'event_location'         => $row['event_location'],
        'event_status'           => $row['event_status']
    );

}

//Check if the form has been submitted
if (isset($_POST['cb_event'])) {

    foreach ($_POST['cb_event'] as $value) {

        $result = $db->fetchRowAssoc("SELECT event_poster FROM " . cfg('base', 'table_events') . " WHERE event_id = '" . $value . "'");

        if ($result['event_poster']) {

            @unlink(cfg('upload', 'upload_path') . 'images/' . $result['event_poster']);

        }

        $where = array(
            'event_id' => $value
        );

        $db->where($where);
        $db->delete(cfg('base', 'table_events'));

    }

    header("Location: events.php");

}

//Navigation class
$current_events = 'class="active"';

//Template values
$tpl->set('current_events', $current_events);
$tpl->set('rowCount', $rowCount);
$tpl->set('current_page', $current_page);
$tpl->set('pages', $pages);
$tpl->set('events', $events);

//Display the template
$tpl->display('admin/events');
