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

// Add new category
if(isset($_POST['add_category'])) {
    $categoryName = mysqli_real_escape_string($conn, $_POST['category_name']);
    $createdAt = date('Y-m-d H:i:s');

    // Insert category
    $sql = mysqli_query($conn, "
        INSERT INTO `categories` (`category_name`, `created_at`)
        VALUES ('$categoryName', '$createdAt')
    ");

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

// Fetch category data for edit
if(isset($_POST['fetch_category'])) {
    $categoryId = mysqli_real_escape_string($conn, $_POST['category_id']);
    $q = mysqli_query($conn,"
        SELECT * FROM categories 
        WHERE id='$categoryId'
        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'])) {
    $categoryId = mysqli_real_escape_string($conn, $_POST['id']);
    $categoryName = mysqli_real_escape_string($conn, $_POST['category_name']);

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

    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
if(isset($_POST['delete_category'])) {
    $categoryId = mysqli_real_escape_string($conn, $_POST['category_id']);
    $q = mysqli_query($conn,"
        DELETE FROM `categories` WHERE `id`='$categoryId'
    ");
    if($q) {
        echo "Category deleted successfully!";
    } else {
        echo "Error deleting category: " . mysqli_error($conn);
    }
    exit;
}
?>
