<?php
require_once __DIR__ . '/../config.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ----------------------
// AUTH CHECK
// ----------------------

if (
    !isset($_SESSION['admin_logged_in']) ||
    $_SESSION['admin_logged_in'] !== true
) {
    if (isset($_GET['ajax'])) {
        header('Content-Type: application/json');
        http_response_code(401);

        echo json_encode([
            'valid' => false,
            'duplicate' => false,
            'slug' => '',
            'message' => 'Not authorised.'
        ]);

        exit;
    }

    header('Location: login.php');
    exit;
}

// ----------------------
// CURRENT USER
// ----------------------

$userId = $_SESSION['admin_user_id'] ?? 0;

$currentUserRole = '';
$currentUsername = 'A user';

// ----------------------
// FETCH CURRENT USER ROLE
// ----------------------

try {

    $userStmt = $pdo->prepare("
        SELECT 
            username,
            role
        FROM admin_users
        WHERE id = ?
        LIMIT 1
    ");

    $userStmt->execute([$userId]);

    $currentUser = $userStmt->fetch(PDO::FETCH_ASSOC);

    if ($currentUser) {
        $currentUsername = $currentUser['username'] ?? 'A user';
        $currentUserRole = $currentUser['role'] ?? '';
    }

} catch (PDOException $e) {

    $currentUserRole = '';
    $currentUsername = 'A user';
}

$canPublishDirectly = in_array(
    $currentUserRole,
    ['Admin', 'Editor'],
    true
);

$systemSenderId = $userId;

// ----------------------
// FUNCTION TO CREATE SLUGS
// ----------------------

function generateSlug($string) {

    $slug = strtolower(
        trim(
            preg_replace('/[^A-Za-z0-9-]+/', '-', $string),
            '-'
        )
    );

    return $slug;
}


// ----------------------
// FEATURED POST HELPER
// ----------------------
//
// Only one live published post should be featured at a time.
// Pending posts can be submitted with featured ticked, but they should not
// replace the current featured post until an admin approves/publishes them.

function unfeatureOtherPosts(PDO $pdo, int $currentPostId): void {

    $stmt = $pdo->prepare("
        UPDATE posts
        SET featured = 0
        WHERE id <> ?
          AND featured = 1
    ");

    $stmt->execute([$currentPostId]);
}

// ----------------------
// AJAX: CHECK SLUG
// ----------------------

if (
    isset($_GET['ajax']) &&
    $_GET['ajax'] === 'check_slug'
) {
    header('Content-Type: application/json');

    $slug = generateSlug($_GET['slug'] ?? '');

    if ($slug === '') {
        echo json_encode([
            'valid' => false,
            'duplicate' => false,
            'slug' => '',
            'message' => 'Slug is required.'
        ]);

        exit;
    }

    if (!preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug)) {
        echo json_encode([
            'valid' => false,
            'duplicate' => false,
            'slug' => $slug,
            'message' => 'Slug can only contain lowercase letters, numbers and hyphens.'
        ]);

        exit;
    }

    try {

        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM posts
            WHERE slug = ?
        ");

        $stmt->execute([$slug]);

        $duplicate = ((int)$stmt->fetchColumn()) > 0;

        echo json_encode([
            'valid' => !$duplicate,
            'duplicate' => $duplicate,
            'slug' => $slug,
            'message' => $duplicate
                ? 'This slug is already in use.'
                : 'Slug is available.'
        ]);

        exit;

    } catch (PDOException $e) {

        echo json_encode([
            'valid' => false,
            'duplicate' => false,
            'slug' => $slug,
            'message' => 'Could not check slug.'
        ]);

        exit;
    }
}

require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/layout.php';

// ----------------------
// INITIALIZE VARIABLES
// ----------------------

$error = $error ?? '';
$success = $success ?? '';
$title = $title ?? '';
$slug = $slug ?? '';
$tagline = $tagline ?? '';
$meta_description = $meta_description ?? '';
$content = $content ?? '';
$tags = $tags ?? '';
$post_location = $post_location ?? '';
$scheduled_at = $scheduled_at ?? '';
$featured = isset($featured) ? (bool)$featured : false;

// ----------------------
// FETCH POST LOCATIONS
// ----------------------

try {

    $stmt = $pdo->query("
        SELECT key_name, label
        FROM post_locations
        ORDER BY label ASC
    ");

    $postLocations = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

} catch (PDOException $e) {

    $postLocations = [];

    $error = 'Error fetching post locations: '
        . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
}

// ----------------------
// LOAD MEDIA FILES
// ----------------------

$mediaFiles = [];

$mediaDir = __DIR__ . '/../uploads/media/';

if (is_dir($mediaDir)) {

    $files = scandir($mediaDir);

    $files = array_diff($files, ['.', '..']);

    foreach ($files as $file) {

        $fullPath = $mediaDir . $file;

        if (is_file($fullPath)) {

            $mediaFiles[] = [
                'name' => $file,
                'url' => '/uploads/media/' . $file,
                'modified' => filemtime($fullPath)
            ];
        }
    }

    usort($mediaFiles, function ($a, $b) {

        return $b['modified'] <=> $a['modified'];
    });
}

// ----------------------
// HANDLE POST
// ----------------------

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $title = $_POST['title'] ?? '';
    $slug = generateSlug($_POST['slug'] ?? '');
    $tagline = $_POST['tagline'] ?? '';
    $meta_description = $_POST['meta_description'] ?? '';
    $content = $_POST['content'] ?? '';
    $tags = $_POST['tags'] ?? '';
    $post_location = $_POST['post_location'] ?? '';
    $scheduled_at = trim((string)($_POST['scheduled_at'] ?? ''));

    if ($scheduled_at === '') {
        $scheduled_at = null;
    } else {
        $scheduled_at = str_replace('T', ' ', $scheduled_at) . ':00';
    }

    if ($slug === '' && trim($title) !== '') {
        $slug = generateSlug($title);
    }

    $featured = isset($_POST['featured'])
        && $_POST['featured'] === '1';

    // ----------------------
    // STATUS
    // ----------------------

    $requestedStatus = $_POST['status'] ?? 'draft';

    if (!in_array($requestedStatus, ['draft', 'published', 'scheduled'], true)) {
        $requestedStatus = 'draft';
    }

    $status = $requestedStatus;

    // Non Admin / Editor users cannot publish or schedule directly.
    if (
        in_array($requestedStatus, ['published', 'scheduled'], true)
        && !$canPublishDirectly
    ) {
        $status = 'pending';
        $scheduled_at = null;
    }

    // Admin / Editor scheduling.
    if (
        $requestedStatus === 'scheduled'
        && $canPublishDirectly
    ) {
        $status = 'scheduled';
    }

    // Only scheduled posts should keep a scheduled date.
    if ($status !== 'scheduled') {
        $scheduled_at = null;
    }

    $imagePath = null;

    if (
        trim($title) === '' ||
        trim(strip_tags($content)) === '' ||
        $post_location === ''
    ) {

        $error = 'Please fill in all required fields.';

    } elseif ($slug === '') {

        $error = 'Please enter a slug.';

    } elseif (!preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug)) {

        $error = 'Slug can only contain lowercase letters, numbers and hyphens.';

    } elseif (mb_strlen($meta_description) > 160) {

        $error = 'Meta description must be 160 characters or fewer.';

    } elseif (
        $status === 'scheduled'
        && empty($scheduled_at)
    ) {

        $error = 'Please choose a date and time to schedule this post.';

    } else {

        try {

            // ----------------------
            // CHECK SLUG IS UNIQUE
            // ----------------------

            $checkStmt = $pdo->prepare("
                SELECT COUNT(*)
                FROM posts
                WHERE slug = ?
            ");

            $checkStmt->execute([$slug]);

            if ((int)$checkStmt->fetchColumn() > 0) {
                $error = 'This slug is already in use. Please choose another one.';
            }

            // ----------------------
            // HANDLE IMAGE UPLOAD
            // ----------------------

            if (
                !$error &&
                isset($_FILES['image']) &&
                $_FILES['image']['error'] === UPLOAD_ERR_OK
            ) {

                $uploadDir = __DIR__ . '/../uploads/';

                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }

                $fileTmp = $_FILES['image']['tmp_name'];

                $fileName = basename($_FILES['image']['name']);

                $ext = pathinfo($fileName, PATHINFO_EXTENSION);

                $newFileName = uniqid('post_', true) . '.' . $ext;

                $destination = $uploadDir . $newFileName;

                $allowedTypes = [
                    'image/jpeg',
                    'image/png',
                    'image/gif',
                    'image/webp'
                ];

                if (
                    in_array(
                        mime_content_type($fileTmp),
                        $allowedTypes,
                        true
                    )
                ) {

                    if (move_uploaded_file($fileTmp, $destination)) {

                        $imagePath = 'uploads/' . $newFileName;

                    } else {

                        $error = 'Failed to move uploaded image.';
                    }

                } else {

                    $error = 'Only JPG, PNG, GIF, and WEBP files are allowed.';
                }
            }

            // ----------------------
            // INSERT POST
            // ----------------------

            if (!$error) {

                $stmt = $pdo->prepare("
                    INSERT INTO posts
                    (
                        title,
                        tagline,
                        meta_description,
                        slug,
                        content,
                        tags,
                        post_location,
                        featured,
                        image_path,
                        created_by,
                        status,
                        scheduled_at
                    )
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");

                $stmt->execute([
                    $title,
                    $tagline,
                    $meta_description,
                    $slug,
                    $content,
                    $tags,
                    $post_location,
                    $featured ? 1 : 0,
                    $imagePath,
                    $userId,
                    $status,
                    $scheduled_at
                ]);

                $newPostId = (int)$pdo->lastInsertId();

                // ----------------------
                // FEATURED POST EXCLUSIVITY
                // ----------------------
                //
                // If an Admin / Editor publishes a featured post directly,
                // remove featured from every other post.
                // Pending posts do not trigger this until approved/published.

                if (
                    $featured
                    && $status === 'published'
                ) {
                    unfeatureOtherPosts($pdo, $newPostId);
                }

                // ----------------------
                // SEND ADMIN MESSAGE IF PENDING
                // ----------------------

                if ($status === 'pending') {

                    $adminStmt = $pdo->prepare("
                        SELECT id
                        FROM admin_users
                        WHERE role = 'Admin'
                    ");

                    $adminStmt->execute();

                    $adminUsers = $adminStmt->fetchAll(PDO::FETCH_COLUMN);

                    if (!empty($adminUsers)) {

                        $messageSubject = 'Post waiting for review';

                        $messageBody = '
                            <p>
                                <strong>'
                                . htmlspecialchars($currentUsername, ENT_QUOTES, 'UTF-8')
                                . '</strong>
                                has created a new post for release. Please review.
                            </p>

                            <p>
                                <strong>Post:</strong>
                                '
                                . htmlspecialchars($title, ENT_QUOTES, 'UTF-8')
                                . '
                            </p>

                            <p>
                                <a href="edit-post.php?id='
                                . (int)$newPostId
                                . '">
                                    Review this post
                                </a>
                            </p>
                        ';

                        $messageStmt = $pdo->prepare("
                            INSERT INTO messages
                            (
                                sender_id,
                                recipient_id,
                                subject,
                                body,
                                parent_message_id,
                                sent_at,
                                is_read
                            )
                            VALUES (?, ?, ?, ?, NULL, NOW(), 0)
                        ");

                        foreach ($adminUsers as $adminUserId) {

                            $messageStmt->execute([
                                $systemSenderId,
                                $adminUserId,
                                $messageSubject,
                                $messageBody
                            ]);
                        }
                    }
                }

                // ----------------------
                // SUCCESS MESSAGE
                // ----------------------

                if ($status === 'draft') {

                    $success = 'Draft saved successfully!';

                } elseif ($status === 'pending') {

                    $success = 'Post submitted for review. An editor has been notified.';

                } elseif ($status === 'scheduled') {

                    $success = 'Post scheduled successfully!';

                    if (!empty($scheduled_at)) {
                        $success .= '<br>Scheduled for: '
                            . htmlspecialchars($scheduled_at, ENT_QUOTES, 'UTF-8');
                    }

                } else {

                    $success = 'Post published successfully!';
                }

                if ($status === 'published') {

                    $success .= '
                        <br>
                        <a href="/'
                        . htmlspecialchars($post_location, ENT_QUOTES, 'UTF-8')
                        . '/'
                        . htmlspecialchars($slug, ENT_QUOTES, 'UTF-8')
                        . '" target="_blank">
                            View Post
                        </a>
                    ';
                }

                if ($imagePath) {

                    $success .= '
                        <br>
                        <img
                            src="/'
                            . htmlspecialchars($imagePath, ENT_QUOTES, 'UTF-8')
                            . '"
                            alt="Featured Image"
                            style="max-width:300px;margin-top:10px;"
                        >
                    ';
                }

                // Clear form values
                $title = '';
                $slug = '';
                $tagline = '';
                $meta_description = '';
                $content = '';
                $tags = '';
                $post_location = '';
                $scheduled_at = '';
                $featured = false;
            }

        } catch (PDOException $e) {

            $error = 'Database error: '
                . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
        }
    }
}
?>


<link rel="stylesheet" href="assets/css/posts.css">

    <div class="mb-2">
        <h1>Add New Post</h1>

</div>

<?php if ($error): ?>
    <div class="alert alert-danger">
        <?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?>
    </div>
<?php endif; ?>

<?php if ($success): ?>
    <div class="alert alert-success">
        <?= $success ?>
    </div>
<?php endif; ?>

<form method="post" id="postForm" class="post-editor-form" enctype="multipart/form-data">

    <div class="post-editor-grid">

        <div class="post-editor-main">

            <section class="post-editor-card">

                <div class="post-editor-section-heading">
                    <h2>Post details</h2>
                    <p>Start with the title, URL slug and search summary.</p>
                </div>

    <div class="mb-3">
        <label for="title" class="form-label">Title *</label>

        <input
            type="text"
            id="title"
            name="title"
            class="form-control"
            required
            value="<?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?>"
        >
    </div>

    <div class="mb-3">
        <label for="slug" class="form-label">Slug *</label>

        <input
            type="text"
            id="slug"
            name="slug"
            class="form-control"
            required
            value="<?= htmlspecialchars($slug, ENT_QUOTES, 'UTF-8') ?>"
            placeholder="example-post-url"
        >

        <div class="form-text">
            This will be used in the post URL. You can edit it before saving.
            <span id="slugStatus"></span>
        </div>
    </div>

    <div class="mb-3">
        <label for="tagline" class="form-label">Tagline</label>

        <input
            type="text"
            id="tagline"
            name="tagline"
            class="form-control"
            value="<?= htmlspecialchars($tagline, ENT_QUOTES, 'UTF-8') ?>"
        >
    </div>

    <div class="mb-3">
        <label for="meta_description" class="form-label">
            Meta Description
        </label>

        <textarea
            id="meta_description"
            name="meta_description"
            class="form-control"
            rows="3"
            maxlength="160"
            placeholder="Short summary for Google search results."
        ><?= htmlspecialchars($meta_description, ENT_QUOTES, 'UTF-8') ?></textarea>

        <div class="form-text">
            Recommended for SEO.
            <span id="metaDescriptionCount">0</span>/160
        </div>
    </div>

            </section>

            <section class="post-editor-card post-editor-card-large">

                <div class="post-editor-section-heading">
                    <h2>Article content</h2>
                    <p>Write the main article body. The editor height is fixed so the page stays manageable.</p>
                </div>

    <div class="mb-3">
        <label for="content" class="form-label">Content *</label>

        <textarea
            id="content"
            name="content"
            class="form-control"
        ><?= htmlspecialchars($content, ENT_QUOTES, 'UTF-8') ?></textarea>
    </div>

            </section>

            <!-- MEDIA BANK -->

            <section class="post-editor-card">

                <div class="post-editor-section-heading">
                    <h2>Media bank</h2>
                    <p>Copy an existing media URL if you want to use an uploaded image in the article body.</p>
                </div>

    <div class="accordion mb-0" id="mediaBankAccordion">

        <div class="accordion-item">

            <h2 class="accordion-header">

                <button
                    class="accordion-button collapsed"
                    type="button"
                    data-bs-toggle="collapse"
                    data-bs-target="#mediaBankCollapse"
                    aria-expanded="false"
                >
                    Media Bank
                </button>

            </h2>

            <div
                id="mediaBankCollapse"
                class="accordion-collapse collapse"
            >

                <div class="accordion-body">

                    <?php if (empty($mediaFiles)): ?>

                        <div class="alert alert-secondary mb-0">
                            No uploaded media found.
                        </div>

                    <?php else: ?>

                        <div class="row g-3 media-bank-grid">

                            <?php foreach ($mediaFiles as $media): ?>

                                <div class="col-xl-2 col-lg-3 col-md-4 col-6">

                                    <div class="card media-bank-card h-100">

                                        <img
                                            src="<?= htmlspecialchars($media['url'], ENT_QUOTES, 'UTF-8') ?>"
                                            alt=""
                                        >

                                        <div class="card-body p-2">

                                            <input
                                                type="text"
                                                class="form-control form-control-sm media-bank-url mb-2"
                                                value="<?= htmlspecialchars($media['url'], ENT_QUOTES, 'UTF-8') ?>"
                                                readonly
                                            >

                                            <button
                                                type="button"
                                                class="btn btn-outline-primary btn-sm w-100"
                                                onclick="copyMediaUrl('<?= htmlspecialchars($media['url'], ENT_QUOTES, 'UTF-8') ?>')"
                                            >
                                                Copy URL
                                            </button>

                                        </div>

                                    </div>

                                </div>

                            <?php endforeach; ?>

                        </div>

                    <?php endif; ?>

                </div>

            </div>

        </div>

    </div>

            </section>

        </div>

        <aside class="post-editor-sidebar">

            <section class="post-editor-card">

                <div class="post-editor-section-heading">
                    <h2>Post settings</h2>
                    <p>Set the type, tags and featured image.</p>
                </div>

    <div class="mb-3 form-check">

        <input
            type="checkbox"
            id="featured"
            name="featured"
            value="1"
            class="form-check-input"
            <?= $featured ? 'checked' : '' ?>
        >

        <label for="featured" class="form-check-label">
            Featured?
        </label>

    </div>

    <div class="mb-3">
        <label for="tags" class="form-label">
            Tags (comma separated)
        </label>

        <input
            type="text"
            id="tags"
            name="tags"
            class="form-control"
            value="<?= htmlspecialchars($tags, ENT_QUOTES, 'UTF-8') ?>"
        >
    </div>

    <div class="mb-3">
        <label for="post_location" class="form-label">
            Post Location *
        </label>

        <select
            id="post_location"
            name="post_location"
            class="form-select"
            required
        >

            <option value="">Select location</option>

            <?php foreach ($postLocations as $key => $label): ?>

                <option
                    value="<?= htmlspecialchars($key, ENT_QUOTES, 'UTF-8') ?>"
                    <?= ($post_location === $key) ? 'selected' : '' ?>
                >
                    <?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?>
                </option>

            <?php endforeach; ?>

        </select>
    </div>

    <div class="mb-3">
        <label for="image" class="form-label">
            Featured Image
        </label>

        <input
            type="file"
            id="image"
            name="image"
            class="form-control"
            accept="image/*"
        >
    </div>

    <?php if ($canPublishDirectly): ?>

        <div class="mb-3">
            <label for="scheduled_at" class="form-label">
                Schedule publish date/time
            </label>

            <input
                type="datetime-local"
                id="scheduled_at"
                name="scheduled_at"
                class="form-control"
                value="<?= htmlspecialchars((string)$scheduled_at, ENT_QUOTES, 'UTF-8') ?>"
            >

            <div class="form-text">
                Only needed if you use Schedule Post.
            </div>
        </div>

    <?php endif; ?>

            </section>

            <section class="post-editor-card post-editor-actions">

                <div class="post-editor-section-heading">
                    <h2>Save options</h2>
                    <p>Drafts stay private. Publishing may submit for review depending on your role.</p>
                </div>

    <!-- BUTTONS -->

    <div class="d-flex gap-2 flex-wrap">

        <button
            type="submit"
            name="status"
            value="draft"
            class="btn btn-outline-secondary"
        >
            Save Draft
        </button>

        <button
            type="submit"
            name="status"
            value="published"
            class="btn btn-primary"
        >
            <?= $canPublishDirectly ? 'Publish Post' : 'Submit for Review' ?>
        </button>

        <?php if ($canPublishDirectly): ?>

            <button
                type="submit"
                name="status"
                value="scheduled"
                class="btn btn-warning"
            >
                Schedule Post
            </button>

        <?php endif; ?>

    </div>

            </section>

        </aside>

    </div>

</form>

<script src="https://cdn.tiny.cloud/1/w4vz3wunp3pewnc7bavv3u16ollglu4nimw1v7tfm35g302r/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>

<script>
tinymce.init({
    selector: '#content',
    height: 400,
    menubar: false,

    plugins: 'lists link image table emoticons hr code fullscreen preview wordcount',

    toolbar: 'undo redo | blocks | bold italic underline | fontsize | forecolor backcolor | bullist numlist | link image | emoticons | hr | removeformat | alignleft aligncenter alignright alignjustify | code preview fullscreen',

    branding: false,

    block_formats: 'Paragraph=p; Heading 2=h2; Heading 3=h3; Heading 4=h4',

    font_size_formats: '12px 14px 16px 18px 22px 26px 32px',

    link_default_target: '_blank',

    link_title: false,

    image_title: true,

    automatic_uploads: true,

    forced_root_block: 'p',


    content_style: `
      body {
        font-family: Arial, sans-serif;
        font-size: 16px;
        line-height: 1.6;
        padding: 10px;
      }

      h2 {
        font-size: 28px;
        margin: 24px 0 12px;
        font-weight: 700;
      }

      h3 {
        font-size: 22px;
        margin: 20px 0 10px;
        font-weight: 700;
      }

      h4 {
        font-size: 18px;
        margin: 16px 0 8px;
        font-weight: 700;
      }

      hr {
        border: none;
        height: 2px;
        background: #898E7D;
        margin: 20px 0;
      }
    `
});

const metaDescription = document.getElementById('meta_description');
const metaDescriptionCount = document.getElementById('metaDescriptionCount');

const titleInput = document.getElementById('title');
const slugInput = document.getElementById('slug');
const slugStatus = document.getElementById('slugStatus');
const scheduledAtInput = document.getElementById('scheduled_at');

let slugManuallyEdited = slugInput && slugInput.value.trim() !== '';
let slugIsValid = false;

function updateMetaDescriptionCount() {

    if (!metaDescription || !metaDescriptionCount) {
        return;
    }

    metaDescriptionCount.textContent = metaDescription.value.length;
}

function copyMediaUrl(url) {

    navigator.clipboard.writeText(url);

    alert('Copied!');
}

function generateSlugFromText(text) {

    return text
        .toString()
        .toLowerCase()
        .trim()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-+|-+$/g, '');
}

function setSlugStatus(message, type) {

    if (!slugStatus) {
        return;
    }

    slugStatus.textContent = message ? ' ' + message : '';

    slugStatus.classList.remove(
        'text-success',
        'text-danger',
        'text-muted',
        'fw-bold'
    );

    if (type === 'success') {
        slugStatus.classList.add('text-success', 'fw-bold');
    } else if (type === 'danger') {
        slugStatus.classList.add('text-danger', 'fw-bold');
    } else {
        slugStatus.classList.add('text-muted');
    }
}

async function checkSlug() {

    if (!slugInput) {
        return;
    }

    const cleanedSlug = generateSlugFromText(slugInput.value);

    slugInput.value = cleanedSlug;

    if (!cleanedSlug) {
        slugIsValid = false;
        setSlugStatus('Slug is required.', 'danger');
        return;
    }

    setSlugStatus('Checking...', 'muted');

    try {

        const response = await fetch(
            '?ajax=check_slug&slug=' + encodeURIComponent(cleanedSlug),
            {
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            }
        );

        const data = await response.json();

        slugInput.value = data.slug || cleanedSlug;
        slugIsValid = !!data.valid;

        setSlugStatus(
            data.message || 'Could not check slug.',
            data.valid ? 'success' : 'danger'
        );

    } catch (error) {

        slugIsValid = false;
        setSlugStatus('Could not check slug.', 'danger');
    }
}

if (metaDescription) {

    updateMetaDescriptionCount();

    metaDescription.addEventListener(
        'input',
        updateMetaDescriptionCount
    );
}

if (titleInput && slugInput) {

    titleInput.addEventListener('input', function() {

        if (slugManuallyEdited) {
            return;
        }

        slugInput.value = generateSlugFromText(titleInput.value);
        slugIsValid = false;

        if (slugInput.value) {
            setSlugStatus(
                'Suggested slug',
                'muted'
            );
        } else {
            setSlugStatus('', 'muted');
        }
    });

    titleInput.addEventListener('blur', function() {

        if (slugManuallyEdited) {
            return;
        }

        slugInput.value = generateSlugFromText(titleInput.value);

        if (slugInput.value) {
            checkSlug();
        }
    });

    slugInput.addEventListener('input', function() {

        slugManuallyEdited = true;
        slugIsValid = false;

        setSlugStatus(
            'Click out to check availability.',
            'muted'
        );
    });

    slugInput.addEventListener('blur', checkSlug);
}

document
    .getElementById('postForm')
    .addEventListener('submit', function(e) {

        const clickedButton = e.submitter;
        const requestedStatus = clickedButton ? clickedButton.value : '';

        if (slugInput) {

            const cleanedSlug = generateSlugFromText(slugInput.value);

            slugInput.value = cleanedSlug;

            if (!cleanedSlug) {

                alert('Slug is required.');

                slugInput.focus();

                e.preventDefault();

                return;
            }

            if (!slugIsValid) {

                alert(
                    'Please click out of the slug field and make sure the slug is available before saving.'
                );

                slugInput.focus();

                e.preventDefault();

                return;
            }
        }

        const contentText = tinymce
            .get('content')
            .getContent({ format: 'text' })
            .trim();

        if (!contentText) {

            alert('Content is required.');

            tinymce.get('content').focus();

            e.preventDefault();

            return;
        }

        if (
            metaDescription &&
            metaDescription.value.length > 160
        ) {

            alert(
                'Meta description must be 160 characters or fewer.'
            );

            metaDescription.focus();

            e.preventDefault();

            return;
        }

        if (
            requestedStatus === 'scheduled' &&
            scheduledAtInput &&
            scheduledAtInput.value.trim() === ''
        ) {

            alert('Please choose a date and time to schedule this post.');

            scheduledAtInput.focus();

            e.preventDefault();

            return;
        }
    });
</script>