<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/layout.php';

$currentUserId = (int)($_SESSION['admin_user_id'] ?? 0);
$currentUserRole = $_SESSION['admin_role'] ?? '';

$error = '';
$success = '';
$post = null;

function generateSlug($string) {

    $string = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $string);

    $string = preg_replace(
        '/[’‘“”"\'!@#$%^&*()+=\[\]{}|\\\:;<>?,.~`]/u',
        '',
        $string
    );

    $string = preg_replace('/[‐-‒–—―]/u', ' ', $string);
    $string = preg_replace('/[^A-Za-z0-9 ]+/', '', $string);
    $string = preg_replace('/\s+/', '-', $string);

    return strtolower(trim($string, '-'));
}


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

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

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

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

$postLocations = [];

try {
    $stmtLocations = $pdo->query("
        SELECT key_name, label
        FROM post_locations
        ORDER BY label
    ");

    $postLocations = $stmtLocations->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die(
        "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'];
    });
}

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id <= 0) {
    die('Invalid post ID.');
}

try {
    $stmt = $pdo->prepare("
        SELECT *
        FROM posts
        WHERE id = ?
    ");

    $stmt->execute([$id]);
    $post = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$post) {
        die('Post not found.');
    }

} catch (PDOException $e) {
    die(
        "Database error: "
        . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8')
    );
}

$existingStatus = $post['status'] ?? 'draft';

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

$postOwnerId = (int)($post['created_by'] ?? 0);

$canDeletePost = $canPublishDirectly || $postOwnerId === $currentUserId;

$canScheduleThisPost = $canPublishDirectly
    && in_array($existingStatus, ['draft', 'pending', 'scheduled'], true);

// ----------------------
// DELETE POST
// ----------------------

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['delete_post'])
) {
    if (!$canDeletePost) {
        die('You do not have permission to delete this post.');
    }

    try {
        if (
            !empty($post['image_path']) &&
            file_exists(__DIR__ . '/../' . $post['image_path'])
        ) {
            unlink(__DIR__ . '/../' . $post['image_path']);
        }

        $deleteStmt = $pdo->prepare("
            DELETE FROM posts
            WHERE id = ?
        ");

        $deleteStmt->execute([$id]);

        header('Location: /admin/posts.php?deleted=1');
        exit;

    } catch (PDOException $e) {
        die(
            'Delete failed: '
            . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8')
        );
    }
}

// ----------------------
// UPDATE POST
// ----------------------

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    !isset($_POST['delete_post'])
) {
    $title = $_POST['title'] ?? '';
    $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';
    }

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

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

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

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

    if ($canPublishDirectly) {
        $status = $requestedStatus;
    } else {
        if ($existingStatus === 'published') {
            $status = 'published';
        } elseif ($existingStatus === 'scheduled') {
            $status = 'scheduled';
        } elseif ($existingStatus === 'pending') {
            $status = 'pending';
        } elseif (
            $existingStatus === 'draft' &&
            $requestedStatus === 'published'
        ) {
            $status = 'pending';
        } else {
            $status = 'draft';
        }
    }

    if ($requestedStatus === 'scheduled') {
        if ($canScheduleThisPost) {
            $status = 'scheduled';
        } else {
            $status = $existingStatus;
            $scheduled_at = null;
        }
    }

    if ($status !== 'scheduled') {
        $scheduled_at = null;
    }

    $imagePath = $post['image_path'] ?? null;

    // ----------------------
    // VALIDATION
    // ----------------------

    if (
        trim($title) === '' ||
        trim(strip_tags($content)) === '' ||
        $post_location === ''
    ) {
        $error = 'Please fill in all required fields.';

    } 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 {
            // ----------------------
            // IMAGE UPLOAD
            // ----------------------

            if (
                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)) {
                        if (
                            !empty($post['image_path']) &&
                            file_exists(__DIR__ . '/../' . $post['image_path'])
                        ) {
                            unlink(__DIR__ . '/../' . $post['image_path']);
                        }

                        $imagePath = 'uploads/' . $newFileName;

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

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

            // ----------------------
            // UPDATE
            // ----------------------

            if (!$error) {
                $slug = generateSlug($title);

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

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

                if ($checkStmt->fetchColumn() > 0) {
                    $slug .= '-' . time();
                }

                $stmtUpdate = $pdo->prepare("
                    UPDATE posts
                    SET
                        title = ?,
                        tagline = ?,
                        meta_description = ?,
                        slug = ?,
                        content = ?,
                        tags = ?,
                        post_location = ?,
                        featured = ?,
                        image_path = ?,
                        status = ?,
                        scheduled_at = ?,
                        updated_at = CASE
                            WHEN created_at IS NOT NULL
                             AND updated_at IS NOT NULL
                             AND updated_at <> created_at
                            THEN NOW()
                            ELSE updated_at
                        END
                    WHERE id = ?
                ");

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

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

                if ($status === 'draft') {
                    $success = 'Draft updated successfully!';
                } elseif ($status === 'pending') {
                    $success = 'Post updated and remains pending review.';
                } elseif ($status === 'scheduled') {
                    $success = 'Post scheduled successfully!';
                } else {
                    $success = 'Post updated successfully!';
                }

                $post = [
                    'id' => $id,
                    'title' => $title,
                    'tagline' => $tagline,
                    'meta_description' => $meta_description,
                    'slug' => $slug,
                    'content' => $content,
                    'tags' => $tags,
                    'post_location' => $post_location,
                    'featured' => $featured,
                    'image_path' => $imagePath,
                    'status' => $status,
                    'scheduled_at' => $scheduled_at,
                    'created_by' => $postOwnerId
                ];

                $existingStatus = $status;

                $canScheduleThisPost = $canPublishDirectly
                    && in_array($existingStatus, ['pending', 'scheduled'], true);
            }

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

$scheduledInputValue = '';

if (!empty($post['scheduled_at'])) {
    $scheduledInputValue = date(
        'Y-m-d\TH:i',
        strtotime($post['scheduled_at'])
    );
}
?>

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

    <div class='mb-2'>
        <h1>Edit Post</h1>
    </div>

<?php if (!empty($post['status'])): ?>

<div class="mb-3">

    <?php if ($post['status'] === 'draft'): ?>

        <span class="badge bg-warning text-dark">
            Draft
        </span>

    <?php elseif ($post['status'] === 'pending'): ?>

        <span class="badge bg-info text-dark">
            Pending Review
        </span>

    <?php elseif ($post['status'] === 'scheduled'): ?>

        <span class="badge bg-warning text-dark">
            Scheduled
        </span>

        <?php if (!empty($post['scheduled_at'])): ?>
            <div class="form-text mt-1">
                Scheduled for:
                <?= htmlspecialchars($post['scheduled_at'], ENT_QUOTES, 'UTF-8') ?>
            </div>
        <?php endif; ?>

    <?php elseif ($post['status'] === 'published'): ?>

        <span class="badge bg-success">
            Published
        </span>

    <?php else: ?>

        <span class="badge bg-secondary">
            <?= htmlspecialchars(ucfirst($post['status']), ENT_QUOTES, 'UTF-8') ?>
        </span>

    <?php endif; ?>

</div>

<?php endif; ?>

<?php if (($post['status'] ?? '') === 'pending'): ?>

    <div class="alert alert-info">
        This post is currently pending review.
        <?php if ($canPublishDirectly): ?>
            You can approve and publish it, or schedule it using the buttons below.
        <?php endif; ?>
    </div>

<?php endif; ?>

<?php if (($post['status'] ?? '') === 'scheduled'): ?>

    <div class="alert alert-warning">
        This post is scheduled.
        <?php if ($canPublishDirectly): ?>
            You can update the scheduled time or publish it now.
        <?php endif; ?>
    </div>

<?php endif; ?>

<?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">

    <?= htmlspecialchars($success, ENT_QUOTES, 'UTF-8') ?>

    <?php if (($post['status'] ?? '') === 'published'): ?>

        <br>

        <a
            href="/<?= htmlspecialchars($post['post_location'], ENT_QUOTES, 'UTF-8') ?>/<?= htmlspecialchars($post['slug'], ENT_QUOTES, 'UTF-8') ?>"
            target="_blank"
        >
            View Post
        </a>

    <?php endif; ?>

    <?php if (!empty($post['image_path'])): ?>

        <br>

        <img
            src="/<?= htmlspecialchars($post['image_path'], ENT_QUOTES, 'UTF-8') ?>"
            alt="Post Image"
            style="display:block;max-width:100%;height:auto;margin-top:10px;border-radius:10px;"
        >

    <?php endif; ?>

</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>Update the title, tagline 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($post['title'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                    >
                </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($post['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($post['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>Edit 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($post['content'] ?? '', ENT_QUOTES, 'UTF-8') ?></textarea>
                </div>

            </section>

            <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"
                                aria-controls="mediaBankCollapse"
                            >
                                Media Bank
                            </button>

                        </h2>

                        <div
                            id="mediaBankCollapse"
                            class="accordion-collapse collapse"
                            data-bs-parent="#mediaBankAccordion"
                        >

                            <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"
                        <?= !empty($post['featured']) ? 'checked' : '' ?>
                    >

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

                </div>

                <div class="mb-3">
                    <label for="tags" class="form-label">
                        Tags
                    </label>

                    <input
                        type="text"
                        id="tags"
                        name="tags"
                        class="form-control"
                        value="<?= htmlspecialchars($post['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 $location): ?>

                            <option
                                value="<?= htmlspecialchars($location['key_name'], ENT_QUOTES, 'UTF-8') ?>"
                                <?= ($post['post_location'] ?? '') === $location['key_name'] ? 'selected' : '' ?>
                            >
                                <?= htmlspecialchars($location['label'], ENT_QUOTES, 'UTF-8') ?>
                            </option>

                        <?php endforeach; ?>

                    </select>
                </div>

                <?php if ($canScheduleThisPost): ?>

                    <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($scheduledInputValue, ENT_QUOTES, 'UTF-8') ?>"
                        >

                        <div class="form-text">
                            Draft, pending or scheduled posts can be scheduled. Published posts cannot be scheduled again.
                        </div>

                    </div>

                <?php endif; ?>

                <div class="mb-3">

                    <label for="image" class="form-label">
                        Replace Featured Image
                    </label>

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

                    <?php if (!empty($post['image_path'])): ?>

                        <div class="mt-3">

                            <strong>Current image:</strong>

                            <img
                                src="/<?= htmlspecialchars($post['image_path'], ENT_QUOTES, 'UTF-8') ?>"
                                alt="Current Image"
                                style="display:block;width:100%;max-width:100%;height:auto;margin-top:0.5rem;border-radius:10px;"
                            >

                        </div>

                    <?php endif; ?>

                </div>

            </section>

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

                <div class="post-editor-section-heading">
                    <h2>Save options</h2>
                    <p>Choose how this update should be handled.</p>
                </div>

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

                    <?php if (
                        $canPublishDirectly ||
                        ($post['status'] ?? '') === 'draft'
                    ): ?>

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

                    <?php endif; ?>

                    <button
                        type="submit"
                        name="status"
                        value="published"
                        class="btn btn-primary"
                    >
                        <?php if ($canPublishDirectly): ?>

                            <?php if (($post['status'] ?? '') === 'pending'): ?>
                                Approve and Publish
                            <?php elseif (($post['status'] ?? '') === 'scheduled'): ?>
                                Publish Now
                            <?php elseif (($post['status'] ?? '') === 'published'): ?>
                                Update Post
                            <?php else: ?>
                                Publish Post
                            <?php endif; ?>

                        <?php else: ?>

                            <?php if (($post['status'] ?? '') === 'published'): ?>
                                Update Post
                            <?php else: ?>
                                Submit for Review
                            <?php endif; ?>

                        <?php endif; ?>
                    </button>

                    <?php if ($canScheduleThisPost): ?>

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

                    <?php endif; ?>

                    <?php if ($canDeletePost): ?>

                        <button
                            type="submit"
                            name="delete_post"
                            value="1"
                            class="btn btn-danger"
                            formnovalidate
                            onclick="return confirm('Are you sure you want to delete this post? This cannot be undone.')"
                        >
                            Delete 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 scheduledAtInput = document.getElementById('scheduled_at');

function updateMetaDescriptionCount() {

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

    metaDescriptionCount.textContent = metaDescription.value.length;
}

function copyMediaUrl(url) {

    navigator.clipboard.writeText(url);

    alert('Copied!');
}

if (metaDescription) {

    updateMetaDescriptionCount();

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

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

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

        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>
