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

//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_partners') . "";

$implode = array();

if (isset($_POST['search']) && !empty($_POST['filter_partner_name']))
    $implode[] = " LCASE(partner_name) LIKE '%" . strtolower($_POST['filter_partner_name']) . "%'";
if ($implode)
    $sql .= " WHERE " . implode(" AND ", $implode);

$sql .= " LIMIT " . $start . ", " . cfg('base', 'per_page_admin') . "";

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

//partners
$partners = array();

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

    $partners[] = array(
        'partner_id'               => $row['partner_id'],
        'partner_name'             => $row['partner_name'],
        'partner_image'            => $row['partner_image'],
        'partner_url'              => $row['partner_url'],
        'partner_status'           => $row['partner_status']
    );

}

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

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

        $result = $db->fetchRowAssoc("SELECT partner_image FROM " . cfg('base', 'table_partners') . " WHERE partner_id = '" . $value . "'");

        if ($result['partner_image']) {

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

        }

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

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

    }

    header("Location: partners.php");

}

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

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

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