<?php
/**
 * Admin API — Edit Category
 * Updates the display name of a category without changing its slug.
 */
session_start();
header('Content-Type: application/json');

if (empty($_SESSION['admin_logged_in'])) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

require_once '../../includes/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? null;
    $name = trim($_POST['name'] ?? '');

    if (empty($id) || empty($name)) {
        echo json_encode(['status' => 'error', 'message' => 'Category ID and new name are required.']);
        exit;
    }

    try {
        // We only update the name, NOT the slug, so existing products aren't affected.
        $stmt = $pdo->prepare("UPDATE categories SET name = ? WHERE id = ?");
        $stmt->execute([$name, $id]);
        
        if ($stmt->rowCount() > 0) {
            echo json_encode(['status' => 'success', 'message' => 'Category updated successfully.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'No changes made or category not found.']);
        }
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
    }
}
?>
