<?php

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

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

$content_ad = $db->fetchRowAssoc("SELECT * FROM " . cfg('base', 'table_ads') . " WHERE ad_id = 1");
$sidebar_ad = $db->fetchRowAssoc("SELECT * FROM " . cfg('base', 'table_ads') . " WHERE ad_id = 2");

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

    if (!$error->hasErrors()) {

    $content_rowCount = $db->rowCount("SELECT ad_id FROM " . cfg('base', 'table_ads') . " WHERE ad_id = '" . $_POST['content_ad_id'] . "'");

        if ($content_rowCount <= 0) {
            $values = array(
                'ad_id'              => $_POST['content_rowCount'],
                'ad_content'      => $_POST['content_ad']
            );
            $db->insert(cfg('base', 'table_ads'), $values);
        } else {
            $values = array(
                'ad_content'      => $_POST['content_ad']
            );

            $where = array(
                'ad_id'           => $_POST['content_ad_id']
            );

            $db->where($where);
            $db->update(cfg('base', 'table_ads'), $values);
        }

    $sidebar_rowCount = $db->rowCount("SELECT ad_id FROM " . cfg('base', 'table_ads') . " WHERE ad_id = '" . $_POST['sidebar_ad_id'] . "'");

        if ($sidebar_rowCount <= 0) {
            $values = array(
                'ad_id'              => $_POST['sidebar_ad_id'],
                'ad_content'      => $_POST['sidebar_ad']
            );
            $db->insert(cfg('base', 'table_ads'), $values);
        } else {
            $values = array(
                'ad_content'      => $_POST['sidebar_ad']
            );

            $where = array(
                'ad_id'           => $_POST['sidebar_ad_id']
            );

            $db->where($where);
            $db->update(cfg('base', 'table_ads'), $values);
        }

    $session->set('success', true);

    header('Location: ads.php');

    }
}

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

//Template values
$tpl->set('current_ads', $current_ads);
$tpl->set('content_ad', $content_ad['ad_content']);
$tpl->set('sidebar_ad', $sidebar_ad['ad_content']);

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