<?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 INTO customer_lable (account_id, name, color, status) VALUES ($account_id, '$name', '$color', 1) ON DUPLICATE KEY UPDATE color=VALUES(color), status=1");
    jsonResponse(true, 'Label saved');
}

if ($action === 'list_for_customer') {
    $customer_id = (int)($_POST['customer_id'] ?? ($json['customer_id'] ?? 0));
    $labels = []; $assigned = [];
    $q = $conn->query("SELECT id, name, color FROM customer_lable WHERE account_id=$account_id AND status=1 ORDER BY name ASC");
    if ($q) while($r=$q->fetch_assoc()) $labels[]=$r;
    $q2 = $conn->query("SELECT lable_id FROM customer_lable_customers WHERE account_id=$account_id AND customer_id=$customer_id");
    if ($q2) while($r=$q2->fetch_assoc()) $assigned[]=(int)$r['lable_id'];
    jsonResponse(true, 'OK', ['labels'=>$labels, 'assigned'=>$assigned]);
}

if ($action === 'assign') {
    $customer_id = (int)($_POST['customer_id'] ?? ($json['customer_id'] ?? 0));
    $lable_id = (int)($_POST['lable_id'] ?? ($json['lable_id'] ?? 0));
    if (!$customer_id || !$lable_id) jsonResponse(false, 'Missing data');
    $conn->query("INSERT IGNORE INTO customer_lable_customers (account_id, customer_id, lable_id) VALUES ($account_id, $customer_id, $lable_id)");
    jsonResponse(true, 'Assigned');
}

if ($action === 'remove') {
    $customer_id = (int)($_POST['customer_id'] ?? ($json['customer_id'] ?? 0));
    $lable_id = (int)($_POST['lable_id'] ?? ($json['lable_id'] ?? 0));
    $conn->query("DELETE FROM customer_lable_customers WHERE account_id=$account_id AND customer_id=$customer_id AND lable_id=$lable_id");
    jsonResponse(true, 'Removed');
}

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