<?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 = (int)$_SESSION['account_id'];
$raw = file_get_contents('php://input');
$json = $raw ? json_decode($raw, true) : [];
$action = $_POST['action'] ?? ($json['action'] ?? '');

if ($action === 'add_label') {
    $name = sanitize($conn, $_POST['name'] ?? ($json['name'] ?? ''));
    $color = sanitize($conn, $_POST['color'] ?? ($json['color'] ?? '#1a3a6f'));
    if (!$name) jsonResponse(false, 'Label name required');
    $conn->query("INSERT IGNORE INTO labels (account_id, name, color) VALUES ($account_id, '$name', '$color')");
    jsonResponse(true, 'Label saved');
}

if ($action === 'assign') {
    $entity_type = sanitize($conn, $_POST['entity_type'] ?? ($json['entity_type'] ?? ''));
    $entity_id = (int)($_POST['entity_id'] ?? ($json['entity_id'] ?? 0));
    $label_id = (int)($_POST['label_id'] ?? ($json['label_id'] ?? 0));
    if (!$entity_type || !$entity_id || !$label_id) jsonResponse(false, 'Missing data');
    $conn->query("INSERT IGNORE INTO entity_labels (account_id, entity_type, entity_id, label_id) VALUES ($account_id, '$entity_type', $entity_id, $label_id)");
    jsonResponse(true, 'Label assigned');
}

if ($action === 'remove') {
    $entity_type = sanitize($conn, $_POST['entity_type'] ?? ($json['entity_type'] ?? ''));
    $entity_id = (int)($_POST['entity_id'] ?? ($json['entity_id'] ?? 0));
    $label_id = (int)($_POST['label_id'] ?? ($json['label_id'] ?? 0));
    $conn->query("DELETE FROM entity_labels WHERE account_id=$account_id AND entity_type='$entity_type' AND entity_id=$entity_id AND label_id=$label_id");
    jsonResponse(true, 'Label removed');
}

jsonResponse(false, 'Invalid action');
?>
