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

if ($action === 'list') {
    $labels = [];
    $q = $conn->query("SELECT id, name, color FROM labels WHERE account_id=$account_id ORDER BY name ASC");
    while ($q && $r = $q->fetch_assoc()) $labels[] = $r;
    jsonResponse(true, '', ['labels'=>$labels]);
}

if ($action === 'customer_labels') {
    $customer_id = (int)($_POST['customer_id'] ?? ($json['customer_id'] ?? 0));
    $labels = [];
    $assigned = [];
    $q = $conn->query("SELECT id, name, color FROM labels WHERE account_id=$account_id ORDER BY name ASC");
    while ($q && $r = $q->fetch_assoc()) $labels[] = $r;
    $a = $conn->query("SELECT label_id FROM entity_labels WHERE account_id=$account_id AND entity_type='customer' AND entity_id=$customer_id");
    while ($a && $r = $a->fetch_assoc()) $assigned[] = (int)$r['label_id'];
    jsonResponse(true, '', ['labels'=>$labels, 'assigned'=>$assigned]);
}

if ($action === 'add_label') {
    requirePermission($conn, 'customers', 'edit');
    $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 === 'save_customer_labels') {
    requirePermission($conn, 'customers', 'edit');
    $customer_id = (int)($_POST['customer_id'] ?? ($json['customer_id'] ?? 0));
    $ids = $_POST['label_ids'] ?? ($json['label_ids'] ?? []);
    if (!is_array($ids)) $ids = [];
    if (!$customer_id) jsonResponse(false, 'Missing customer');
    $conn->query("DELETE FROM entity_labels WHERE account_id=$account_id AND entity_type='customer' AND entity_id=$customer_id");
    foreach ($ids as $id) {
        $id = (int)$id;
        if ($id > 0) $conn->query("INSERT IGNORE INTO entity_labels (account_id, entity_type, entity_id, label_id) VALUES ($account_id, 'customer', $customer_id, $id)");
    }
    jsonResponse(true, 'Labels updated');
}

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');
?>
