<?php
ob_start();
include("connection.php");

// Add new category item
if(isset($_POST['add_category'])) {
    $category_name = trim($_POST['category_name']);
    
    // Server-side validation
    if (empty($category_name)) {
        echo "Error: Category name is required";
        exit;
    }
    
    $category_name = mysqli_real_escape_string($conn, $category_name);
    $created_at = date('Y-m-d H:i:s');

    $sql = mysqli_query($conn, "
        INSERT INTO `categories`(`category_name`, `created_at`)
        VALUES ('$category_name','$created_at')
    ");

    if($sql){
        echo "Category added successfully!";
    } else {
        echo "Error: " . mysqli_error($conn);
    }
}

// Fetch category data for edit
if(isset($_POST['fetch_category'])) {
    $category_id = $_POST['category_id'];
    $q = mysqli_query($conn,"SELECT * FROM categories WHERE id='$category_id' ORDER BY id ASC limit 1");
    $data = mysqli_fetch_assoc($q);
    echo json_encode([
        "id" => $data['id'],
        "category_name" => $data['category_name']
    ]);
    exit;
}

// Edit category details
if(isset($_POST['edit_category'])) {
    $category_id = mysqli_real_escape_string($conn, $_POST['id']);
    $category_name = trim($_POST['category_name']);
    
    // Server-side validation
    if (empty($category_name)) {
        echo "Error: Category name is required";
        exit;
    }
    
    $category_name = mysqli_real_escape_string($conn, $category_name);

    // Update category
    $sql = mysqli_query($conn, "
        UPDATE `categories` SET 
        `category_name`='$category_name'
        WHERE `id`='$category_id'
    ");

    if ($sql) {
        if (mysqli_affected_rows($conn) > 0) {
            echo "Category updated successfully!";
        } else {
            echo "No changes made to category data.";
        }
    } else {
        echo "Error updating category: " . mysqli_error($conn);
    }
}

// Delete category item
if(isset($_POST['delete_category'])) {
    $category_id = $_POST['category_id'];
    $q = mysqli_query($conn,"DELETE FROM `categories` WHERE `id`='$category_id'");
    if($q) {
        echo "Category deleted successfully!";
    } else {
        echo "Error deleting category: " . mysqli_error($conn);
    }
    exit;
}
?>