<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/layout.php';
$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, '-'));
}

$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')
    );
}

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

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['delete_post'])
) {

    // Permission check
    if (!in_array($currentUserRole, ['Admin', 'Editor'], true)) {

        die('You do not have permission to delete posts.');
    }

    try {

        // Delete image if exists
        if (
            !empty($post['image_path']) &&
            file_exists(__DIR__ . '/../' . $post['image_path'])
        ) {

            unlink(__DIR__ . '/../' . $post['image_path']);
        }

        // Delete post
        $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'] ?? '';

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

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

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

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

    $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.';

    } 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 (
                            $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);

                // Ensure unique slug
                $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 = ?,
                        updated_at = NOW()
                    WHERE id = ?
                ");

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

                $success = $status === 'draft'
                    ? 'Draft updated successfully!'
                    : 'Post published successfully!';

                // Refresh local post array
                $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
                ];
            }

        } catch (PDOException $e) {

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

<style>

.media-bank-grid {
    max-height: 500px;
    overflow-y: auto;
}

.media-bank-card img {
    width: 100%;
    height: 120px;
    object-fit: cover;
}

.media-bank-url {
    font-size: 11px;
}

</style>

<h1>Edit Post</h1>

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

<div class="mb-3">

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

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

    <?php else: ?>

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

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

    <?= $success ?>

    <br>

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

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

        <br>

        <img
            src="/<?= htmlspecialchars($post['image_path'], ENT_QUOTES, 'UTF-8') ?>"
            alt="Post Image"
            style="max-width:300px;margin-top:10px;"
        >

    <?php endif; ?>

</div>

<?php endif; ?>

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

    <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"
        ><?= htmlspecialchars($post['meta_description'] ?? '', ENT_QUOTES, 'UTF-8') ?></textarea>

        <div class="form-text">
            <span id="metaDescriptionCount">0</span>/160
        </div>

    </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>

    <!-- MEDIA BANK -->

    <div class="accordion mb-4" 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>

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

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

                <strong>Current:</strong>

                <br>

                <img
                    src="/<?= htmlspecialchars($post['image_path'], ENT_QUOTES, 'UTF-8') ?>"
                    alt="Current Image"
                    style="max-width:200px;"
                >

            </div>

        <?php endif; ?>

    </div>

    <!-- BUTTONS -->

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

        <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"
        >
            Publish Post
        </button>

<?php if (in_array($currentUserRole, ['Admin', 'Editor'], true)): ?>

    <button
        type="submit"
        name="delete_post"
        value="1"
        class="btn btn-danger ms-auto"
        formnovalidate
        onclick="return confirm('Are you sure you want to delete this post? This cannot be undone.')"
    >
        Delete Post
    </button>

<?php endif; ?>

    </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 autoresize',

    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',
    autoresize_bottom_margin: 20,

    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');

  function updateMetaDescriptionCount() {
    if (!metaDescription || !metaDescriptionCount) return;
    metaDescriptionCount.textContent = metaDescription.value.length;
  }

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

  function copyMediaUrl(url) {
    navigator.clipboard.writeText(url);
    alert('Copied!');
  }

  document.getElementById('postForm').addEventListener('submit', function(e) {
    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();
    }
  });
</script>