<?php
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

if (!$auth->hasPermission('can_create') && !$auth->hasPermission('can_edit') && !$auth->hasRole('super_admin')) {
    $_SESSION['error'] = "You don't have permission";
    header('Location: dashboard.php');
    exit;
}

$current_user = $auth->getCurrentUser();
$is_edit = isset($_GET['id']);
$post = null;

if ($is_edit) {
    $id = (int)$_GET['id'];
    $post = $db->fetchOne("SELECT * FROM blog_posts WHERE id = ?", [$id]);
    if (!$post) {
        $_SESSION['error'] = "Post not found";
        header('Location: blog.php');
        exit;
    }
    $page_title = 'Edit Post';
} else {
    $page_title = 'New Post';
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    $title = trim($_POST['title']);
    $content = trim($_POST['content']);
    $excerpt = trim($_POST['excerpt']);
    $category = trim($_POST['category']);
    $tags = isset($_POST['tags']) ? array_filter(array_map('trim', explode(',', $_POST['tags']))) : [];
    $status = $_POST['status'];
    $meta_title = trim($_POST['meta_title']);
    $meta_description = trim($_POST['meta_description']);
    
    if (empty($title)) $errors[] = "Title is required";
    if (empty($content)) $errors[] = "Content is required";
    
    // Handle featured image
    $featured_image = $post['featured_image'] ?? '';
    
    if (!empty($_FILES['featured_image']['name'])) {
        $file = $_FILES['featured_image'];
        if ($file['error'] === UPLOAD_ERR_OK) {
            if (in_array($file['type'], ALLOWED_IMAGE_TYPES) && $file['size'] <= MAX_FILE_SIZE) {
                $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                $filename = 'blog_' . uniqid() . '_' . time() . '.' . $extension;
                $upload_path = BLOG_UPLOAD_DIR . '/' . $filename;
                
                if (move_uploaded_file($file['tmp_name'], $upload_path)) {
                    $featured_image = 'uploads/blog/' . $filename;
                    
                    // Delete old image
                    if ($is_edit && $post['featured_image']) {
                        $old_file = BLOG_UPLOAD_DIR . '/' . basename($post['featured_image']);
                        if (file_exists($old_file)) unlink($old_file);
                    }
                }
            }
        }
    }
    
    if (empty($errors)) {
        try {
            $slug = Security::generateSlug($title);
            $slug_check = $db->fetchOne("SELECT id FROM blog_posts WHERE slug = ? AND id != ?", [$slug, $id ?? 0]);
            if ($slug_check) $slug .= '-' . time();
            
            $published_at = ($status === 'published' && !$is_edit) ? date('Y-m-d H:i:s') : 
                           (($status === 'published' && $post['published_at']) ? $post['published_at'] : null);
            
            if ($is_edit) {
                $sql = "UPDATE blog_posts SET 
                        title = ?, slug = ?, content = ?, excerpt = ?,
                        featured_image = ?, category = ?, tags = ?,
                        status = ?, published_at = ?, meta_title = ?,
                        meta_description = ?, updated_at = NOW()
                        WHERE id = ?";
                
                $db->execute($sql, [
                    $title, $slug, $content, $excerpt,
                    $featured_image, $category, json_encode($tags),
                    $status, $published_at, $meta_title,
                    $meta_description, $id
                ]);
                
                $_SESSION['success'] = "Post updated successfully";
            } else {
                $sql = "INSERT INTO blog_posts (
                        title, slug, content, excerpt, featured_image,
                        category, tags, author_id, status, published_at,
                        meta_title, meta_description
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                
                $db->execute($sql, [
                    $title, $slug, $content, $excerpt, $featured_image,
                    $category, json_encode($tags), $current_user['id'],
                    $status, $published_at, $meta_title, $meta_description
                ]);
                
                $_SESSION['success'] = "Post created successfully";
            }
            
            header('Location: blog.php');
            exit;
        } catch (Exception $e) {
            $errors[] = "Error: " . $e->getMessage();
        }
    }
}

include 'includes/header.php';
?>

<div class="page-header">
    <h1><?php echo $page_title; ?></h1>
</div>

<?php if (!empty($errors)): ?>
<div class="alert alert-danger">
    <ul class="mb-0">
        <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
        <?php endforeach; ?>
    </ul>
</div>
<?php endif; ?>

<form method="POST" enctype="multipart/form-data">
    <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
    
    <div class="row">
        <div class="col-lg-8">
            <div class="card mb-4">
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Title <span class="text-danger">*</span></label>
                        <input type="text" name="title" class="form-control" required
                               value="<?php echo htmlspecialchars($post['title'] ?? ''); ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Content <span class="text-danger">*</span></label>
                        <textarea name="content" class="form-control" rows="15" required><?php echo htmlspecialchars($post['content'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Excerpt</label>
                        <textarea name="excerpt" class="form-control" rows="3"><?php echo htmlspecialchars($post['excerpt'] ?? ''); ?></textarea>
                    </div>
                </div>
            </div>
            
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">SEO Settings</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Meta Title</label>
                        <input type="text" name="meta_title" class="form-control"
                               value="<?php echo htmlspecialchars($post['meta_title'] ?? ''); ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Meta Description</label>
                        <textarea name="meta_description" class="form-control" rows="2"><?php echo htmlspecialchars($post['meta_description'] ?? ''); ?></textarea>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Publish</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="draft" <?php echo ($post['status'] ?? 'draft') === 'draft' ? 'selected' : ''; ?>>Draft</option>
                            <option value="published" <?php echo ($post['status'] ?? '') === 'published' ? 'selected' : ''; ?>>Published</option>
                            <option value="archived" <?php echo ($post['status'] ?? '') === 'archived' ? 'selected' : ''; ?>>Archived</option>
                        </select>
                    </div>
                    
                    <button type="submit" name="submit" class="btn btn-primary w-100">
                        <i class="fas fa-save"></i> <?php echo $is_edit ? 'Update' : 'Publish'; ?>
                    </button>
                    
                    <a href="blog.php" class="btn btn-outline-secondary w-100 mt-2">
                        <i class="fas fa-times"></i> Cancel
                    </a>
                </div>
            </div>
            
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Featured Image</h5>
                </div>
                <div class="card-body">
                    <?php if ($is_edit && $post['featured_image']): ?>
                    <img src="../<?php echo htmlspecialchars($post['featured_image']); ?>" 
                         class="img-fluid mb-3" alt="Featured">
                    <?php endif; ?>
                    <input type="file" name="featured_image" class="form-control" accept="image/*">
                </div>
            </div>
            
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Categories & Tags</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Category</label>
                        <input type="text" name="category" class="form-control"
                               value="<?php echo htmlspecialchars($post['category'] ?? ''); ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Tags (comma separated)</label>
                        <input type="text" name="tags" class="form-control"
                               value="<?php echo htmlspecialchars(implode(', ', json_decode($post['tags'] ?? '[]', true))); ?>">
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

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