<?php
/**
 * Pure Chemical Admin
 * redirects.php
 *
 * Existing table used:
 * redirects
 *
 * Columns:
 * id
 * old_url
 * new_url
 * redirect_type
 * status
 * created_at
 * updated_at
 */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';

if (file_exists(__DIR__ . '/includes/auth.php')) {
    require_once __DIR__ . '/includes/auth.php';
}

if (function_exists('requireAdmin')) {
    requireAdmin();
}

/* -----------------------------------------------------------
   Helpers
----------------------------------------------------------- */

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('csrf_token')) {
    function csrf_token()
    {
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }

        return $_SESSION['csrf_token'];
    }
}

if (!function_exists('csrf_field')) {
    function csrf_field()
    {
        return '<input type="hidden" name="csrf_token" value="' .
            e(csrf_token()) .
            '">';
    }
}

function verify_csrf_token()
{
    $token = isset($_POST['csrf_token'])
        ? (string)$_POST['csrf_token']
        : '';

    if (
        empty($_SESSION['csrf_token']) ||
        !$token ||
        !hash_equals($_SESSION['csrf_token'], $token)
    ) {
        return false;
    }

    return true;
}

function normalize_url_value($url)
{
    $url = trim((string)$url);

    if ($url === '') {
        return '';
    }

    /*
     * Allow internal relative URLs:
     * /old-page
     * /products/chemical
     *
     * Also allow:
     * https://example.com/page
     * http://example.com/page
     */
    if (strpos($url, '/') === 0) {
        return '/' . ltrim($url, '/');
    }

    return $url;
}

function is_valid_redirect_target($url)
{
    $url = trim((string)$url);

    if ($url === '') {
        return false;
    }

    /*
     * Relative URL
     */
    if (strpos($url, '/') === 0) {
        return true;
    }

    /*
     * Absolute URL
     */
    if (filter_var($url, FILTER_VALIDATE_URL)) {
        $scheme = strtolower((string)parse_url($url, PHP_URL_SCHEME));

        return in_array($scheme, ['http', 'https'], true);
    }

    return false;
}

function redirect_type_label($type)
{
    $types = [
        301 => '301 Permanent',
        302 => '302 Temporary',
        303 => '303 See Other',
        307 => '307 Temporary',
        308 => '308 Permanent',
    ];

    return isset($types[(int)$type])
        ? $types[(int)$type]
        : ((int)$type . ' Redirect');
}

function redirect_type_badge_class($type)
{
    switch ((int)$type) {
        case 301:
        case 308:
            return 'type-permanent';

        case 302:
        case 307:
            return 'type-temporary';

        case 303:
            return 'type-other';

        default:
            return 'type-other';
    }
}

function flash_message($type, $message)
{
    $_SESSION['redirects_flash'] = [
        'type' => $type,
        'message' => $message,
    ];
}

function get_flash_message()
{
    if (empty($_SESSION['redirects_flash'])) {
        return null;
    }

    $flash = $_SESSION['redirects_flash'];
    unset($_SESSION['redirects_flash']);

    return $flash;
}

/* -----------------------------------------------------------
   Allowed Redirect Types
----------------------------------------------------------- */

$allowedRedirectTypes = [
    301,
    302,
    303,
    307,
    308,
];

/* -----------------------------------------------------------
   POST Actions
----------------------------------------------------------- */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!verify_csrf_token()) {
        flash_message('error', 'Security token expired. Please try again.');
        header('Location: redirects.php');
        exit;
    }

    $action = isset($_POST['action'])
        ? trim((string)$_POST['action'])
        : '';

    try {

        /* ---------------------------------------------------
           SAVE REDIRECT
        --------------------------------------------------- */

        if ($action === 'save') {

            $id = isset($_POST['id'])
                ? (int)$_POST['id']
                : 0;

            $oldUrl = normalize_url_value(
                isset($_POST['old_url'])
                    ? $_POST['old_url']
                    : ''
            );

            $newUrl = normalize_url_value(
                isset($_POST['new_url'])
                    ? $_POST['new_url']
                    : ''
            );

            $redirectType = isset($_POST['redirect_type'])
                ? (int)$_POST['redirect_type']
                : 301;

            $status = isset($_POST['status'])
                ? (int)$_POST['status']
                : 1;

            if ($oldUrl === '') {
                throw new Exception('Old URL is required.');
            }

            if ($newUrl === '') {
                throw new Exception('New URL is required.');
            }

            if (!is_valid_redirect_target($oldUrl)) {
                throw new Exception(
                    'Old URL must be a valid relative URL or HTTP/HTTPS URL.'
                );
            }

            if (!is_valid_redirect_target($newUrl)) {
                throw new Exception(
                    'New URL must be a valid relative URL or HTTP/HTTPS URL.'
                );
            }

            if ($oldUrl === $newUrl) {
                throw new Exception(
                    'Old URL and New URL cannot be the same.'
                );
            }

            if (!in_array($redirectType, $allowedRedirectTypes, true)) {
                throw new Exception('Invalid redirect type selected.');
            }

            $status = $status === 1 ? 1 : 0;

            /*
             * Duplicate old_url protection
             */
            if ($id > 0) {

                $duplicateStmt = $pdo->prepare("
                    SELECT id
                    FROM redirects
                    WHERE old_url = :old_url
                      AND id != :id
                    LIMIT 1
                ");

                $duplicateStmt->execute([
                    ':old_url' => $oldUrl,
                    ':id'      => $id,
                ]);

            } else {

                $duplicateStmt = $pdo->prepare("
                    SELECT id
                    FROM redirects
                    WHERE old_url = :old_url
                    LIMIT 1
                ");

                $duplicateStmt->execute([
                    ':old_url' => $oldUrl,
                ]);
            }

            $duplicateId = $duplicateStmt->fetchColumn();

            if ($duplicateId) {
                throw new Exception(
                    'This Old URL already has a redirect.'
                );
            }

            /* UPDATE */

            if ($id > 0) {

                $checkStmt = $pdo->prepare("
                    SELECT id
                    FROM redirects
                    WHERE id = :id
                    LIMIT 1
                ");

                $checkStmt->execute([
                    ':id' => $id,
                ]);

                if (!$checkStmt->fetchColumn()) {
                    throw new Exception('Redirect record not found.');
                }

                $stmt = $pdo->prepare("
                    UPDATE redirects
                    SET
                        old_url = :old_url,
                        new_url = :new_url,
                        redirect_type = :redirect_type,
                        status = :status
                    WHERE id = :id
                    LIMIT 1
                ");

                $stmt->execute([
                    ':old_url'       => $oldUrl,
                    ':new_url'       => $newUrl,
                    ':redirect_type' => $redirectType,
                    ':status'        => $status,
                    ':id'            => $id,
                ]);

                flash_message(
                    'success',
                    'Redirect updated successfully.'
                );

            } else {

                $stmt = $pdo->prepare("
                    INSERT INTO redirects
                    (
                        old_url,
                        new_url,
                        redirect_type,
                        status
                    )
                    VALUES
                    (
                        :old_url,
                        :new_url,
                        :redirect_type,
                        :status
                    )
                ");

                $stmt->execute([
                    ':old_url'       => $oldUrl,
                    ':new_url'       => $newUrl,
                    ':redirect_type' => $redirectType,
                    ':status'        => $status,
                ]);

                flash_message(
                    'success',
                    'Redirect created successfully.'
                );
            }

            header('Location: redirects.php');
            exit;
        }

        /* ---------------------------------------------------
           DELETE
        --------------------------------------------------- */

        if ($action === 'delete') {

            $id = isset($_POST['id'])
                ? (int)$_POST['id']
                : 0;

            if ($id <= 0) {
                throw new Exception('Invalid redirect ID.');
            }

            $stmt = $pdo->prepare("
                DELETE FROM redirects
                WHERE id = :id
                LIMIT 1
            ");

            $stmt->execute([
                ':id' => $id,
            ]);

            if ($stmt->rowCount() > 0) {
                flash_message(
                    'success',
                    'Redirect deleted successfully.'
                );
            } else {
                flash_message(
                    'error',
                    'Redirect record not found.'
                );
            }

            header('Location: redirects.php');
            exit;
        }

        /* ---------------------------------------------------
           TOGGLE STATUS
        --------------------------------------------------- */

        if ($action === 'toggle_status') {

            $id = isset($_POST['id'])
                ? (int)$_POST['id']
                : 0;

            if ($id <= 0) {
                throw new Exception('Invalid redirect ID.');
            }

            $stmt = $pdo->prepare("
                SELECT status
                FROM redirects
                WHERE id = :id
                LIMIT 1
            ");

            $stmt->execute([
                ':id' => $id,
            ]);

            $currentStatus = $stmt->fetchColumn();

            if ($currentStatus === false) {
                throw new Exception('Redirect record not found.');
            }

            $newStatus = ((int)$currentStatus === 1) ? 0 : 1;

            $updateStmt = $pdo->prepare("
                UPDATE redirects
                SET status = :status
                WHERE id = :id
                LIMIT 1
            ");

            $updateStmt->execute([
                ':status' => $newStatus,
                ':id'     => $id,
            ]);

            flash_message(
                'success',
                $newStatus === 1
                    ? 'Redirect activated.'
                    : 'Redirect disabled.'
            );

            header('Location: redirects.php');
            exit;
        }

    } catch (Throwable $e) {

        flash_message(
            'error',
            $e->getMessage()
        );

        header('Location: redirects.php');
        exit;
    }
}

/* -----------------------------------------------------------
   Filters
----------------------------------------------------------- */

$search = isset($_GET['search'])
    ? trim((string)$_GET['search'])
    : '';

$statusFilter = isset($_GET['status'])
    ? (string)$_GET['status']
    : '';

$typeFilter = isset($_GET['redirect_type'])
    ? (string)$_GET['redirect_type']
    : '';

$where = [];
$params = [];

/* Search */

if ($search !== '') {

    $where[] = "
        (
            r.old_url LIKE :search
            OR r.new_url LIKE :search
        )
    ";

    $params[':search'] = '%' . $search . '%';
}

/* Status */

if ($statusFilter !== '' && in_array($statusFilter, ['0', '1'], true)) {

    $where[] = "r.status = :status";

    $params[':status'] = (int)$statusFilter;
}

/* Redirect Type */

if (
    $typeFilter !== '' &&
    in_array((int)$typeFilter, $allowedRedirectTypes, true)
) {

    $where[] = "r.redirect_type = :redirect_type";

    $params[':redirect_type'] = (int)$typeFilter;
}

$whereSql = '';

if (!empty($where)) {
    $whereSql = 'WHERE ' . implode(' AND ', $where);
}

/* -----------------------------------------------------------
   Stats
----------------------------------------------------------- */

$statsStmt = $pdo->query("
    SELECT
        COUNT(*) AS total,
        SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS active,
        SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) AS inactive,
        SUM(CASE WHEN redirect_type IN (301, 308) THEN 1 ELSE 0 END) AS permanent_count,
        SUM(CASE WHEN redirect_type IN (302, 303, 307) THEN 1 ELSE 0 END) AS temporary_count
    FROM redirects
");

$stats = $statsStmt->fetch();

$totalRedirects = (int)($stats['total'] ?? 0);
$activeRedirects = (int)($stats['active'] ?? 0);
$inactiveRedirects = (int)($stats['inactive'] ?? 0);
$permanentRedirects = (int)($stats['permanent_count'] ?? 0);
$temporaryRedirects = (int)($stats['temporary_count'] ?? 0);

/* -----------------------------------------------------------
   Last 30 Days
----------------------------------------------------------- */

$recentStmt = $pdo->query("
    SELECT COUNT(*)
    FROM redirects
    WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
");

$recentRedirects = (int)$recentStmt->fetchColumn();

/* -----------------------------------------------------------
   Redirect List
----------------------------------------------------------- */

$listSql = "
    SELECT
        r.id,
        r.old_url,
        r.new_url,
        r.redirect_type,
        r.status,
        r.created_at,
        r.updated_at
    FROM redirects r
    {$whereSql}
    ORDER BY r.id DESC
";

$listStmt = $pdo->prepare($listSql);
$listStmt->execute($params);

$redirects = $listStmt->fetchAll();

$flash = get_flash_message();

/* -----------------------------------------------------------
   Page Variables
----------------------------------------------------------- */

$pageTitle = 'URL Redirects';
$pageSubtitle = 'Manage website URL redirects and SEO-safe routing.';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        <?= e($pageTitle); ?> | Pure Chemical Admin
    </title>

    <meta
        name="description"
        content="Manage URL redirects"
    >

    <!-- Google Font -->
    <link
        rel="preconnect"
        href="https://fonts.googleapis.com"
    >

    <link
        rel="preconnect"
        href="https://fonts.gstatic.com"
        crossorigin
    >

    <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
        rel="stylesheet"
    >

    <!-- Font Awesome -->
    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
    >

    <style>
        :root {
            --primary: #0f766e;
            --primary-dark: #115e59;
            --primary-soft: #ecfdf5;

            --text: #0f172a;
            --muted: #64748b;

            --border: #e2e8f0;
            --surface: #ffffff;
            --surface-soft: #f8fafc;

            --success: #15803d;
            --success-bg: #f0fdf4;

            --danger: #dc2626;
            --danger-bg: #fef2f2;

            --warning: #d97706;
            --warning-bg: #fffbeb;

            --blue: #2563eb;
            --blue-bg: #eff6ff;

            --shadow-sm:
                0 1px 2px rgba(15, 23, 42, 0.04);

            --shadow-md:
                0 10px 30px rgba(15, 23, 42, 0.07);

            --shadow-lg:
                0 20px 50px rgba(15, 23, 42, 0.12);

            --radius: 18px;
        }

        * {
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            margin: 0;
            background:
                linear-gradient(
                    180deg,
                    #f8fafc 0%,
                    #f1f5f9 100%
                );

            color: var(--text);
            font-family: "Inter", sans-serif;
            font-size: 14px;
            line-height: 1.5;
        }

        button,
        input,
        select,
        textarea {
            font: inherit;
        }

        a {
            color: inherit;
            text-decoration: none;
        }

        /* -------------------------------------------------
           Main Area
        ------------------------------------------------- */

        .page-shell {
            margin-left: 280px;
            min-height: 100vh;
        }

        .page-container {
            width: min(1500px, calc(100% - 44px));
            margin: 0 auto;
            padding: 28px 0 60px;
        }

        /* -------------------------------------------------
           Topbar
        ------------------------------------------------- */

        .topbar {
            position: sticky;
            top: 0;
            z-index: 50;

            height: 76px;

            display: flex;
            align-items: center;
            justify-content: space-between;

            padding: 0 30px;

            background: rgba(255, 255, 255, 0.88);
            backdrop-filter: blur(18px);
            -webkit-backdrop-filter: blur(18px);

            border-bottom: 1px solid rgba(226, 232, 240, 0.85);
        }

        .topbar-left {
            display: flex;
            align-items: center;
            gap: 14px;
        }

        .topbar-icon {
            width: 42px;
            height: 42px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 13px;

            color: var(--primary);
            background: var(--primary-soft);
        }

        .topbar-title {
            margin: 0;
            font-size: 17px;
            font-weight: 800;
            letter-spacing: -0.02em;
        }

        .topbar-subtitle {
            margin: 2px 0 0;
            color: var(--muted);
            font-size: 12px;
        }

        .topbar-right {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .topbar-pill {
            display: inline-flex;
            align-items: center;
            gap: 8px;

            padding: 9px 13px;

            border: 1px solid var(--border);
            border-radius: 999px;

            background: #fff;
            color: var(--muted);

            font-size: 12px;
            font-weight: 600;
        }

        .topbar-pill i {
            color: var(--primary);
        }

        /* -------------------------------------------------
           Page Header
        ------------------------------------------------- */

        .page-header {
            display: flex;
            align-items: flex-end;
            justify-content: space-between;

            gap: 20px;

            margin-bottom: 24px;
        }

        .page-heading h1 {
            margin: 0;

            font-size: clamp(25px, 3vw, 34px);
            line-height: 1.15;

            letter-spacing: -0.035em;
            font-weight: 800;
        }

        .page-heading p {
            margin: 8px 0 0;
            color: var(--muted);
            max-width: 720px;
        }

        .btn-primary {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 9px;

            min-height: 44px;
            padding: 0 17px;

            border: 0;
            border-radius: 12px;

            color: #fff;
            background: linear-gradient(
                135deg,
                var(--primary),
                var(--primary-dark)
            );

            box-shadow:
                0 8px 18px rgba(15, 118, 110, 0.20);

            font-size: 13px;
            font-weight: 700;

            cursor: pointer;

            transition:
                transform .2s ease,
                box-shadow .2s ease;
        }

        .btn-primary:hover {
            transform: translateY(-1px);
            box-shadow:
                0 12px 24px rgba(15, 118, 110, 0.26);
        }

        /* -------------------------------------------------
           Stats
        ------------------------------------------------- */

        .stats-grid {
            display: grid;

            grid-template-columns:
                repeat(5, minmax(0, 1fr));

            gap: 15px;

            margin-bottom: 22px;
        }

        .stat-card {
            position: relative;
            overflow: hidden;

            background: var(--surface);

            border: 1px solid var(--border);
            border-radius: var(--radius);

            padding: 19px;

            box-shadow: var(--shadow-sm);
        }

        .stat-card::after {
            content: "";

            position: absolute;
            width: 90px;
            height: 90px;

            right: -35px;
            bottom: -40px;

            border-radius: 50%;

            background: var(--primary-soft);
        }

        .stat-top {
            display: flex;
            align-items: center;
            justify-content: space-between;

            gap: 12px;
        }

        .stat-icon {
            width: 40px;
            height: 40px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 12px;

            background: var(--primary-soft);
            color: var(--primary);
        }

        .stat-value {
            margin-top: 15px;

            font-size: 25px;
            line-height: 1;

            font-weight: 800;
            letter-spacing: -0.03em;
        }

        .stat-label {
            margin-top: 7px;

            color: var(--muted);

            font-size: 12px;
            font-weight: 600;
        }

        /* -------------------------------------------------
           Flash
        ------------------------------------------------- */

        .flash {
            display: flex;
            align-items: center;
            gap: 11px;

            margin-bottom: 18px;
            padding: 14px 16px;

            border-radius: 14px;

            font-weight: 600;
            font-size: 13px;
        }

        .flash.success {
            color: var(--success);
            background: var(--success-bg);
            border: 1px solid #bbf7d0;
        }

        .flash.error {
            color: var(--danger);
            background: var(--danger-bg);
            border: 1px solid #fecaca;
        }

        /* -------------------------------------------------
           Main Card
        ------------------------------------------------- */

        .content-card {
            background: var(--surface);

            border: 1px solid var(--border);
            border-radius: 22px;

            box-shadow: var(--shadow-md);

            overflow: hidden;
        }

        .card-toolbar {
            display: flex;
            align-items: center;
            justify-content: space-between;

            gap: 16px;

            padding: 18px 20px;

            border-bottom: 1px solid var(--border);
            background: #fff;
        }

        .toolbar-left {
            display: flex;
            align-items: center;

            gap: 10px;

            flex: 1;
        }

        .search-box {
            position: relative;

            width: min(460px, 100%);
        }

        .search-box i {
            position: absolute;

            left: 14px;
            top: 50%;

            transform: translateY(-50%);

            color: #94a3b8;
        }

        .form-control,
        .form-select {
            width: 100%;

            min-height: 44px;

            padding: 0 13px;

            border: 1px solid var(--border);
            border-radius: 11px;

            background: #fff;
            color: var(--text);

            outline: none;

            transition:
                border-color .2s ease,
                box-shadow .2s ease;
        }

        .search-box .form-control {
            padding-left: 41px;
        }

        .form-control:focus,
        .form-select:focus {
            border-color: rgba(15, 118, 110, .55);

            box-shadow:
                0 0 0 4px rgba(15, 118, 110, .09);
        }

        .filter-select {
            min-width: 145px;
        }

        .btn-light {
            min-height: 44px;

            display: inline-flex;
            align-items: center;
            justify-content: center;

            gap: 8px;

            padding: 0 14px;

            border: 1px solid var(--border);
            border-radius: 11px;

            background: #fff;
            color: #475569;

            font-weight: 700;
            font-size: 12px;

            cursor: pointer;
        }

        .btn-light:hover {
            background: var(--surface-soft);
        }

        /* -------------------------------------------------
           Table
        ------------------------------------------------- */

        .table-wrap {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;

            min-width: 1020px;
        }

        thead th {
            padding: 13px 18px;

            background: #f8fafc;

            border-bottom: 1px solid var(--border);

            color: #64748b;

            font-size: 10px;
            font-weight: 800;

            letter-spacing: .07em;
            text-transform: uppercase;

            white-space: nowrap;
        }

        tbody td {
            padding: 15px 18px;

            border-bottom: 1px solid #edf2f7;

            vertical-align: middle;
        }

        tbody tr {
            transition: background .18s ease;
        }

        tbody tr:hover {
            background: #fbfefd;
        }

        tbody tr:last-child td {
            border-bottom: 0;
        }

        .id-cell {
            color: #94a3b8;
            font-weight: 700;
            font-size: 12px;
        }

        .url-cell {
            max-width: 330px;
        }

        .url-main {
            display: flex;
            align-items: center;
            gap: 8px;

            min-width: 0;
        }

        .url-icon {
            width: 31px;
            height: 31px;

            flex: 0 0 31px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 9px;

            background: var(--primary-soft);
            color: var(--primary);

            font-size: 12px;
        }

        .url-text {
            min-width: 0;

            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;

            font-size: 12px;
            font-weight: 700;
        }

        .url-sub {
            margin-top: 3px;

            color: #94a3b8;

            font-size: 10px;
        }

        .arrow-cell {
            width: 42px;

            text-align: center;

            color: #94a3b8;
        }

        .type-badge {
            display: inline-flex;
            align-items: center;

            padding: 6px 9px;

            border-radius: 8px;

            font-size: 10px;
            font-weight: 800;

            white-space: nowrap;
        }

        .type-permanent {
            color: #166534;
            background: #dcfce7;
        }

        .type-temporary {
            color: #92400e;
            background: #fef3c7;
        }

        .type-other {
            color: #1d4ed8;
            background: #dbeafe;
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;

            padding: 6px 9px;

            border-radius: 999px;

            font-size: 10px;
            font-weight: 800;
        }

        .status-badge.active {
            color: #166534;
            background: #dcfce7;
        }

        .status-badge.inactive {
            color: #991b1b;
            background: #fee2e2;
        }

        .status-dot {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: currentColor;
        }

        .date-text {
            color: #64748b;
            font-size: 11px;
            white-space: nowrap;
        }

        .actions {
            display: flex;
            align-items: center;
            justify-content: flex-end;

            gap: 6px;
        }

        .icon-btn {
            width: 34px;
            height: 34px;

            display: inline-flex;
            align-items: center;
            justify-content: center;

            border: 1px solid var(--border);
            border-radius: 9px;

            background: #fff;
            color: #64748b;

            cursor: pointer;

            transition:
                background .18s ease,
                color .18s ease,
                border-color .18s ease;
        }

        .icon-btn:hover {
            background: var(--surface-soft);
            color: var(--text);
        }

        .icon-btn.success:hover {
            color: var(--success);
            border-color: #bbf7d0;
            background: var(--success-bg);
        }

        .icon-btn.warning:hover {
            color: var(--warning);
            border-color: #fde68a;
            background: var(--warning-bg);
        }

        .icon-btn.danger:hover {
            color: var(--danger);
            border-color: #fecaca;
            background: var(--danger-bg);
        }

        .empty-state {
            text-align: center;
            padding: 70px 20px;
        }

        .empty-icon {
            width: 64px;
            height: 64px;

            margin: 0 auto 15px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 18px;

            background: var(--primary-soft);
            color: var(--primary);

            font-size: 24px;
        }

        .empty-state h3 {
            margin: 0;

            font-size: 17px;
        }

        .empty-state p {
            margin: 7px 0 20px;

            color: var(--muted);
        }

        /* -------------------------------------------------
           Modal
        ------------------------------------------------- */

        .modal-backdrop {
            position: fixed;

            inset: 0;

            z-index: 100;

            display: none;
            align-items: center;
            justify-content: center;

            padding: 20px;

            background: rgba(15, 23, 42, .55);

            backdrop-filter: blur(7px);
            -webkit-backdrop-filter: blur(7px);
        }

        .modal-backdrop.show {
            display: flex;
        }

        .modal {
            width: min(680px, 100%);

            max-height: calc(100vh - 40px);

            overflow-y: auto;

            background: #fff;

            border-radius: 22px;

            box-shadow: var(--shadow-lg);

            animation: modalIn .22s ease;
        }

        @keyframes modalIn {
            from {
                opacity: 0;
                transform: translateY(10px) scale(.98);
            }

            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }

        .modal-header {
            display: flex;
            align-items: center;
            justify-content: space-between;

            gap: 15px;

            padding: 20px 22px;

            border-bottom: 1px solid var(--border);
        }

        .modal-title {
            display: flex;
            align-items: center;
            gap: 11px;
        }

        .modal-title-icon {
            width: 38px;
            height: 38px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 11px;

            background: var(--primary-soft);
            color: var(--primary);
        }

        .modal-title h3 {
            margin: 0;

            font-size: 17px;
            font-weight: 800;
        }

        .modal-title p {
            margin: 2px 0 0;

            color: var(--muted);
            font-size: 11px;
        }

        .close-btn {
            width: 36px;
            height: 36px;

            display: flex;
            align-items: center;
            justify-content: center;

            border: 1px solid var(--border);
            border-radius: 10px;

            background: #fff;
            color: #64748b;

            cursor: pointer;
        }

        .close-btn:hover {
            color: var(--danger);
            background: var(--danger-bg);
        }

        .modal-body {
            padding: 22px;
        }

        .form-grid {
            display: grid;

            grid-template-columns:
                repeat(2, minmax(0, 1fr));

            gap: 17px;
        }

        .form-group.full {
            grid-column: 1 / -1;
        }

        .form-label {
            display: block;

            margin-bottom: 7px;

            color: #334155;

            font-size: 12px;
            font-weight: 800;
        }

        .required {
            color: var(--danger);
        }

        .field-help {
            margin-top: 6px;

            color: #94a3b8;

            font-size: 10px;
            line-height: 1.5;
        }

        .modal-footer {
            display: flex;
            align-items: center;
            justify-content: flex-end;

            gap: 9px;

            padding: 16px 22px;

            border-top: 1px solid var(--border);

            background: #fafafa;
        }

        .btn-secondary {
            min-height: 42px;

            padding: 0 15px;

            border: 1px solid var(--border);
            border-radius: 11px;

            background: #fff;
            color: #475569;

            font-size: 12px;
            font-weight: 700;

            cursor: pointer;
        }

        .status-toggle {
            display: flex;
            align-items: center;
            gap: 10px;

            min-height: 44px;

            padding: 0 13px;

            border: 1px solid var(--border);
            border-radius: 11px;

            background: #fff;
        }

        .status-toggle input {
            width: 17px;
            height: 17px;

            accent-color: var(--primary);
        }

        .status-toggle span {
            font-size: 12px;
            font-weight: 700;
        }

        /* -------------------------------------------------
           Responsive
        ------------------------------------------------- */

        @media (max-width: 1250px) {
            .stats-grid {
                grid-template-columns:
                    repeat(3, minmax(0, 1fr));
            }
        }

        @media (max-width: 1100px) {
            .page-shell {
                margin-left: 0;
            }

            .topbar {
                padding: 0 20px;
            }
        }

        @media (max-width: 800px) {
            .page-container {
                width: min(100% - 28px, 1500px);
                padding-top: 20px;
            }

            .page-header {
                align-items: flex-start;
                flex-direction: column;
            }

            .stats-grid {
                grid-template-columns:
                    repeat(2, minmax(0, 1fr));
            }

            .card-toolbar {
                align-items: stretch;
                flex-direction: column;
            }

            .toolbar-left {
                flex-direction: column;
                align-items: stretch;
            }

            .search-box {
                width: 100%;
            }

            .filter-select {
                width: 100%;
            }

            .topbar-subtitle {
                display: none;
            }
        }

        @media (max-width: 560px) {
            .page-container {
                width: calc(100% - 20px);
                padding-bottom: 35px;
            }

            .topbar {
                height: 66px;
                padding: 0 13px;
            }

            .topbar-icon {
                width: 37px;
                height: 37px;
            }

            .topbar-title {
                font-size: 14px;
            }

            .topbar-pill {
                padding: 8px 10px;
            }

            .topbar-pill span {
                display: none;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .form-grid {
                grid-template-columns: 1fr;
            }

            .form-group.full {
                grid-column: auto;
            }

            .modal-backdrop {
                padding: 10px;
            }

            .modal {
                border-radius: 17px;
            }

            .modal-body {
                padding: 17px;
            }

            .modal-footer {
                padding: 14px 17px;
            }
        }
    </style>
</head>

<body>

<?php
/*
 * IMPORTANT:
 * Sidebar is intentionally included separately.
 * Do not include admin/header.php here.
 */
require_once __DIR__ . '/sidebar.php';
?>

<div class="page-shell">

    <!-- =====================================================
         TOPBAR
    ====================================================== -->

    <header class="topbar">

        <div class="topbar-left">

            <div class="topbar-icon">
                <i class="fa-solid fa-arrow-right-arrow-left"></i>
            </div>

            <div>
                <h2 class="topbar-title">
                    URL Redirects
                </h2>

                <p class="topbar-subtitle">
                    SEO & URL management
                </p>
            </div>

        </div>

        <div class="topbar-right">

            <div class="topbar-pill">
                <i class="fa-solid fa-shield-halved"></i>
                <span>Admin Panel</span>
            </div>

        </div>

    </header>

    <!-- =====================================================
         MAIN
    ====================================================== -->

    <main class="page-container">

        <!-- Page Header -->

        <div class="page-header">

            <div class="page-heading">

                <h1>
                    Redirect Management
                </h1>

                <p>
                    Create and manage URL redirects to preserve
                    old links, improve SEO and avoid broken pages.
                </p>

            </div>

            <button
                type="button"
                class="btn-primary"
                onclick="openAddModal()"
            >
                <i class="fa-solid fa-plus"></i>
                Add Redirect
            </button>

        </div>

        <!-- =================================================
             FLASH
        ================================================== -->

        <?php if ($flash): ?>

            <div class="flash <?= e($flash['type']); ?>">

                <?php if ($flash['type'] === 'success'): ?>

                    <i class="fa-solid fa-circle-check"></i>

                <?php else: ?>

                    <i class="fa-solid fa-circle-exclamation"></i>

                <?php endif; ?>

                <span>
                    <?= e($flash['message']); ?>
                </span>

            </div>

        <?php endif; ?>

        <!-- =================================================
             STATS
        ================================================== -->

        <div class="stats-grid">

            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-icon">
                        <i class="fa-solid fa-link"></i>
                    </div>

                </div>

                <div class="stat-value">
                    <?= number_format($totalRedirects); ?>
                </div>

                <div class="stat-label">
                    Total Redirects
                </div>

            </div>

            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-icon">
                        <i class="fa-solid fa-circle-check"></i>
                    </div>

                </div>

                <div class="stat-value">
                    <?= number_format($activeRedirects); ?>
                </div>

                <div class="stat-label">
                    Active Redirects
                </div>

            </div>

            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-icon">
                        <i class="fa-solid fa-circle-pause"></i>
                    </div>

                </div>

                <div class="stat-value">
                    <?= number_format($inactiveRedirects); ?>
                </div>

                <div class="stat-label">
                    Disabled Redirects
                </div>

            </div>

            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-icon">
                        <i class="fa-solid fa-arrow-trend-up"></i>
                    </div>

                </div>

                <div class="stat-value">
                    <?= number_format($permanentRedirects); ?>
                </div>

                <div class="stat-label">
                    Permanent Redirects
                </div>

            </div>

            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-icon">
                        <i class="fa-solid fa-clock-rotate-left"></i>
                    </div>

                </div>

                <div class="stat-value">
                    <?= number_format($recentRedirects); ?>
                </div>

                <div class="stat-label">
                    Added Last 30 Days
                </div>

            </div>

        </div>

        <!-- =================================================
             REDIRECT LIST
        ================================================== -->

        <section class="content-card">

            <div class="card-toolbar">

                <form
                    method="get"
                    action="redirects.php"
                    class="toolbar-left"
                >

                    <div class="search-box">

                        <i class="fa-solid fa-magnifying-glass"></i>

                        <input
                            type="text"
                            name="search"
                            class="form-control"
                            value="<?= e($search); ?>"
                            placeholder="Search old or new URL..."
                        >

                    </div>

                    <select
                        name="status"
                        class="form-select filter-select"
                        onchange="this.form.submit()"
                    >

                        <option value="">
                            All Status
                        </option>

                        <option
                            value="1"
                            <?= $statusFilter === '1' ? 'selected' : ''; ?>
                        >
                            Active
                        </option>

                        <option
                            value="0"
                            <?= $statusFilter === '0' ? 'selected' : ''; ?>
                        >
                            Disabled
                        </option>

                    </select>

                    <select
                        name="redirect_type"
                        class="form-select filter-select"
                        onchange="this.form.submit()"
                    >

                        <option value="">
                            All Types
                        </option>

                        <?php foreach ($allowedRedirectTypes as $type): ?>

                            <option
                                value="<?= $type; ?>"
                                <?= (string)$typeFilter === (string)$type ? 'selected' : ''; ?>
                            >
                                <?= e(redirect_type_label($type)); ?>
                            </option>

                        <?php endforeach; ?>

                    </select>

                    <button
                        type="submit"
                        class="btn-light"
                    >
                        <i class="fa-solid fa-filter"></i>
                        Filter
                    </button>

                    <?php if (
                        $search !== '' ||
                        $statusFilter !== '' ||
                        $typeFilter !== ''
                    ): ?>

                        <a
                            href="redirects.php"
                            class="btn-light"
                        >
                            <i class="fa-solid fa-xmark"></i>
                            Clear
                        </a>

                    <?php endif; ?>

                </form>

            </div>

            <?php if (!empty($redirects)): ?>

                <div class="table-wrap">

                    <table>

                        <thead>

                            <tr>

                                <th>
                                    ID
                                </th>

                                <th>
                                    Old URL
                                </th>

                                <th>
                                    →
                                </th>

                                <th>
                                    New URL
                                </th>

                                <th>
                                    Type
                                </th>

                                <th>
                                    Status
                                </th>

                                <th>
                                    Created
                                </th>

                                <th style="text-align:right;">
                                    Actions
                                </th>

                            </tr>

                        </thead>

                        <tbody>

                        <?php foreach ($redirects as $redirect): ?>

                            <tr>

                                <!-- ID -->

                                <td>
                                    <span class="id-cell">
                                        #<?= (int)$redirect['id']; ?>
                                    </span>
                                </td>

                                <!-- OLD URL -->

                                <td class="url-cell">

                                    <div class="url-main">

                                        <div class="url-icon">
                                            <i class="fa-solid fa-arrow-up-right-from-square"></i>
                                        </div>

                                        <div style="min-width:0;">

                                            <div
                                                class="url-text"
                                                title="<?= e($redirect['old_url']); ?>"
                                            >
                                                <?= e($redirect['old_url']); ?>
                                            </div>

                                            <div class="url-sub">
                                                Source URL
                                            </div>

                                        </div>

                                    </div>

                                </td>

                                <!-- ARROW -->

                                <td class="arrow-cell">

                                    <i class="fa-solid fa-arrow-right"></i>

                                </td>

                                <!-- NEW URL -->

                                <td class="url-cell">

                                    <div class="url-main">

                                        <div
                                            class="url-icon"
                                            style="
                                                color:#2563eb;
                                                background:#eff6ff;
                                            "
                                        >
                                            <i class="fa-solid fa-location-arrow"></i>
                                        </div>

                                        <div style="min-width:0;">

                                            <div
                                                class="url-text"
                                                title="<?= e($redirect['new_url']); ?>"
                                            >
                                                <?= e($redirect['new_url']); ?>
                                            </div>

                                            <div class="url-sub">
                                                Destination URL
                                            </div>

                                        </div>

                                    </div>

                                </td>

                                <!-- TYPE -->

                                <td>

                                    <span
                                        class="type-badge <?= e(
                                            redirect_type_badge_class(
                                                $redirect['redirect_type']
                                            )
                                        ); ?>"
                                    >
                                        <?= e(
                                            redirect_type_label(
                                                $redirect['redirect_type']
                                            )
                                        ); ?>
                                    </span>

                                </td>

                                <!-- STATUS -->

                                <td>

                                    <?php if ((int)$redirect['status'] === 1): ?>

                                        <span class="status-badge active">
                                            <span class="status-dot"></span>
                                            Active
                                        </span>

                                    <?php else: ?>

                                        <span class="status-badge inactive">
                                            <span class="status-dot"></span>
                                            Disabled
                                        </span>

                                    <?php endif; ?>

                                </td>

                                <!-- DATE -->

                                <td>

                                    <span class="date-text">
                                        <?= !empty($redirect['created_at'])
                                            ? e(date(
                                                'd M Y',
                                                strtotime($redirect['created_at'])
                                            ))
                                            : '—';
                                        ?>
                                    </span>

                                </td>

                                <!-- ACTIONS -->

                                <td>

                                    <div class="actions">

                                        <!-- Edit -->

                                        <button
                                            type="button"
                                            class="icon-btn"
                                            title="Edit"
                                            onclick='openEditModal(
                                                <?= json_encode([
                                                    'id' => (int)$redirect['id'],
                                                    'old_url' => $redirect['old_url'],
                                                    'new_url' => $redirect['new_url'],
                                                    'redirect_type' => (int)$redirect['redirect_type'],
                                                    'status' => (int)$redirect['status'],
                                                ], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT); ?>
                                            )'
                                        >
                                            <i class="fa-solid fa-pen"></i>
                                        </button>

                                        <!-- Toggle -->

                                        <form
                                            method="post"
                                            style="display:inline;"
                                            onsubmit="return confirmToggle(<?= (int)$redirect['status']; ?>);"
                                        >

                                            <?= csrf_field(); ?>

                                            <input
                                                type="hidden"
                                                name="action"
                                                value="toggle_status"
                                            >

                                            <input
                                                type="hidden"
                                                name="id"
                                                value="<?= (int)$redirect['id']; ?>"
                                            >

                                            <button
                                                type="submit"
                                                class="icon-btn <?= (int)$redirect['status'] === 1 ? 'warning' : 'success'; ?>"
                                                title="<?= (int)$redirect['status'] === 1 ? 'Disable' : 'Activate'; ?>"
                                            >

                                                <?php if ((int)$redirect['status'] === 1): ?>

                                                    <i class="fa-solid fa-pause"></i>

                                                <?php else: ?>

                                                    <i class="fa-solid fa-play"></i>

                                                <?php endif; ?>

                                            </button>

                                        </form>

                                        <!-- Delete -->

                                        <form
                                            method="post"
                                            style="display:inline;"
                                            onsubmit="return confirmDelete();"
                                        >

                                            <?= csrf_field(); ?>

                                            <input
                                                type="hidden"
                                                name="action"
                                                value="delete"
                                            >

                                            <input
                                                type="hidden"
                                                name="id"
                                                value="<?= (int)$redirect['id']; ?>"
                                            >

                                            <button
                                                type="submit"
                                                class="icon-btn danger"
                                                title="Delete"
                                            >
                                                <i class="fa-solid fa-trash"></i>
                                            </button>

                                        </form>

                                    </div>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>

            <?php else: ?>

                <div class="empty-state">

                    <div class="empty-icon">
                        <i class="fa-solid fa-arrow-right-arrow-left"></i>
                    </div>

                    <h3>
                        No redirects found
                    </h3>

                    <p>
                        <?php if (
                            $search !== '' ||
                            $statusFilter !== '' ||
                            $typeFilter !== ''
                        ): ?>

                            Try changing your filters or create a new redirect.

                        <?php else: ?>

                            Start by creating your first URL redirect.

                        <?php endif; ?>
                    </p>

                    <?php if (
                        $search !== '' ||
                        $statusFilter !== '' ||
                        $typeFilter !== ''
                    ): ?>

                        <a
                            href="redirects.php"
                            class="btn-light"
                        >
                            <i class="fa-solid fa-rotate-left"></i>
                            Reset Filters
                        </a>

                    <?php else: ?>

                        <button
                            type="button"
                            class="btn-primary"
                            onclick="openAddModal()"
                        >
                            <i class="fa-solid fa-plus"></i>
                            Add Redirect
                        </button>

                    <?php endif; ?>

                </div>

            <?php endif; ?>

        </section>

    </main>

</div>

<!-- =========================================================
     ADD / EDIT MODAL
========================================================= -->

<div
    class="modal-backdrop"
    id="redirectModal"
    onclick="backdropClose(event)"
>

    <div class="modal">

        <div class="modal-header">

            <div class="modal-title">

                <div class="modal-title-icon">
                    <i
                        id="modalIcon"
                        class="fa-solid fa-plus"
                    ></i>
                </div>

                <div>

                    <h3 id="modalTitle">
                        Add Redirect
                    </h3>

                    <p id="modalSubtitle">
                        Create a new URL redirect.
                    </p>

                </div>

            </div>

            <button
                type="button"
                class="close-btn"
                onclick="closeModal()"
            >
                <i class="fa-solid fa-xmark"></i>
            </button>

        </div>

        <form
            method="post"
            action="redirects.php"
            id="redirectForm"
        >

            <?= csrf_field(); ?>

            <input
                type="hidden"
                name="action"
                value="save"
            >

            <input
                type="hidden"
                name="id"
                id="redirectId"
                value="0"
            >

            <div class="modal-body">

                <div class="form-grid">

                    <!-- Old URL -->

                    <div class="form-group full">

                        <label class="form-label">
                            Old URL
                            <span class="required">*</span>
                        </label>

                        <input
                            type="text"
                            name="old_url"
                            id="oldUrl"
                            class="form-control"
                            placeholder="/old-page"
                            required
                            maxlength="1000"
                        >

                        <div class="field-help">
                            Example:
                            <strong>/old-product-page</strong>
                            or
                            <strong>https://example.com/old-page</strong>
                        </div>

                    </div>

                    <!-- New URL -->

                    <div class="form-group full">

                        <label class="form-label">
                            New URL
                            <span class="required">*</span>
                        </label>

                        <input
                            type="text"
                            name="new_url"
                            id="newUrl"
                            class="form-control"
                            placeholder="/new-page"
                            required
                            maxlength="1000"
                        >

                        <div class="field-help">
                            Internal relative URLs and HTTP/HTTPS URLs
                            are supported.
                        </div>

                    </div>

                    <!-- Redirect Type -->

                    <div class="form-group">

                        <label class="form-label">
                            Redirect Type
                        </label>

                        <select
                            name="redirect_type"
                            id="redirectType"
                            class="form-select"
                        >

                            <option value="301">
                                301 — Permanent
                            </option>

                            <option value="302">
                                302 — Temporary
                            </option>

                            <option value="303">
                                303 — See Other
                            </option>

                            <option value="307">
                                307 — Temporary
                            </option>

                            <option value="308">
                                308 — Permanent
                            </option>

                        </select>

                        <div class="field-help">
                            Use 301/308 when the URL has permanently moved.
                        </div>

                    </div>

                    <!-- Status -->

                    <div class="form-group">

                        <label class="form-label">
                            Status
                        </label>

                        <label class="status-toggle">

                            <input
                                type="checkbox"
                                name="status"
                                id="redirectStatus"
                                value="1"
                                checked
                            >

                            <span>
                                Redirect is active
                            </span>

                        </label>

                    </div>

                </div>

            </div>

            <div class="modal-footer">

                <button
                    type="button"
                    class="btn-secondary"
                    onclick="closeModal()"
                >
                    Cancel
                </button>

                <button
                    type="submit"
                    class="btn-primary"
                    id="saveButton"
                >
                    <i class="fa-solid fa-check"></i>
                    Save Redirect
                </button>

            </div>

        </form>

    </div>

</div>

<script>
    /* -------------------------------------------------------
       Modal
    ------------------------------------------------------- */

    const redirectModal = document.getElementById('redirectModal');
    const redirectForm = document.getElementById('redirectForm');

    const redirectId = document.getElementById('redirectId');
    const oldUrl = document.getElementById('oldUrl');
    const newUrl = document.getElementById('newUrl');
    const redirectType = document.getElementById('redirectType');
    const redirectStatus = document.getElementById('redirectStatus');

    const modalTitle = document.getElementById('modalTitle');
    const modalSubtitle = document.getElementById('modalSubtitle');
    const modalIcon = document.getElementById('modalIcon');
    const saveButton = document.getElementById('saveButton');

    function openAddModal() {

        redirectForm.reset();

        redirectId.value = '0';

        oldUrl.value = '';
        newUrl.value = '';

        redirectType.value = '301';

        redirectStatus.checked = true;

        modalTitle.textContent = 'Add Redirect';

        modalSubtitle.textContent =
            'Create a new URL redirect.';

        modalIcon.className =
            'fa-solid fa-plus';

        saveButton.innerHTML =
            '<i class="fa-solid fa-check"></i> Save Redirect';

        redirectModal.classList.add('show');

        document.body.style.overflow = 'hidden';

        setTimeout(function () {
            oldUrl.focus();
        }, 100);
    }

    function openEditModal(data) {

        redirectId.value = data.id || 0;

        oldUrl.value = data.old_url || '';

        newUrl.value = data.new_url || '';

        redirectType.value =
            String(data.redirect_type || 301);

        redirectStatus.checked =
            Number(data.status) === 1;

        modalTitle.textContent = 'Edit Redirect';

        modalSubtitle.textContent =
            'Update the selected URL redirect.';

        modalIcon.className =
            'fa-solid fa-pen';

        saveButton.innerHTML =
            '<i class="fa-solid fa-floppy-disk"></i> Update Redirect';

        redirectModal.classList.add('show');

        document.body.style.overflow = 'hidden';

        setTimeout(function () {
            oldUrl.focus();
        }, 100);
    }

    function closeModal() {

        redirectModal.classList.remove('show');

        document.body.style.overflow = '';
    }

    function backdropClose(event) {

        if (event.target === redirectModal) {
            closeModal();
        }
    }

    document.addEventListener('keydown', function (event) {

        if (event.key === 'Escape') {
            closeModal();
        }

    });

    /* -------------------------------------------------------
       Confirmations
    ------------------------------------------------------- */

    function confirmDelete() {

        return confirm(
            'Are you sure you want to delete this redirect? This action cannot be undone.'
        );
    }

    function confirmToggle(currentStatus) {

        if (Number(currentStatus) === 1) {

            return confirm(
                'Disable this redirect?'
            );

        }

        return confirm(
            'Activate this redirect?'
        );
    }

    /* -------------------------------------------------------
       Submit Protection
    ------------------------------------------------------- */

    redirectForm.addEventListener('submit', function () {

        saveButton.disabled = true;

        saveButton.innerHTML =
            '<i class="fa-solid fa-spinner fa-spin"></i> Saving...';

    });

    /* -------------------------------------------------------
       Auto clean URL
    ------------------------------------------------------- */

    oldUrl.addEventListener('blur', function () {

        let value = oldUrl.value.trim();

        if (value !== '' && value.charAt(0) === '/') {
            value = '/' + value.replace(/^\/+/, '');
        }

        oldUrl.value = value;

    });

    newUrl.addEventListener('blur', function () {

        let value = newUrl.value.trim();

        if (value !== '' && value.charAt(0) === '/') {
            value = '/' + value.replace(/^\/+/, '');
        }

        newUrl.value = value;

    });
</script>

</body>
</html>