<?php

$path = '../../../';
require $path.'core/includes/header.inc.php';

$page_meta['title'] = 'Manage SEO Redirects';
$action = "Add";

$errors = array();
$form = array(
    'old_url' => '',
    'new_url' => '',
    'code' => ''
);

if ($_REQUEST['delete']) {
    $redirect = SeoRedirect::find($_REQUEST['delete'])
                ->delete();

    header('Location: manage.seo.redirects.php?message=success');
    exit();
}

if ($_REQUEST['edit']) {
    $redirect = SeoRedirect::find($_REQUEST['edit']);
    $action = "Edit";

    $form['old_url'] = $redirect->old_url;
    $form['new_url'] = $redirect->new_url;
    $form['code'] = $redirect->code;
}

if ($_REQUEST['action'] == 'save') {
    $form['old_url'] =  $_REQUEST['old_url'];
    $form['new_url'] =  $_REQUEST['new_url'];
    $form['code']    =  $_REQUEST['code'];

    //check if new rule will cause redirect loop
    $redirect_loop = SeoRedirect::where('old_url', '=', $form['new_url'])
                            ->where('new_url', '=', $form['old_url'])
                            ->count();

    if ($redirect_loop > 0 || ($form['old_url'] == $form['new_url'])) {
         $errors[] = 'This rule will cause redirect loop!';
    }

    if (!preg_match('#^/#', $form['old_url'])) {
        $errors[] = 'Old URL path has to start with a forward slash: /';
    }

    if (!preg_match('#^/#', $form['new_url'])) {
        $errors[] = 'New URL path has to start with a forward slash: /';
    }

    if ($form['old_url'] == '/' || $form['new_url'] == '/') {
        $errors[] = 'Use /index.php for home';
    }

    if (count($errors) === 0) {
        if (empty($_REQUEST['edit'])) {
            $redirect = new SeoRedirect();
        }

        $redirect->fill($form);
        $redirect->save();

        header('Location: manage.seo.redirects.php?message=success');
        exit;
    }
}

if ($_REQUEST['action'] == 'csv') {
    if (!empty($_REQUEST['export'])) {
        header('Location: csv.get.php?type=redirects');
        exit;
    } elseif (!empty($_REQUEST['import'])) {
        SeoCsv::importCsv('redirects');
        header('Location: manage.seo.redirects.php?message=success');
        exit;
    }
}

// pagination
$totalnumrows = SeoRedirect::count();
$rowsPerPage = 25;

if (empty($_GET['page'])) {
    $_GET['page'] = 1;
}


$pageNum = $_GET['page'];
$offset = ($pageNum - 1) * $rowsPerPage;
$redirects_list = SeoRedirect::offset($offset)
                ->take($rowsPerPage)
                ->get();

//list with redirect codes
$redirect_codes = SeoRedirect::$redirect_codes;

/* * ***********************************************************************************************************************************
 * 														OUTPUT
 * *********************************************************************************************************************************** */

include $path.'core/admin/templates/adminheader.html.php';
?>
<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <li><a href="/admin/seoadmin">Manage SEO</a> /</li>
    <li class="end"><?= clean_page($page_meta['title']) ?></li>
</ul>

<h1>Redirects</h1>
<?php
include 'tabnav.php';

if (count($errors) > 0) {
    showerrors($errors);
}

if (count($errors) == 0 && !empty($_REQUEST['message']) && $_REQUEST['message'] == 'success') {
    echo showmsg("Operation carried out successfully", "success", $path);
}
echo showmsg("Previous redirects are removed during upload. ", "warning", $path);

?>

<form action="" method="post" class="style">
    <fieldset <?=(isset($_REQUEST['edit']) ? 'class="show"' : '')?>>
        <h1><a class="show el"><?=clean_page($action);?> Redirect<i class="fa fa-caret-right"></i></a></h1>

        <div class="row">
            <label for="path">Old URL</label>
            <input type="text" name="old_url" value="<?= clean_page($form['old_url']) ?>" />
        </div>
        <div class="row">
            <label for="title">New URL</label>
            <input type="text" name="new_url" id="title" value="<?= clean_page($form['new_url']); ?>">
        </div>
        <div class="row">
            <label for="code">Code</label>
            <select name="code" id="code">
                <?php
                    foreach ($redirect_codes as $code => $name) {
                        if ($code == $form['code']) {
                            $selected = 'selected';
                        } else {
                            $selected = '';
                        }
                ?>
                <option value="<?=clean_page($code);?>" <?=clean_page($selected);?>>
                    <?=clean_page($name);?> (<?=clean_page($code);?>)
                </option>
                <?php
                    }
                ?>
            </select>
        </div>
        <div class="row">
            <button type="submit" class="btn" name="action" value="save"><?=$action;?></button>
        </div>
    </fieldset>
</form>

<?php

include __DIR__.'/templates/csvform.html.php';

if ($totalnumrows > 0 && !isset($_REQUEST['edit'])) {
    include($path . 'core/admin/templates/pagination.php');
    ?>

    <table class="">
        <tr>
            <th class="center"></th>
            <th>Old URL</th>
            <th>New URL</th>
            <th>Code</th>
            <th>Hits</th>
            <th class="center">Edit</th>
            <th class="center">Delete</th>
        </tr>
        <tbody class="tabular">
            <?php
            foreach ($redirects_list as $redirect) {
                ?>
                <tr>
                    <td>
                        <a href="<?= clean_page($redirect['old_url']); ?>" target="_blank"><i class="fa fa-eye"></i></a>
                    </td>
                    <td><?= clean_page($redirect->old_url); ?></td>
                    <td><?= clean_page($redirect->new_url); ?></td>
                    <td><?= clean_page($redirect->code); ?></td>
                    <td><?= clean_page($redirect->hits); ?></td>
                    <td class="center">
                        <a href="?edit=<?= $redirect['id'] ?>"><i class="fa fa-pencil"></i></a>
                    </td>
                    <td class="center">
                        <a href="?delete=<?= $redirect['id'] ?>" class="alert error" title="Are you sure you want to delete this entry?"><i class="fa fa-times-circle"></i></a>
                    </td>
                </tr>
                <?php

            }
    ?>
        </tbody>
    </table>

    <?php

    include($path . 'core/admin/templates/pagination.php');
}
require_once $path.'core/admin/templates/adminfooter.html.php';
