<?php
/**
 * Blog Management API
 * Handles CRUD operations for blog posts
 */

session_start();
header('Content-Type: application/json');

require_once 'config.php';

// Get the action
$action = isset($_GET['action']) ? $_GET['action'] : (isset($_POST['action']) ? $_POST['action'] : '');

try {
    switch ($action) {
        // Admin Actions
        case 'create_blog':
            echo json_encode(createBlog($conn));
            break;
        case 'get_blogs_admin':
            echo json_encode(getBlogsAdmin($conn));
            break;
        case 'get_blog':
            echo json_encode(getBlog($conn, $_GET['id'] ?? 0));
            break;
        case 'update_blog':
            echo json_encode(updateBlog($conn));
            break;
        case 'delete_blog':
            echo json_encode(deleteBlog($conn, $_POST['id'] ?? 0));
            break;

        // Public API
        case 'get_blogs':
            echo json_encode(getPublicBlogs($conn));
            break;
        case 'get_blog_public':
            echo json_encode(getPublicBlog($conn, $_GET['id'] ?? $_GET['slug'] ?? 0));
            break;
        case 'get_featured_blogs':
            echo json_encode(getFeaturedBlogs($conn));
            break;

        default:
            echo json_encode([
                'success' => false,
                'message' => 'Invalid action: ' . $action
            ]);
    }
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'API Error: ' . $e->getMessage()
    ]);
}

// ===== ADMIN FUNCTIONS =====

function createBlog($conn) {
    $title = isset($_POST['title']) ? trim($_POST['title']) : '';
    $content = isset($_POST['content']) ? trim($_POST['content']) : '';
    $excerpt = isset($_POST['excerpt']) ? trim($_POST['excerpt']) : '';
    $category = isset($_POST['category']) ? trim($_POST['category']) : '';
    $status = isset($_POST['status']) ? trim($_POST['status']) : 'draft';
    $featured = isset($_POST['featured']) ? (int)$_POST['featured'] : 0;
    
    if (empty($title)) {
        return ['success' => false, 'message' => 'Title is required'];
    }
    
    if (empty($content)) {
        return ['success' => false, 'message' => 'Content is required'];
    }

    // Generate slug
    $slug = generateSlug($title);
    
    // Check if slug already exists
    $checkStmt = $conn->prepare("SELECT id FROM blog WHERE slug = ?");
    $checkStmt->bind_param("s", $slug);
    $checkStmt->execute();
    if ($checkStmt->get_result()->num_rows > 0) {
        $slug = $slug . '-' . time();
    }
    $checkStmt->close();

    // Handle image upload
    $featured_image = null;
    if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] === UPLOAD_ERR_OK) {
        $featured_image = uploadBlogImage($_FILES['featured_image']);
        if (!$featured_image) {
            return ['success' => false, 'message' => 'Failed to upload image'];
        }
    }

    $stmt = $conn->prepare("INSERT INTO blog (title, slug, content, excerpt, featured_image, category, status, featured) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sssssssi", $title, $slug, $content, $excerpt, $featured_image, $category, $status, $featured);

    if ($stmt->execute()) {
        return ['success' => true, 'message' => 'Blog created successfully', 'id' => $conn->insert_id];
    }
    return ['success' => false, 'message' => 'Failed to create blog: ' . $stmt->error];
}

function getBlogsAdmin($conn) {
    $stmt = $conn->prepare("SELECT id, title, slug, excerpt, featured_image, category, status, featured, created_at, updated_at FROM blog ORDER BY created_at DESC");
    
    if (!$stmt->execute()) {
        return ['success' => false, 'message' => 'Query failed: ' . $stmt->error];
    }

    $result = $stmt->get_result();
    $blogs = [];
    
    while ($row = $result->fetch_assoc()) {
        $blogs[] = $row;
    }

    return ['success' => true, 'data' => $blogs];
}

function getBlog($conn, $id) {
    if (!$id) {
        return ['success' => false, 'message' => 'Blog ID is required'];
    }

    $stmt = $conn->prepare("SELECT id, title, slug, content, excerpt, featured_image, category, status, featured, created_at, updated_at FROM blog WHERE id = ?");
    $stmt->bind_param("i", $id);
    
    if (!$stmt->execute()) {
        return ['success' => false, 'message' => 'Query failed'];
    }

    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        return ['success' => false, 'message' => 'Blog not found'];
    }

    $blog = $result->fetch_assoc();
    return ['success' => true, 'data' => $blog];
}

function updateBlog($conn) {
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    $title = isset($_POST['title']) ? trim($_POST['title']) : '';
    $content = isset($_POST['content']) ? trim($_POST['content']) : '';
    $excerpt = isset($_POST['excerpt']) ? trim($_POST['excerpt']) : '';
    $category = isset($_POST['category']) ? trim($_POST['category']) : '';
    $status = isset($_POST['status']) ? trim($_POST['status']) : 'draft';
    $featured = isset($_POST['featured']) ? (int)$_POST['featured'] : 0;

    if (!$id || empty($title) || empty($content)) {
        return ['success' => false, 'message' => 'Missing required fields'];
    }

    // Get current blog to check for existing image
    $currentBlog = getBlog($conn, $id);
    $featured_image = $currentBlog['data']['featured_image'] ?? null;

    // Handle image upload
    if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] === UPLOAD_ERR_OK) {
        $new_image = uploadBlogImage($_FILES['featured_image']);
        if (!$new_image) {
            return ['success' => false, 'message' => 'Failed to upload image'];
        }
        // Delete old image
        if ($featured_image && file_exists("../assets/uploads/blog/" . basename($featured_image))) {
            unlink("../assets/uploads/blog/" . basename($featured_image));
        }
        $featured_image = $new_image;
    }

    $stmt = $conn->prepare("UPDATE blog SET title = ?, content = ?, excerpt = ?, featured_image = ?, category = ?, status = ?, featured = ? WHERE id = ?");
    $stmt->bind_param("ssssssii", $title, $content, $excerpt, $featured_image, $category, $status, $featured, $id);

    if ($stmt->execute()) {
        return ['success' => true, 'message' => 'Blog updated successfully'];
    }
    return ['success' => false, 'message' => 'Failed to update blog'];
}

function deleteBlog($conn, $id) {
    if (!$id) {
        return ['success' => false, 'message' => 'Blog ID is required'];
    }

    // Get blog to delete image
    $blog = getBlog($conn, $id);
    if ($blog['success'] && $blog['data']['featured_image']) {
        $image_path = "../assets/uploads/blog/" . basename($blog['data']['featured_image']);
        if (file_exists($image_path)) {
            unlink($image_path);
        }
    }

    $stmt = $conn->prepare("DELETE FROM blog WHERE id = ?");
    $stmt->bind_param("i", $id);

    if ($stmt->execute()) {
        return ['success' => true, 'message' => 'Blog deleted successfully'];
    }
    return ['success' => false, 'message' => 'Failed to delete blog'];
}

// ===== PUBLIC FUNCTIONS =====

function getPublicBlogs($conn) {
    $stmt = $conn->prepare("SELECT id, title, slug, excerpt, featured_image, category, created_at FROM blog WHERE status = 'published' ORDER BY created_at DESC");
    
    if (!$stmt->execute()) {
        return ['success' => false, 'message' => 'Query failed'];
    }

    $result = $stmt->get_result();
    $blogs = [];
    
    while ($row = $result->fetch_assoc()) {
        $blogs[] = $row;
    }

    return ['success' => true, 'data' => $blogs];
}

function getPublicBlog($conn, $identifier) {
    if (!$identifier) {
        return ['success' => false, 'message' => 'Blog ID or slug is required'];
    }

    // Try to get by ID first, then by slug
    if (is_numeric($identifier)) {
        $stmt = $conn->prepare("SELECT id, title, slug, content, excerpt, featured_image, category, created_at FROM blog WHERE id = ? AND status = 'published'");
        $stmt->bind_param("i", $identifier);
    } else {
        $stmt = $conn->prepare("SELECT id, title, slug, content, excerpt, featured_image, category, created_at FROM blog WHERE slug = ? AND status = 'published'");
        $stmt->bind_param("s", $identifier);
    }
    
    if (!$stmt->execute()) {
        return ['success' => false, 'message' => 'Query failed'];
    }

    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        return ['success' => false, 'message' => 'Blog not found'];
    }

    $blog = $result->fetch_assoc();
    return ['success' => true, 'data' => $blog];
}

function getFeaturedBlogs($conn) {
    $stmt = $conn->prepare("SELECT id, title, slug, excerpt, featured_image, category, created_at FROM blog WHERE status = 'published' AND featured = 1 ORDER BY created_at DESC LIMIT 6");
    
    if (!$stmt->execute()) {
        return ['success' => false, 'message' => 'Query failed'];
    }

    $result = $stmt->get_result();
    $blogs = [];
    
    while ($row = $result->fetch_assoc()) {
        $blogs[] = $row;
    }

    return ['success' => true, 'data' => $blogs];
}

// ===== HELPER FUNCTIONS =====

function generateSlug($title) {
    $slug = strtolower($title);
    $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
    $slug = trim($slug, '-');
    return $slug;
}

function uploadBlogImage($file) {
    $upload_dir = "../assets/uploads/blog/";
    
    // Create directory if it doesn't exist
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    
    if (!in_array($file['type'], $allowed_types)) {
        return false;
    }

    $max_size = 5 * 1024 * 1024; // 5MB
    if ($file['size'] > $max_size) {
        return false;
    }

    $filename = time() . '_' . basename($file['name']);
    $filepath = $upload_dir . $filename;

    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        return "assets/uploads/blog/" . $filename;
    }

    return false;
}

?>
