<?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') . " WHERE partner_id = '" . $_GET['partner_id'] . "'");

$partner = $db->fetchRowAssoc("SELECT * FROM " . cfg('base', 'table_partners') . " WHERE partner_id = '" . $_GET['partner_id'] . "'");

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

    $validate->required($_POST['partner_name'], 'Enter partner name.');
    $validate->required($_POST['partner_url'], 'Enter partner url.');

    if (!empty($_FILES['image']['name'])) {

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

        if ($result['partner_image']) {

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

        }

        $image = $upload->uploadImage('image',url($_POST['partner_name']), 200, 200);

    }

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

        $values = array(
            'partner_name'            => $_POST['partner_name'],
            'partner_url'             => $_POST['partner_url'],
            'partner_status'          => $_POST['partner_status']
        );

        $where = array(
            'partner_id' => $_GET['partner_id']
        );

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

        if (isset($image)) {

            $values['partner_image'] = $image;

        }

        $where = array(
            'partner_id' => $_GET['partner_id']
        );

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

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

        header('Location: edit_partner.php?partner_id='.$_GET['partner_id'].'');

    }
}

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

//Template values
$tpl->set('current_partners', $current_partners);
$tpl->set('rowCount', $rowCount);
$tpl->set('partner', $partner);

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