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

requireLogin();

$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 = $_SESSION['user_id']; // Default to current user
        $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));

        $pdo = getDB();

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

        $stmt = $pdo->prepare("INSERT INTO posts (title, slug, content, excerpt, category_id, author_id, manual_author_name, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");

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

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

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

<?php if ($success): ?>
    <div class="alert alert-success">
        <?php echo htmlspecialchars($success); ?>
    </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 echo htmlspecialchars($_POST['author_name'] ?? ''); ?></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">Create Post</button>
        <a href="posts.php" class="btn btn-secondary">Cancel</a>
    </div>
</form>

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