<?php

// Define ACCESS constant for included files
define('ACCESS', true);

// Get blog categories
$blogCategories = $connect->query("SELECT * FROM blog_categories WHERE blog_cat_status = 1 ORDER BY blog_cat_name")->fetchAll(PDO::FETCH_ASSOC);

// Get all active users for author selection
$allAuthors = $connect->query("SELECT user_id, user_name, user_email FROM users WHERE user_status = 1 ORDER BY user_name")->fetchAll(PDO::FETCH_ASSOC);

// Check if editing existing post
$isEdit = isset($_GET['id']) && !empty($_GET['id']);
$post = null;

if ($isEdit) {
    $stmt = $connect->prepare("SELECT * FROM blog_posts WHERE post_id = :id");
    $stmt->execute([':id' => $_GET['id']]);
    $post = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$post) {
        header('Location: ./blog.php');
        exit;
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save') {
    
    $post_title = cleardata($_POST['post_title']);
    $post_slug = !empty($_POST['post_slug']) ? cleardata($_POST['post_slug']) : convertSlug($post_title);
    $post_content = $_POST['post_content']; // Don't clear HTML content
    $post_excerpt = cleardata($_POST['post_excerpt']);
    $post_category = !empty($_POST['post_category']) ? intval($_POST['post_category']) : null;
    $post_status = cleardata($_POST['post_status']);
    $post_featured = isset($_POST['post_featured']) ? 1 : 0;
    $post_seo_title = cleardata($_POST['post_seo_title']);
    $post_seo_description = cleardata($_POST['post_seo_description']);
    $post_tags = cleardata($_POST['post_tags']);
    $post_author = isset($_POST['post_author']) ? intval($_POST['post_author']) : $_SESSION['user_id'];
    $post_author_name = cleardata($_POST['post_author_name']);
    $post_author_bio = cleardata($_POST['post_author_bio']);
    
    // Handle featured image upload
    $post_featured_image = $isEdit ? $post['post_featured_image'] : null;
    $post_featured_image_cdn_url = cleardata($_POST['post_featured_image_cdn_url']);
    $post_use_cdn = !empty($post_featured_image_cdn_url) ? 1 : 0;
    
    if (isset($_FILES['post_featured_image']) && $_FILES['post_featured_image']['error'] == 0) {
        $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        $filename = $_FILES['post_featured_image']['name'];
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        
        if (in_array($ext, $allowed)) {
            $newFilename = 'blog_' . time() . '.' . $ext;
            $uploadPath = '../../images/' . $newFilename;
            
            if (move_uploaded_file($_FILES['post_featured_image']['tmp_name'], $uploadPath)) {
                $post_featured_image = $newFilename;
                $post_use_cdn = 0;
            }
        }
    }
    
    try {
        if ($isEdit) {
            // Update existing post
            $stmt = $connect->prepare("UPDATE blog_posts SET 
                post_title = :title,
                post_slug = :slug,
                post_content = :content,
                post_excerpt = :excerpt,
                post_featured_image = :image,
                post_featured_image_cdn_url = :cdn_url,
                post_use_cdn = :use_cdn,
                post_category = :category,
                post_status = :status,
                post_featured = :featured,
                post_seo_title = :seo_title,
                post_seo_description = :seo_desc,
                post_tags = :tags,
                post_author_name = :author_name,
                post_author_bio = :author_bio,
                published_at = CASE WHEN :status2 = 'published' AND published_at IS NULL THEN NOW() ELSE published_at END
                WHERE post_id = :id");
            
            $stmt->execute([
                ':title' => $post_title,
                ':slug' => $post_slug,
                ':content' => $post_content,
                ':excerpt' => $post_excerpt,
                ':image' => $post_featured_image,
                ':cdn_url' => $post_featured_image_cdn_url,
                ':use_cdn' => $post_use_cdn,
                ':category' => $post_category,
                ':status' => $post_status,
                ':status2' => $post_status,
                ':featured' => $post_featured,
                ':seo_title' => $post_seo_title,
                ':seo_desc' => $post_seo_description,
                ':tags' => $post_tags,
                ':author_name' => $post_author_name,
                ':author_bio' => $post_author_bio,
                ':id' => $_POST['post_id']
            ]);
            
            $message = "Post updated successfully!";
            $post_id = $_POST['post_id'];
            
        } else {
            // Create new post
            $stmt = $connect->prepare("INSERT INTO blog_posts 
                (post_title, post_slug, post_content, post_excerpt, post_featured_image, post_featured_image_cdn_url, post_use_cdn, post_category, post_author, post_status, post_featured, post_seo_title, post_seo_description, post_tags, post_author_name, post_author_bio, published_at) 
                VALUES 
                (:title, :slug, :content, :excerpt, :image, :cdn_url, :use_cdn, :category, :author, :status, :featured, :seo_title, :seo_desc, :tags, :author_name, :author_bio, CASE WHEN :status2 = 'published' THEN NOW() ELSE NULL END)");
            
            $stmt->execute([
                ':title' => $post_title,
                ':slug' => $post_slug,
                ':content' => $post_content,
                ':excerpt' => $post_excerpt,
                ':image' => $post_featured_image,
                ':cdn_url' => $post_featured_image_cdn_url,
                ':use_cdn' => $post_use_cdn,
                ':category' => $post_category,
                ':author' => $post_author,
                ':status' => $post_status,
                ':status2' => $post_status,
                ':featured' => $post_featured,
                ':seo_title' => $post_seo_title,
                ':seo_desc' => $post_seo_description,
                ':tags' => $post_tags,
                ':author_name' => $post_author_name,
                ':author_bio' => $post_author_bio
            ]);
            
            $post_id = $connect->lastInsertId();
            $message = "Post created successfully!";
        }
        
        header('Location: ./edit_blog.php?id=' . $post_id . '&success=' . urlencode($message));
        exit;
        
    } catch (Exception $e) {
        $error = "Error saving post: " . $e->getMessage();
    }
}

require '../views/blog.editor.view.php';
?>
