<?php
session_start();
if (!isset($_SESSION['user_id'])) { http_response_code(403); exit(json_encode(['success'=>false,'message'=>'Unauthorized'])); }
require_once '../connect.php';
$account_id = $_SESSION['account_id'];
$raw    = file_get_contents('php://input');
$json   = $raw ? json_decode($raw, true) : null;
if (is_array($json)) crmDecodeIdsInArray($json);
crmDecodeIdsInArray($_POST);
$action = $_POST['action'] ?? ($json['action'] ?? '');

switch ($action) {
    case 'add':
    case 'edit':
        requirePermission($conn, 'items', ($_POST['edit_id'] ?? 0) ? 'edit' : 'add');
        $name = sanitize($conn, $_POST['name'] ?? '');
        $description = sanitize($conn, $_POST['description'] ?? '');
        $color = sanitize($conn, $_POST['color'] ?? '#3B82F6');
        $edit_id = (int)($_POST['edit_id'] ?? 0);
        
        if (!$name) jsonResponse(false, 'Category name required');
        
        if ($edit_id) {
            $conn->query("UPDATE categories SET name='$name', description='$description', color='$color' WHERE id=$edit_id AND account_id=$account_id");
        } else {
            $conn->query("INSERT INTO categories (name, description, color, account_id) VALUES ('$name','$description','$color',$account_id)");
        }
        jsonResponse(true, $edit_id ? 'Category updated' : 'Category added');
        
    case 'get':
        $id = (int)($json['id'] ?? $_POST['id'] ?? 0);
        $r = $conn->query("SELECT * FROM categories WHERE id=$id AND account_id=$account_id")->fetch_assoc();
        if (!$r) jsonResponse(false, 'Not found');
        jsonResponse(true, '', ['data' => $r]);
        
    case 'delete':
        requirePermission($conn, 'items', 'delete');
        $id = (int)($json['id'] ?? $_POST['id'] ?? 0);
        // Set category_id to NULL for items in this category first
        $conn->query("UPDATE items SET category_id = NULL WHERE category_id = $id AND account_id = $account_id");
        $conn->query("DELETE FROM categories WHERE id=$id AND account_id=$account_id");
        jsonResponse(true, 'Category deleted');
        
    default:
        jsonResponse(false, 'Invalid action');
}