<?php
session_start();
include_once 'model/posts_model.php';

// Ensure the request is a POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Get the category name from the form submission
    $category_name = isset($_POST['categoryName']) ? trim($_POST['categoryName']) : '';

    // Validate category name
    if (empty($category_name)) {
        // Respond with an error if the category name is empty
        echo json_encode([
            'success' => false,
            'message' => 'Category name is required.'
        ]);
        exit;
    }

    // Instantiate the posts_model to interact with the database
    $posts_model = new posts_model();

    // Attempt to add the new category
    $add_result = $posts_model->add_category($category_name, $date_created = date('Y-m-d H:i:s'), $created_by = $_SESSION['user_id']);

    if ($add_result) {
        // If category was successfully added, send a success response
        echo json_encode([
            'success' => true,
            'message' => 'Category added successfully.'
        ]);
    } else {
        // If there was an issue adding the category, send an error response
        echo json_encode([
            'success' => false,
            'message' => 'Failed to add category. Please try again.'
        ]);
    }

} else {
    // If the request method is not POST, return an error
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method.'
    ]);
}
?>
