<?php
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../../odbconexion/odbconexion.php';

function clean($v){ return trim((string)($v ?? '')); }

try {
  if($_SERVER['REQUEST_METHOD'] !== 'POST'){
    echo json_encode(["ok"=>false, "msg"=>"Método no permitido"], JSON_UNESCAPED_UNICODE);
    exit;
  }

  $promotor = clean($_POST['promotor'] ?? '');
  if($promotor === ''){
    echo json_encode(["ok"=>false, "msg"=>"Promotor es obligatorio"], JSON_UNESCAPED_UNICODE);
    exit;
  }

  session_start();
  $usuario = $_SESSION['usuario'] ?? ($_SESSION['user'] ?? 'sistema');

  $db = (new odbconexion())->openconection();
  $db->set_charset("utf8mb4");

  // Evitar duplicados exactos
  $stmt = $db->prepare("SELECT Id_Catalogo_Cliente_Pertenece FROM catalogo_cliente_pertenece WHERE Promotor = ? LIMIT 1");
  $stmt->bind_param("s", $promotor);
  $stmt->execute();
  $r = $stmt->get_result();
  if($r && $r->num_rows > 0){
    $row = $r->fetch_assoc();
    echo json_encode(["ok"=>true, "id"=>(int)$row['Id_Catalogo_Cliente_Pertenece'], "text"=>$promotor, "msg"=>"Ya existía, se seleccionó"], JSON_UNESCAPED_UNICODE);
    exit;
  }

  $stmt2 = $db->prepare("
    INSERT INTO catalogo_cliente_pertenece (Promotor, Fecha_De_Registro, Usuario_Que_Registra)
    VALUES (?, NOW(), ?)
  ");
  if(!$stmt2){
    echo json_encode(["ok"=>false, "msg"=>"Prepare error: ".$db->error], JSON_UNESCAPED_UNICODE);
    exit;
  }

  $stmt2->bind_param("ss", $promotor, $usuario);
  if(!$stmt2->execute()){
    echo json_encode(["ok"=>false, "msg"=>"Execute error: ".$stmt2->error], JSON_UNESCAPED_UNICODE);
    exit;
  }

  echo json_encode(["ok"=>true, "id"=>(int)$stmt2->insert_id, "text"=>$promotor], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e){
  echo json_encode(["ok"=>false, "msg"=>"Error: ".$e->getMessage()], JSON_UNESCAPED_UNICODE);
}
