<?php
/* ===========================================================
   /htdocs/appquadrata/home/cotizador/index.php
   Cotizador de Fianza - TODO INTEGRADO
=========================================================== */
// en un config.php global
define('BASE_PATH', $_SERVER['DOCUMENT_ROOT'] . '/appquadrata/');

$pathConexion = __DIR__ . '/../../odbconexion/config.php';
if(!file_exists($pathConexion)){
  die("No se encontró odbconexion.php en: <br><b>".$pathConexion."</b><br><br>
       Revisa que exista: D:\\quadrata_app\\htdocs\\appquadrata\\odbconexion\\odbconexion.php");
}
require_once $pathConexion;

function json_out($arr){
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode($arr, JSON_UNESCAPED_UNICODE);
  exit;
}
function clean($v){ return trim((string)($v ?? '')); }

// ==============================
// AJAX ENDPOINTS (MISMO ARCHIVO)
// ==============================
if(isset($_GET['ajax'])){
  try{
    $db = (new odbconexion())->openconection();
    $db->set_charset("utf8mb4");

    $ajax = $_GET['ajax'];

    // ---------- PROMOTORES ----------
    if($ajax === 'get_promotores'){
      $res = $db->query("SELECT Id_Catalogo_Cliente_Pertenece, Promotor
                         FROM catalogo_cliente_pertenece
                         ORDER BY Promotor ASC");
      $out = [];
      if($res){
        while($r = $res->fetch_assoc()){
          $out[] = ["id"=>(int)$r['Id_Catalogo_Cliente_Pertenece'], "text"=>clean($r['Promotor'])];
        }
      }
      json_out(["ok"=>true,"data"=>$out]);
    }

    if($ajax === 'insert_promotor'){
      if($_SERVER['REQUEST_METHOD'] !== 'POST') json_out(["ok"=>false,"msg"=>"Método no permitido"]);

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

      if($promotor === '') json_out(["ok"=>false,"msg"=>"Promotor es obligatorio"]);

      // evitar duplicado exacto
      $stmt = $db->prepare("SELECT Id_Catalogo_Cliente_Pertenece FROM catalogo_cliente_pertenece WHERE Promotor = ? LIMIT 1");
      $stmt->bind_param("s",$promotor);
      $stmt->execute();
      $rr = $stmt->get_result();
      if($rr && $rr->num_rows>0){
        $row = $rr->fetch_assoc();
        json_out(["ok"=>true,"id"=>(int)$row['Id_Catalogo_Cliente_Pertenece'],"text"=>$promotor,"msg"=>"Ya existía, se seleccionó"]);
      }

      $stmt2 = $db->prepare("INSERT INTO catalogo_cliente_pertenece (Promotor, Fecha_De_Registro, Usuario_Que_Registra)
                             VALUES (?, NOW(), ?)");
      if(!$stmt2) json_out(["ok"=>false,"msg"=>"Prepare error: ".$db->error]);
      $stmt2->bind_param("ss",$promotor,$usuario);
      if(!$stmt2->execute()) json_out(["ok"=>false,"msg"=>"Execute error: ".$stmt2->error]);

      json_out(["ok"=>true,"id"=>(int)$stmt2->insert_id,"text"=>$promotor]);
    }

    // ---------- CLIENTES ----------
    if($ajax === 'get_clientes'){
      $res = $db->query("SELECT Id_Clientes, Nombre_Completo, Apellido_Paterno, Apellido_Materno, RFC, Razon_Social_Persona_Moral
                         FROM clientes
                         ORDER BY Id_Clientes DESC");
      $out = [];
      if($res){
        while($row = $res->fetch_assoc()){
          $nombre = trim(clean($row['Nombre_Completo'])." ".clean($row['Apellido_Paterno'])." ".clean($row['Apellido_Materno']));
          $razon  = clean($row['Razon_Social_Persona_Moral']);
          $rfc    = clean($row['RFC']);

          $label = $razon !== '' ? $razon : ($nombre !== '' ? $nombre : ('Cliente #'.$row['Id_Clientes']));
          if($rfc !== '') $label .= " — $rfc";

          $out[] = ["id"=>(int)$row['Id_Clientes'],"text"=>$label];
        }
      }
      json_out(["ok"=>true,"data"=>$out]);
    }

    if($ajax === 'insert_cliente'){
      if($_SERVER['REQUEST_METHOD'] !== 'POST') json_out(["ok"=>false,"msg"=>"Método no permitido"]);

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

      $tipo = clean($_POST['tipo_persona'] ?? 'fisica'); // fisica|moral
      $id_promotor = (int)($_POST['id_fk_catalogo_cliente_pertenece'] ?? 0);

      $rfc    = clean($_POST['rfc'] ?? '');
      $correo = clean($_POST['correo_1'] ?? '');
      $cel    = clean($_POST['no_de_celular'] ?? '');
      $obs    = clean($_POST['observaciones_y_notas'] ?? '');

      $nombre = clean($_POST['nombre_completo'] ?? '');
      $ap     = clean($_POST['apellido_paterno'] ?? '');
      $am     = clean($_POST['apellido_materno'] ?? '');

      $razon  = clean($_POST['razon_social_persona_moral'] ?? '');
      $contacto = clean($_POST['nombre_de_contacto_persona_moral'] ?? '');

      if($tipo === 'moral'){
        if($razon === '') json_out(["ok"=>false,"msg"=>"Razón social es obligatoria (Persona Moral)"]);
      } else {
        if($nombre === '' && ($ap==='' && $am==='')) json_out(["ok"=>false,"msg"=>"Nombre o apellidos son obligatorios (Persona Física)"]);
      }

      $stmt = $db->prepare("
        INSERT INTO clientes
        (
          Id_Fk_Catalogo_Cliente_Pertenece,
          Nombre_Completo, Apellido_Paterno, Apellido_Materno,
          RFC,
          Razon_Social_Persona_Moral,
          Nombre_De_Contacto_Persona_Moral,
          No_De_Celular,
          Correo_1,
          Observaciones_Y_Notas,
          Fecha_De_Registro,
          Usuario_Que_Registra
        )
        VALUES
        (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?)
      ");
      if(!$stmt) json_out(["ok"=>false,"msg"=>"Prepare error: ".$db->error]);

      $stmt->bind_param(
        "issssssssss",
        $id_promotor,
        $nombre, $ap, $am,
        $rfc,
        $razon,
        $contacto,
        $cel,
        $correo,
        $obs,
        $usuario
      );

      if(!$stmt->execute()) json_out(["ok"=>false,"msg"=>"Execute error: ".$stmt->error]);

      $newId = (int)$stmt->insert_id;

      $label = ($razon !== '') ? $razon : trim("$nombre $ap $am");
      if($label === '') $label = "Cliente #$newId";
      if($rfc !== '') $label .= " — $rfc";

      json_out(["ok"=>true,"id"=>$newId,"text"=>$label]);
    }

    json_out(["ok"=>false,"msg"=>"Acción ajax no válida"]);
  } catch(Throwable $e){
    json_out(["ok"=>false,"msg"=>"Error: ".$e->getMessage()]);
  }
}

// ==============================
// RENDER NORMAL DEL COTIZADOR
// ==============================
$db = (new odbconexion())->openconection();
$db->set_charset("utf8mb4");

$afianzadoras = [];
$res = $db->query("SELECT Id_Afianzadora, Nombre_Afianzadora, Gastos_de_Expedicion
                   FROM afianzadoras
                   ORDER BY Nombre_Afianzadora ASC");
if($res){
  while($row = $res->fetch_assoc()){
    $afianzadoras[] = $row;
  }
}

$firstGastos = 0;
if(count($afianzadoras)>0){
  $firstGastos = (float)($afianzadoras[0]['Gastos_de_Expedicion'] ?? 0);
}
?>
<!doctype html>
<html lang="es-MX">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Cotizador de Fianza</title>

<style>
:root{
  --bg:#f6f8fb;
  --card:#ffffff;
  --text:#0d1420;
  --muted:#516078;
  --line:rgba(0,0,0,.12);
  --accent:#ff9a1f;
  --ok:#1f9d6a;
  --radius:16px;
  --shadow:0 10px 28px rgba(0,0,0,.10);
}
body.dark{
  --bg:#0b0f14;
  --card:#101826;
  --text:#e9f0ff;
  --muted:#9fb0c6;
  --line:rgba(255,255,255,.12);
  --shadow:0 14px 34px rgba(0,0,0,.45);
}
*{ box-sizing:border-box; }
body{
  margin:0;
  font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial;
  background:var(--bg);
  color:var(--text);
  transition:background .4s,color .4s;
}
.wrap{ max-width:980px; margin:auto; padding:16px; }
header{
  display:flex; flex-direction:column; gap:8px;
  padding:16px; border-radius:var(--radius);
  background:var(--card); border:1px solid var(--line);
  box-shadow:var(--shadow);
}
header h1{ margin:0; font-size:18px; }
.badge{
  align-self:flex-start; font-size:12px;
  padding:6px 10px; border-radius:999px;
  background:rgba(255,154,31,.15);
  border:1px solid rgba(255,154,31,.45);
}
.grid{ margin-top:16px; display:grid; grid-template-columns:1fr 1fr; gap:16px; }
@media(max-width:900px){ .grid{ grid-template-columns:1fr; } }
.card{
  background:var(--card); border:1px solid var(--line);
  border-radius:var(--radius); padding:16px;
  box-shadow:var(--shadow);
}
.card h2{ margin:0 0 12px; font-size:14px; color:var(--muted); }
.row{ display:grid; grid-template-columns:1fr 1fr; gap:12px; }
@media(max-width:600px){ .row{ grid-template-columns:1fr; } }
label{ font-size:12px; color:var(--muted); display:block; margin-bottom:6px; }
input,select{
  width:100%; padding:14px; font-size:16px;
  border-radius:12px; border:1px solid var(--line);
  background:transparent; color:var(--text);
}
input:focus,select:focus{
  outline:none; border-color:var(--accent);
  box-shadow:0 0 0 3px rgba(255,154,31,.25);
}
.help{ font-size:12px; color:var(--muted); margin-top:6px; }
.actions{ display:flex; gap:10px; margin-top:14px; flex-wrap:wrap; }
button{
  padding:12px 14px; font-size:14px; border-radius:12px;
  border:1px solid var(--line); background:transparent;
  color:var(--text); cursor:pointer;
}
button.primary{
  background:linear-gradient(180deg,#ffb14a,#ff9a1f);
  color:#000; border:none; font-weight:700;
}
.totals{ display:grid; grid-template-columns:1fr 1fr; gap:12px; }
@media(max-width:600px){ .totals{ grid-template-columns:1fr; } }
.kpi{ padding:14px; border-radius:14px; border:1px dashed var(--line); }
.kpi .t{ font-size:12px; color:var(--muted); }
.kpi .v{ margin-top:6px; font-size:20px; font-weight:800; }
.kpi.total{ border-style:solid; background:rgba(31,157,106,.12); }
.kpi.total .v{ color:var(--ok); font-size:24px; }
.note{ margin-top:12px; font-size:12px; padding:10px; border-radius:12px; border:1px solid var(--line); color:var(--muted); }

/* Cliente/Promotor */
.fieldline{ display:flex; gap:10px; align-items:stretch; }
.fieldline > div{ flex:1; }
.btnPlus{
  width:48px; min-width:48px;
  border-radius:12px; border:1px solid var(--line);
  background:rgba(255,154,31,.12);
  cursor:pointer; font-weight:900;
}
.btnPlus:hover{ background:rgba(255,154,31,.22); }

/* Modales */
.modalBack{
  position:fixed; inset:0;
  background:rgba(0,0,0,.55);
  display:none; align-items:center; justify-content:center;
  padding:16px; z-index:9999;
}
.modal{
  width:min(760px, 100%);
  background:var(--card); color:var(--text);
  border-radius:16px; border:1px solid var(--line);
  overflow:hidden; box-shadow:var(--shadow);
}
.modalHeader{
  display:flex; justify-content:space-between; align-items:center;
  padding:14px 16px;
  background:linear-gradient(180deg,#ffb14a,#ff9a1f);
  color:#000; font-weight:800;
}
.modalBody{ padding:16px; }
.modalFooter{
  padding:14px 16px; display:flex; gap:10px;
  justify-content:flex-end; border-top:1px solid var(--line);
}
.mgrid{ display:grid; grid-template-columns:1fr 1fr; gap:12px; }
@media(max-width:700px){ .mgrid{ grid-template-columns:1fr; } }
.mlabel{ font-size:12px; color:var(--muted); margin-bottom:6px; display:block; }
.minput, .mselect{
  width:100%; padding:12px;
  border-radius:12px; border:1px solid var(--line);
  background:transparent; color:var(--text);
}
.xbtn{
  border:0; background:rgba(0,0,0,.18); color:#000;
  width:36px; height:36px; border-radius:12px;
  cursor:pointer; font-weight:900;
}
.btn{
  padding:11px 14px; border-radius:12px;
  border:1px solid var(--line); background:transparent;
  cursor:pointer;
}
.btn.primary{ background:#101826; color:#fff; border:0; font-weight:800; }
.msg{ font-size:12px; margin-top:10px; color:var(--muted); }
.tabs{ display:flex; gap:8px; margin-bottom:12px; flex-wrap:wrap; }
.tab{
  padding:8px 10px; border-radius:999px;
  border:1px solid var(--line); cursor:pointer;
  user-select:none; font-size:12px;
}
.tab.active{
  background:rgba(255,154,31,.18);
  border-color:rgba(255,154,31,.55);
  font-weight:800;
}
</style>
</head>

<body>
<div class="wrap">
<header>
  <h1>Cotizador de Fianza</h1>
  <span class="badge">Prima mínima $2,500</span>
</header>

<div class="grid">

<section class="card">
<h2>Datos</h2>

<div class="row">
  <div>
    <label>Promotor</label>
    <div class="fieldline">
      <div><select id="selPromotor"></select></div>
      <button type="button" class="btnPlus" id="btnAddPromotor" title="Agregar Promotor">+</button>
    </div>
    <div class="help">Catálogo: <b>catalogo_cliente_pertenece</b></div>
  </div>

  <div>
    <label>Cliente</label>
    <div class="fieldline">
      <div><select id="selCliente"></select></div>
      <button type="button" class="btnPlus" id="btnAddCliente" title="Agregar Cliente">+</button>
    </div>
    <div class="help">Tabla: <b>clientes</b></div>
  </div>
</div>

<div class="row" style="margin-top:12px;">
  <div>
    <label>Afianzadora</label>
    <select id="afianzadora" <?= count($afianzadoras)===0 ? 'disabled' : '' ?>>
      <?php if(count($afianzadoras)===0): ?>
        <option value="" selected>No hay afianzadoras registradas</option>
      <?php else: ?>
        <?php foreach($afianzadoras as $i=>$a):
          $id = (int)$a['Id_Afianzadora'];
          $nom = htmlspecialchars((string)($a['Nombre_Afianzadora'] ?? ''), ENT_QUOTES, 'UTF-8');
          $gastos = (float)($a['Gastos_de_Expedicion'] ?? 0);
        ?>
          <option value="<?= $id ?>" data-gastos="<?= $gastos ?>" <?= $i===0?'selected':'' ?>><?= $nom ?></option>
        <?php endforeach; ?>
      <?php endif; ?>
    </select>
  </div>
  <div>
    <label>Gastos de expedición</label>
    <input id="gastos" readonly value="<?= number_format($firstGastos,2,'.','') ?>">
  </div>
</div>

<div class="row">
  <div><label>Monto de fianza</label><input id="monto" value="0" inputmode="decimal" autocomplete="off"></div>
  <div><label>Tarifa (%)</label><input id="tarifa" value="1.20" inputmode="decimal" autocomplete="off"></div>
</div>

<div class="row">
  <div><label>D.I.V. (%)</label><input id="divRate" value="3.50" inputmode="decimal" autocomplete="off"></div>
  <div><label>IVA (%)</label><input id="ivaRate" value="16.00" inputmode="decimal" autocomplete="off"></div>
</div>

<div class="actions">
  <button class="primary" id="btnEjemplo" type="button">Ejemplo</button>
  <button id="btnLimpiar" type="button">Limpiar</button>
</div>

<div class="note">La prima nunca puede ser menor a <b>$2,500</b>, sin importar el monto de fianza.</div>
</section>

<section class="card">
<h2>Resultados</h2>

<div class="totals">
  <div class="kpi"><div class="t">Prima</div><div class="v" id="primaOut">$0</div></div>
  <div class="kpi"><div class="t">D.I.V.</div><div class="v" id="divOut">$0</div></div>
  <div class="kpi"><div class="t">Subtotal</div><div class="v" id="subOut">$0</div></div>
  <div class="kpi"><div class="t">IVA</div><div class="v" id="ivaOut">$0</div></div>
  <div class="kpi total"><div class="t">Total</div><div class="v" id="totalOut">$0</div></div>
</div>

<div class="note" style="margin-top:14px;">
<b>Cliente:</b> <span id="clienteLabel">—</span><br>
<b>Promotor:</b> <span id="promotorLabel">—</span><br>
<b>Afianzadora:</b> <span id="afianzadoraLabel">—</span>
</div>

</section>

</div>
</div>

<!-- MODAL PROMOTOR -->
<div class="modalBack" id="modalPromotorBack">
  <div class="modal">
    <div class="modalHeader">
      <div>Agregar Promotor</div>
      <button class="xbtn" type="button" onclick="closeModal('modalPromotorBack')">✕</button>
    </div>
    <div class="modalBody">
      <label class="mlabel">Nombre de Promotor</label>
      <input class="minput" id="inpPromotor" placeholder="Ej. Juan Pérez / Oficina QRO / etc">
      <div class="msg" id="msgPromotor"></div>
    </div>
    <div class="modalFooter">
      <button class="btn" type="button" onclick="closeModal('modalPromotorBack')">Cancelar</button>
      <button class="btn primary" type="button" id="btnSavePromotor">Guardar</button>
    </div>
  </div>
</div>

<!-- MODAL CLIENTE -->
<div class="modalBack" id="modalClienteBack">
  <div class="modal">
    <div class="modalHeader">
      <div>Agregar Cliente</div>
      <button class="xbtn" type="button" onclick="closeModal('modalClienteBack')">✕</button>
    </div>
    <div class="modalBody">
      <div class="tabs">
        <div class="tab active" id="tabFisica" onclick="setTipoPersona('fisica')">Persona Física</div>
        <div class="tab" id="tabMoral" onclick="setTipoPersona('moral')">Persona Moral</div>
      </div>
      <input type="hidden" id="tipoPersona" value="fisica">

      <div class="mgrid">
        <div>
          <label class="mlabel">Promotor (se guardará ligado)</label>
          <select class="mselect" id="cliPromotor"></select>
        </div>
        <div>
          <label class="mlabel">RFC</label>
          <input class="minput" id="cliRFC" placeholder="RFC">
        </div>

        <div id="boxFisicaA">
          <label class="mlabel">Nombre(s)</label>
          <input class="minput" id="cliNombre" placeholder="Nombre(s)">
        </div>
        <div id="boxFisicaB">
          <label class="mlabel">Apellido Paterno</label>
          <input class="minput" id="cliAP" placeholder="Apellido paterno">
        </div>
        <div id="boxFisicaC">
          <label class="mlabel">Apellido Materno</label>
          <input class="minput" id="cliAM" placeholder="Apellido materno">
        </div>

        <div id="boxMoralA" style="display:none;">
          <label class="mlabel">Razón social</label>
          <input class="minput" id="cliRazon" placeholder="Razón social">
        </div>
        <div id="boxMoralB" style="display:none;">
          <label class="mlabel">Nombre de contacto</label>
          <input class="minput" id="cliContacto" placeholder="Contacto (opcional)">
        </div>

        <div>
          <label class="mlabel">Celular</label>
          <input class="minput" id="cliCel" placeholder="10 dígitos">
        </div>
        <div>
          <label class="mlabel">Correo</label>
          <input class="minput" id="cliCorreo" placeholder="correo@dominio.com">
        </div>

        <div style="grid-column:1/-1;">
          <label class="mlabel">Observaciones</label>
          <input class="minput" id="cliObs" placeholder="Notas internas (opcional)">
        </div>
      </div>

      <div class="msg" id="msgCliente"></div>
    </div>
    <div class="modalFooter">
      <button class="btn" type="button" onclick="closeModal('modalClienteBack')">Cancelar</button>
      <button class="btn primary" type="button" id="btnSaveCliente">Guardar</button>
    </div>
  </div>
</div>

<script>
(function(){
  const hour = new Date().getHours();
  if(hour >= 19 || hour < 6) document.body.classList.add('dark');
})();

const MIN_PRIMA = 2500;
const mxn = new Intl.NumberFormat('es-MX',{style:'currency',currency:'MXN'});
const num = new Intl.NumberFormat('es-MX',{minimumFractionDigits:2, maximumFractionDigits:2});
const $ = id=>document.getElementById(id);

function parseNum(v){ return Number(String(v).replace(/[^0-9.]/g,''))||0; }
function openModal(id){ $(id).style.display='flex'; }
function closeModal(id){ $(id).style.display='none'; }

function setTipoPersona(t){
  $('tipoPersona').value=t;
  $('tabFisica').classList.toggle('active', t==='fisica');
  $('tabMoral').classList.toggle('active', t==='moral');
  const fis = (t==='fisica');
  $('boxFisicaA').style.display = fis ? '' : 'none';
  $('boxFisicaB').style.display = fis ? '' : 'none';
  $('boxFisicaC').style.display = fis ? '' : 'none';
  $('boxMoralA').style.display = !fis ? '' : 'none';
  $('boxMoralB').style.display = !fis ? '' : 'none';
}

async function fetchJSON(url, opts){
  const r = await fetch(url, opts);
  return await r.json();
}
function fillSelect(sel, items, placeholder){
  sel.innerHTML='';
  const opt0=document.createElement('option');
  opt0.value=''; opt0.textContent=placeholder||'Seleccione...';
  opt0.disabled=true; opt0.selected=true;
  sel.appendChild(opt0);
  (items||[]).forEach(it=>{
    const o=document.createElement('option');
    o.value=it.id; o.textContent=it.text;
    sel.appendChild(o);
  });
}
function updateLabels(){
  const sp=$('selPromotor'), sc=$('selCliente'), sa=$('afianzadora');
  $('promotorLabel').textContent = sp && sp.value ? (sp.options[sp.selectedIndex]?.textContent||'—'):'—';
  $('clienteLabel').textContent  = sc && sc.value ? (sc.options[sc.selectedIndex]?.textContent||'—'):'—';
  $('afianzadoraLabel').textContent = sa && sa.value ? (sa.options[sa.selectedIndex]?.textContent||'—'):'—';
}

async function loadPromotores(){
  const js = await fetchJSON("index.php?ajax=get_promotores");
  if(!js.ok) throw new Error(js.msg||'Error promotores');
  fillSelect($('selPromotor'), js.data, "Seleccione promotor...");
  fillSelect($('cliPromotor'), js.data, "Seleccione promotor...");
}
async function loadClientes(){
  const js = await fetchJSON("index.php?ajax=get_clientes");
  if(!js.ok) throw new Error(js.msg||'Error clientes');
  fillSelect($('selCliente'), js.data, "Seleccione cliente...");
}

$('btnAddPromotor').onclick = ()=>{
  $('inpPromotor').value='';
  $('msgPromotor').textContent='';
  openModal('modalPromotorBack');
};
$('btnSavePromotor').onclick = async ()=>{
  const msg=$('msgPromotor');
  msg.textContent='Guardando...';
  try{
    const fd=new FormData();
    fd.append('promotor', $('inpPromotor').value.trim());
    const js=await fetchJSON("index.php?ajax=insert_promotor",{method:'POST',body:fd});
    if(!js.ok) throw new Error(js.msg||'No se pudo guardar');
    await loadPromotores();
    $('selPromotor').value = js.id;
    $('cliPromotor').value = js.id;
    closeModal('modalPromotorBack');
    updateLabels();
  }catch(e){
    msg.textContent="Error: "+e.message;
  }
};

$('btnAddCliente').onclick = ()=>{
  $('msgCliente').textContent='';
  const promSel=$('selPromotor').value;
  if(promSel) $('cliPromotor').value=promSel;
  openModal('modalClienteBack');
};
$('btnSaveCliente').onclick = async ()=>{
  const msg=$('msgCliente');
  msg.textContent='Guardando...';
  try{
    const fd=new FormData();
    fd.append('tipo_persona', $('tipoPersona').value);
    fd.append('id_fk_catalogo_cliente_pertenece', $('cliPromotor').value||0);
    fd.append('rfc', $('cliRFC').value.trim());
    fd.append('correo_1', $('cliCorreo').value.trim());
    fd.append('no_de_celular', $('cliCel').value.trim());
    fd.append('observaciones_y_notas', $('cliObs').value.trim());
    fd.append('nombre_completo', $('cliNombre').value.trim());
    fd.append('apellido_paterno', $('cliAP').value.trim());
    fd.append('apellido_materno', $('cliAM').value.trim());
    fd.append('razon_social_persona_moral', $('cliRazon').value.trim());
    fd.append('nombre_de_contacto_persona_moral', $('cliContacto').value.trim());

    const js=await fetchJSON("index.php?ajax=insert_cliente",{method:'POST',body:fd});
    if(!js.ok) throw new Error(js.msg||'No se pudo guardar');

    await loadClientes();
    $('selCliente').value = js.id;
    closeModal('modalClienteBack');
    updateLabels();
  }catch(e){
    msg.textContent="Error: "+e.message;
  }
};

$('selPromotor').onchange = updateLabels;
$('selCliente').onchange = updateLabels;

function setGastosFromAfianzadora(){
  const sel=$('afianzadora');
  if(!sel || sel.disabled) return;
  const opt=sel.options[sel.selectedIndex];
  const gastos = opt ? parseNum(opt.getAttribute('data-gastos')||'0') : 0;
  $('gastos').value = num.format(gastos);
  updateLabels();
}
$('afianzadora') && ($('afianzadora').onchange = ()=>{ setGastosFromAfianzadora(); calc(); });

function calc(){
  const monto=parseNum($('monto').value);
  const tarifa=parseNum($('tarifa').value)/100;
  const divP=parseNum($('divRate').value)/100;
  const ivaP=parseNum($('ivaRate').value)/100;
  const gastos=parseNum($('gastos').value);

  let prima=monto*tarifa;
  if(prima>0 && prima<MIN_PRIMA) prima=MIN_PRIMA;
  if(monto<=0) prima=0;

  const div=prima*divP;
  const sub=prima+div+gastos;
  const iva=sub*ivaP;
  const total=sub+iva;

  $('primaOut').textContent=mxn.format(prima);
  $('divOut').textContent=mxn.format(div);
  $('subOut').textContent=mxn.format(sub);
  $('ivaOut').textContent=mxn.format(iva);
  $('totalOut').textContent=mxn.format(total);
}

['monto','tarifa','divRate','ivaRate'].forEach(id=> $(id).oninput=calc);

$('btnEjemplo').onclick=()=>{
  $('monto').value=num.format(208333.33);
  setGastosFromAfianzadora();
  calc();
};
$('btnLimpiar').onclick=()=>{
  $('monto').value='0';
  calc();
};

(async ()=>{
  try{
    await loadPromotores();
    await loadClientes();
  }catch(e){
    console.error(e);
  }
  setGastosFromAfianzadora();
  updateLabels();
  calc();
})();
</script>
</body>
</html>
