<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../includes/functions.php';

requireLogin();

$id = $_GET['id'] ?? 0;
$pdo = getDB();

// Get post
$stmt = $pdo->prepare("SELECT * FROM posts WHERE id = ?");
$stmt->execute([$id]);
$post = $stmt->fetch();

if (!$post) {
    header('Location: posts.php');
    exit;
}

$categories = getCategories();
$users = getUsers();
$currentUser = getCurrentUser();
$isAdmin = ($currentUser['role'] === 'admin');
$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = trim($_POST['title'] ?? '');
    $content = $_POST['content'] ?? '';
    $category_id = $_POST['category_id'] ?? '';
    $status = $_POST['status'] ?? 'draft';

    // Handle image upload
    if (isset($_FILES['image']) && $_FILES['image']['error'] == UPLOAD_ERR_OK) {
        $uploadDir = '../assets/images/';
        $fileName = basename($_FILES['image']['name']);
        $fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
        $uniqueName = uniqid() . '.' . $fileExt;
        $uploadFile = $uploadDir . $uniqueName;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadFile)) {
            $imageTag = '<img src="assets/images/' . $uniqueName . '" alt="' . htmlspecialchars($fileName) . '" style="max-width:100%;">';
            $content = $imageTag . $content;
        }
    }

    if ($title && $content) {
        $slug = generateSlug($title);
        $author_name = trim($_POST['author_name'] ?? '');

        // Check if author name matches an existing user
        $author_id = $post['author_id']; // Default to existing author
        $manual_author_name = null;

        if ($author_name) {
            $userMatch = null;
            foreach ($users as $user) {
                if (strtolower($user['username']) === strtolower($author_name)) {
                    $userMatch = $user;
                    break;
                }
            }

            if ($userMatch) {
                $author_id = $userMatch['id'];
                $manual_author_name = null;
            } else {
                $manual_author_name = $author_name;
            }
        }

        $excerpt = truncateText(strip_tags($content));

        // Check if slug exists (excluding current post)
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM posts WHERE slug = ? AND id != ?");
        $stmt->execute([$slug, $id]);
        if ($stmt->fetchColumn() > 0) {
            $slug .= '-' . time();
        }

        $stmt = $pdo->prepare("UPDATE posts SET title = ?, slug = ?, content = ?, excerpt = ?, category_id = ?, author_id = ?, manual_author_name = ?, status = ? WHERE id = ?");

        if ($stmt->execute([$title, $slug, $content, $excerpt, $category_id, $author_id, $manual_author_name, $status, $id])) {
            header('Location: posts.php?updated=1');
            exit;
        } else {
            $error = 'Error updating post.';
        }
    } else {
        $error = 'Please fill in all required fields.';
    }
}

$page_title = 'Edit Post';
include 'includes/admin_header.php';
?>

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

<form method="POST" enctype="multipart/form-data" class="post-form">
    <div class="form-row">
        <div class="form-group">
            <label for="title">Title *</label>
            <textarea id="title" name="title" required rows="3" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors" placeholder="Enter post title"><?php echo htmlspecialchars($post['title']); ?></textarea>
        </div>
        
        <div class="form-group">
            <label for="category_id">Category</label>
            <select id="category_id" name="category_id" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors">
                <option value="">Select Category</option>
                <?php foreach ($categories as $category): ?>
                    <option value="<?php echo $category['id']; ?>" <?php echo $post['category_id'] == $category['id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($category['name']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="form-group">
            <label for="author_name">Author Name</label>
            <textarea id="author_name" name="author_name" rows="2" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors" placeholder="Enter author name"><?php
                $author_value = $_POST['author_name'] ?? ($post['manual_author_name'] ?: ($post['author_name'] ?? ''));
                echo htmlspecialchars($author_value);
            ?></textarea>
            <datalist id="authors-list">
                <?php foreach ($users as $user): ?>
                    <option value="<?php echo htmlspecialchars($user['username']); ?>">
                <?php endforeach; ?>
            </datalist>
            <small class="text-gray-500 mt-1 block">Start typing to see existing authors, or enter a new name</small>
        </div>
    </div>

    <div class="form-group">
        <label for="content">Content *</label>
        <textarea id="content" name="content" rows="15" required class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors" placeholder="Write your post content here..."><?php echo htmlspecialchars($post['content']); ?></textarea>
    </div>

    <div class="form-group">
        <label for="image">Upload Image</label>
        <input type="file" id="image" name="image" accept="image/*" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors bg-white">
        <small class="text-gray-500 mt-1 block">Upload an image to include in the post content.</small>
    </div>

    <div class="form-row">
        <div class="form-group">
            <label for="status">Status</label>
            <select id="status" name="status" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors">
                <option value="draft" <?php echo $post['status'] == 'draft' ? 'selected' : ''; ?>>Draft</option>
                <option value="published" <?php echo $post['status'] == 'published' ? 'selected' : ''; ?>>Published</option>
            </select>
        </div>
    </div>

    <div class="form-actions">
        <button type="submit" class="btn btn-primary">Update Post</button>
        <a href="posts.php" class="btn btn-secondary">Cancel</a>
        <?php if ($post['status'] == 'published'): ?>
            <a href="../post.php?slug=<?php echo urlencode($post['slug']); ?>" class="btn btn-outline" target="_blank">View Post</a>
        <?php endif; ?>
    </div>
</form>

<?php include 'includes/admin_footer.php'; ?>