<?php
/**
 * Blog API Endpoints
 * Handles all blog-related database operations
 */

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

require_once __DIR__ . '/config/db.php';

// Get request method
$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_GET['action']) ? $_GET['action'] : '';

// Routes
switch ($method) {
    case 'GET':
        if ($action === 'get-blogs') {
            getBlogPosts();
        } elseif ($action === 'get-blog') {
            getBlogById();
        } elseif ($action === 'search-blogs') {
            searchBlogs();
        } else {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
        }
        break;

    case 'POST':
        if ($action === 'add-blog') {
            addBlog();
        } else {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
        }
        break;

    case 'PUT':
        if ($action === 'update-blog') {
            updateBlog();
        } else {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
        }
        break;

    case 'DELETE':
        if ($action === 'delete-blog') {
            deleteBlog();
        } else {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
        break;
}

/**
 * Get all blog posts
 */
function getBlogPosts() {
    global $connection;

    $query = "SELECT id, title, category, author, day, month, image_path, created_at FROM blogs ORDER BY created_at DESC";
    $result = $connection->query($query);

    if (!$result) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $connection->error]);
        return;
    }

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

    echo json_encode(['success' => true, 'data' => $blogs, 'count' => count($blogs)]);
}

/**
 * Get single blog by ID
 */
function getBlogById() {
    global $connection;

    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;

    if ($id <= 0) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid blog ID']);
        return;
    }

    $stmt = $connection->prepare("SELECT id, title, category, author, day, month, image_path, content, created_at FROM blogs WHERE id = ?");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();

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

    $blog = $result->fetch_assoc();
    $stmt->close();

    echo json_encode(['success' => true, 'data' => $blog]);
}

/**
 * Search blogs by title, category, or author
 */
function searchBlogs() {
    global $connection;

    $search = isset($_GET['q']) ? trim($_GET['q']) : '';

    if (strlen($search) < 2) {
        echo json_encode(['success' => false, 'message' => 'Search term must be at least 2 characters']);
        return;
    }

    $search = '%' . $connection->real_escape_string($search) . '%';

    $query = "SELECT id, title, category, author, day, month, image_path, created_at FROM blogs 
              WHERE title LIKE ? OR category LIKE ? OR author LIKE ? 
              ORDER BY created_at DESC";

    $stmt = $connection->prepare($query);
    $stmt->bind_param('sss', $search, $search, $search);
    $stmt->execute();
    $result = $stmt->get_result();

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

    $stmt->close();

    echo json_encode(['success' => true, 'data' => $blogs, 'count' => count($blogs)]);
}

/**
 * Add new blog post
 */
function addBlog() {
    global $connection;

    // Validate inputs
    $title = isset($_POST['title']) ? trim($_POST['title']) : '';
    $category = isset($_POST['category']) ? trim($_POST['category']) : '';
    $author = isset($_POST['author']) ? trim($_POST['author']) : '';
    $day = isset($_POST['day']) ? trim($_POST['day']) : '';
    $month = isset($_POST['month']) ? trim($_POST['month']) : '';
    $content = isset($_POST['content']) ? trim($_POST['content']) : '';

    if (empty($title) || empty($category) || empty($author) || empty($day) || empty($month)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        return;
    }

    // Handle image upload
    $image_path = '';
    if (isset($_FILES['image']) && $_FILES['image']['error'] == UPLOAD_ERR_OK) {
        $file = $_FILES['image'];
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        $max_size = 5 * 1024 * 1024; // 5MB

        if (!in_array($file['type'], $allowed_types)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid file type']);
            return;
        }

        if ($file['size'] > $max_size) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'File size exceeds 5MB limit']);
            return;
        }

        $file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $filename = 'blog-' . time() . '-' . rand(1000, 9999) . '.' . $file_ext;
        $upload_dir = __DIR__ . '/assets/img/blog/';

        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }

        $upload_path = $upload_dir . $filename;

        if (move_uploaded_file($file['tmp_name'], $upload_path)) {
            $image_path = 'assets/img/blog/' . $filename;
        } else {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to upload image']);
            return;
        }
    } else {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Image upload is required']);
        return;
    }

    // Insert into database
    $stmt = $connection->prepare("INSERT INTO blogs (title, category, author, day, month, image_path, content, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");

    if (!$stmt) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $connection->error]);
        return;
    }

    $stmt->bind_param('sssssss', $title, $category, $author, $day, $month, $image_path, $content);
    $stmt->execute();

    if ($stmt->affected_rows > 0) {
        $blog_id = $stmt->insert_id;
        $stmt->close();
        echo json_encode(['success' => true, 'message' => 'Blog post added successfully', 'blog_id' => $blog_id]);
    } else {
        $stmt->close();
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Failed to add blog post']);
    }
}

/**
 * Update blog post
 */
function updateBlog() {
    global $connection;

    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $title = isset($_POST['title']) ? trim($_POST['title']) : '';
    $category = isset($_POST['category']) ? trim($_POST['category']) : '';
    $author = isset($_POST['author']) ? trim($_POST['author']) : '';
    $day = isset($_POST['day']) ? trim($_POST['day']) : '';
    $month = isset($_POST['month']) ? trim($_POST['month']) : '';
    $content = isset($_POST['content']) ? trim($_POST['content']) : '';

    if ($id <= 0 || empty($title) || empty($category)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid input']);
        return;
    }

    // Check if blog exists
    $check_stmt = $connection->prepare("SELECT image_path FROM blogs WHERE id = ?");
    $check_stmt->bind_param('i', $id);
    $check_stmt->execute();
    $result = $check_stmt->get_result();

    if ($result->num_rows === 0) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Blog not found']);
        $check_stmt->close();
        return;
    }

    $old_blog = $result->fetch_assoc();
    $check_stmt->close();

    $image_path = $old_blog['image_path'];

    // Handle new image if provided
    if (isset($_FILES['image']) && $_FILES['image']['error'] == UPLOAD_ERR_OK) {
        $file = $_FILES['image'];
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        $max_size = 5 * 1024 * 1024;

        if (!in_array($file['type'], $allowed_types)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid file type']);
            return;
        }

        if ($file['size'] > $max_size) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'File size exceeds 5MB limit']);
            return;
        }

        $file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $filename = 'blog-' . time() . '-' . rand(1000, 9999) . '.' . $file_ext;
        $upload_dir = __DIR__ . '/assets/img/blog/';
        $upload_path = $upload_dir . $filename;

        if (move_uploaded_file($file['tmp_name'], $upload_path)) {
            // Delete old image
            $old_image_path = __DIR__ . '/' . $old_blog['image_path'];
            if (file_exists($old_image_path)) {
                @unlink($old_image_path);
            }
            $image_path = 'assets/img/blog/' . $filename;
        } else {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to upload image']);
            return;
        }
    }

    // Update database
    $stmt = $connection->prepare("UPDATE blogs SET title = ?, category = ?, author = ?, day = ?, month = ?, image_path = ?, content = ? WHERE id = ?");
    $stmt->bind_param('sssssssi', $title, $category, $author, $day, $month, $image_path, $content, $id);
    $stmt->execute();

    if ($stmt->affected_rows >= 0) {
        $stmt->close();
        echo json_encode(['success' => true, 'message' => 'Blog post updated successfully']);
    } else {
        $stmt->close();
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Failed to update blog post']);
    }
}

/**
 * Delete blog post
 */
function deleteBlog() {
    global $connection;

    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;

    if ($id <= 0) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid blog ID']);
        return;
    }

    // Get blog image path before deleting
    $stmt = $connection->prepare("SELECT image_path FROM blogs WHERE id = ?");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();

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

    $blog = $result->fetch_assoc();
    $stmt->close();

    // Delete from database
    $delete_stmt = $connection->prepare("DELETE FROM blogs WHERE id = ?");
    $delete_stmt->bind_param('i', $id);
    $delete_stmt->execute();

    if ($delete_stmt->affected_rows > 0) {
        // Delete image file
        $image_path = __DIR__ . '/' . $blog['image_path'];
        if (file_exists($image_path)) {
            @unlink($image_path);
        }

        $delete_stmt->close();
        echo json_encode(['success' => true, 'message' => 'Blog post deleted successfully']);
    } else {
        $delete_stmt->close();
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Failed to delete blog post']);
    }
}
?>
