<?php
session_start();
include '../config.php';
include 'auth_check.php';

// Auth Check handled by auth_check.php

// Ensure User ID is set (fix for sessions started before update)
if (!isset($_SESSION['user_id'])) {
    $email = $_SESSION['admin_email'];
    $u_res = $conn->query("SELECT id FROM users WHERE email = '$email'");
    if ($u_res && $row = $u_res->fetch_assoc()) {
        $_SESSION['user_id'] = $row['id'];
    }
}
$user_id = $_SESSION['user_id'];

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$content = null;
$error = null;
$success = null;

// Fetch Categories for Dropdown
$cats = [];
$cat_res = $conn->query("SELECT id, title FROM categories ORDER BY id");
if ($cat_res) {
    while ($c = $cat_res->fetch_assoc())
        $cats[] = $c;
}

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $category_id = intval($_POST['category_id']);
    $type = $_POST['type'];
    $title = trim($_POST['title']);
    $body = $_POST['body'];
    $status = $_POST['status'];

    if (empty($title) || empty($body)) {
        $error = "Title and Body are required.";
    } else {
        if ($id > 0) {
            // Update
            $stmt = $conn->prepare("UPDATE content SET category_id=?, type=?, title=?, body=?, status=? WHERE id=?");
            $stmt->bind_param("issssi", $category_id, $type, $title, $body, $status, $id);
            if ($stmt->execute()) {
                $success = "Content updated successfully.";
            } else {
                $error = "Error updating content: " . $conn->error;
            }
        } else {
            // Create
            $stmt = $conn->prepare("INSERT INTO content (user_id, category_id, type, title, body, status) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("iissss", $user_id, $category_id, $type, $title, $body, $status);
            if ($stmt->execute()) {
                $success = "Content created successfully.";
                $id = $stmt->insert_id;
            } else {
                $error = "Error creating content: " . $conn->error;
            }
        }
    }
}

// Fetch Content Data for Edit
if ($id > 0) {
    $stmt = $conn->prepare("SELECT * FROM content WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result();
    $content = $res->fetch_assoc();
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SaniBook Admin -
        <?php echo $id > 0 ? 'Edit' : 'Add'; ?> Content
    </title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <!-- TinyMCE Rich Text Editor -->
    <script src="https://cdn.tiny.cloud/1/99e5svnkqzxwfsazowd60xjihw1x523a9g247dn0ie4gdike/tinymce/6/tinymce.min.js"
        referrerpolicy="origin"></script>
    <style>
        .form-input {
            width: 100%;
            border: 1px solid #e2e8f0;
            border-radius: 0.5rem;
            padding: 0.5rem 1rem;
            outline: none;
            transition: border-color 0.2s;
        }

        .form-input:focus {
            border-color: #3b82f6;
            ring: 2px solid #93c5fd;
        }
    </style>
</head>

<body class="bg-slate-100 font-sans text-slate-900">

    <?php include 'navbar.php'; ?>

    <div class="max-w-4xl mx-auto p-6">
        <div class="flex items-center gap-4 mb-6">
            <a href="index.php" class="text-slate-500 hover:text-blue-600"><i class="fa-solid fa-arrow-left mr-1"></i>
                Back to Content</a>
            <h2 class="text-2xl font-bold text-slate-800">
                <?php echo $id > 0 ? 'Edit Content' : 'Add New Content'; ?>
            </h2>
        </div>

        <?php if ($error): ?>
            <div class="bg-red-100 text-red-700 p-4 rounded-lg mb-6 border border-red-200">
                <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="bg-green-100 text-green-700 p-4 rounded-lg mb-6 border border-green-200">
                <?php echo $success; ?>
            </div>
        <?php endif; ?>

        <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-8">
            <form method="POST" class="space-y-6">

                <div class="grid md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-2">Title</label>
                        <input type="text" name="title" required
                            value="<?php echo htmlspecialchars($content['title'] ?? ''); ?>" class="form-input">
                    </div>
                </div>

                <div class="grid md:grid-cols-3 gap-6">
                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-2">Category</label>
                        <select name="category_id" class="form-input bg-white" required>
                            <?php foreach ($cats as $c): ?>
                                <option value="<?php echo $c['id']; ?>" <?php echo ($content['category_id'] ?? '') == $c['id'] ? 'selected' : ''; ?>>
                                    <?php echo $c['id'] . '. ' . htmlspecialchars($c['title']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-2">Type</label>
                        <select name="type" class="form-input bg-white">
                            <option value="story" <?php echo ($content['type'] ?? '') === 'story' ? 'selected' : ''; ?>>
                                Data</option>
                            <option value="chronicle" <?php echo ($content['type'] ?? '') === 'chronicle' ? 'selected' : ''; ?>>Chronicle</option>
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-2">Status</label>
                        <select name="status" class="form-input bg-white">
                            <option value="pending" <?php echo ($content['status'] ?? '') === 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="approved" <?php echo ($content['status'] ?? '') === 'approved' ? 'selected' : ''; ?>>Approved</option>
                            <option value="rejected" <?php echo ($content['status'] ?? '') === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                        </select>
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Content Body</label>
                    <textarea name="body" id="body-editor" rows="15" class="form-input"
                        required><?php echo htmlspecialchars($content['body'] ?? ''); ?></textarea>
                    <p class="text-xs text-slate-500 mt-2">Use the toolbar above to format your content with bold,
                        bullets, links, and more.</p>
                </div>

                <div class="pt-4 flex justify-end">
                    <button type="submit"
                        class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-8 rounded-lg shadow-lg transition-all transform hover:scale-105">
                        <i class="fa-solid fa-save mr-2"></i> Save Content
                    </button>
                </div>

            </form>
        </div>
    </div>

    <script>
        tinymce.init({
            selector: '#body-editor',
            height: 400,
            menubar: false,
            plugins: 'lists link image code table wordcount',
            toolbar: 'undo redo | blocks | bold italic underline strikethrough | bullist numlist | link image | alignleft aligncenter alignright | code',
            content_style: 'body { font-family: Inter, sans-serif; font-size: 14px; }',
            branding: false,
            branding: false,
            promotion: false,
            // Force standard fonts
            invalid_styles: {
                '*': 'font-family font-size color background-color'
            },
            paste_as_text: false, // Allow bold/italic but strip styles
            paste_block_drop: false,
            paste_data_images: true,
            paste_webkit_styles: 'none', // Strip extra webkit styles on paste
            paste_retain_style_properties: 'none', // Don't keep any styles
            paste_word_valid_elements: 'b,strong,i,em,h1,h2,h3,h4,ul,li,ol,p,br', // Strict Word pasting rules
        });
    </script>
</body>

</html>
