<?php
session_start();
require_once '../config/db.php';

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

try {
    if (!isset($_SESSION['username'])) {
        throw new Exception('User not logged in');
    }

    if (empty($_POST['id']) || empty($_POST['category_name'])) {
        throw new Exception('Missing required fields');
    }

    $id = $_POST['id'];
    $category_name = strtoupper(trim($_POST['category_name']));

    // Check if new name already exists
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM categories WHERE category_name = ? AND id != ?");
    $stmt->execute([$category_name, $id]);
    if ($stmt->fetchColumn() > 0) {
        throw new Exception('Category name already exists');
    }

    // Update category
    $stmt = $pdo->prepare("UPDATE categories SET category_name = ? WHERE id = ?");
    $stmt->execute([$category_name, $id]);

    echo json_encode(['success' => true]);
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}