<?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==='list'){
  $labels=[];$q=$conn->query("SELECT id,name,color FROM customer_lable WHERE account_id=$account_id AND status=1 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 customer_lable WHERE account_id=$account_id AND status=1 ORDER BY name ASC");
  while($q&&$r=$q->fetch_assoc())$labels[]=$r;
  $a=$conn->query("SELECT lable_id FROM customer_lable_customers WHERE account_id=$account_id AND customer_id=$customer_id");
  while($a&&$r=$a->fetch_assoc())$assigned[]=(int)$r['lable_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 customer_lable (account_id,name,color,status,date_created) VALUES ($account_id,'$name','$color',1,NOW())");
  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 customer_lable_customers WHERE account_id=$account_id AND customer_id=$customer_id");
  foreach($ids as $id){$id=(int)$id;if($id>0)$conn->query("INSERT IGNORE INTO customer_lable_customers (account_id,customer_id,lable_id,date_created) VALUES ($account_id,$customer_id,$id,NOW())");}
  jsonResponse(true,'Labels updated');
}
jsonResponse(false,'Invalid action');
?>
