<?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 mix_id FROM " . cfg('base', 'table_mixes'). "");

//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_mixes') . " s, " . cfg('base', 'table_mix_translations') . " t WHERE s.mix_id = t.mix_id AND t.language_code = '" . cfg('language', 'site_language') . "'";

$implode = array();

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

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

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

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

//mix
$mixes = array();

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

    $mixes[] = array(
        'mix_id'               => $row['mix_id'],
        'mix_title'               => $row['mix_title'],
        'cover'                   => $row['cover'],
        'author'               => $row['author'],
        'date_added'           => $row['date_added'],
        'mix_status'           => $row['mix_status']
    );

}

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

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

        $result = $db->fetchRowAssoc("SELECT cover FROM " . cfg('base', 'table_mixes') . " WHERE mix_id = '" . $value . "'");

        if ($result['cover']) {

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

        }

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

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

    }

    header("Location: mixes.php");

}

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

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

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