<?php
$title='Nuevo cliente';
require_once __DIR__ . '/../inc/header.php';

$pdo=db();
ensure_schema_safe();

// Detect column name reliably on each request
$ccol = client_customer_col();
$prefill_customer = $ccol ? generate_customer_no() : '';

if($_SERVER['REQUEST_METHOD']==='POST'){
  csrf_check();

  $nombre = trim((string)($_POST['nombre'] ?? ''));
  if($nombre===''){
    flash_set('danger','El nombre es obligatorio.');
    redirect('clientes/new.php');
  }

  $apellidos = trim((string)($_POST['apellidos'] ?? ''));
  $direccion = trim((string)($_POST['direccion'] ?? ''));
  $nif_cif   = trim((string)($_POST['nif_cif'] ?? ''));
  $telefono  = trim((string)($_POST['telefono'] ?? ''));
  $postal_code = trim((string)($_POST['postal_code'] ?? ''));
  $localidad = trim((string)($_POST['localidad'] ?? ''));
  $provincia = trim((string)($_POST['provincia'] ?? ''));

  // Re-detect to avoid edge cases with sessions
  $ccol = client_customer_col();
  $cval = null;

  if($ccol){
    // IMPORTANT: do NOT rely on readonly field being posted; always generate if empty.
    $posted = trim((string)($_POST['customer_no'] ?? ''));
    $cval = $posted !== '' ? $posted : generate_customer_no();

    $sql = "INSERT INTO clients(`$ccol`,nombre,apellidos,direccion,nif_cif,telefono,postal_code,localidad,provincia)
            VALUES(?,?,?,?,?,?,?,?,?)";
    $st=$pdo->prepare($sql);
    $st->execute([$cval,$nombre,$apellidos?:null,$direccion?:null,$nif_cif?:null,$telefono?:null,$postal_code?:null,$localidad?:null,$provincia?:null]);
  } else {
    $st=$pdo->prepare("INSERT INTO clients(nombre,apellidos,direccion,nif_cif,telefono,postal_code,localidad,provincia)
                       VALUES(?,?,?,?,?,?,?,?)");
    $st->execute([$nombre,$apellidos?:null,$direccion?:null,$nif_cif?:null,$telefono?:null,$postal_code?:null,$localidad?:null,$provincia?:null]);
  }

  $new_id = (int)$pdo->lastInsertId();
  flash_set('success','Cliente creado.');
  redirect('clientes/view.php?id='.$new_id);
}
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="mb-0">Nuevo cliente</h4>
    <div class="text-muted">Rellena lo que tengas: solo el nombre es obligatorio.</div>
  </div>
  <a class="btn btn-outline-secondary" href="<?= url('clientes/list.php') ?>">Volver</a>
</div>

<div class="row g-3">
  <div class="col-lg-7">
    <div class="card shadow-sm">
      <div class="card-body">
        <form method="post" class="row g-3" autocomplete="off">
          <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
          <?php if($ccol): ?>
            <div class="col-12">
              <label class="form-label">Código cliente (auto)</label>
              <input class="form-control" name="customer_no" id="customer_no" value="<?= h($prefill_customer) ?>" readonly>
            </div>
          <?php endif; ?>

          <div class="col-md-6">
            <label class="form-label">Nombre *</label>
            <input class="form-control" name="nombre" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Apellidos</label>
            <input class="form-control" name="apellidos">
          </div>

          <div class="col-12 position-relative">
            <label class="form-label">Dirección</label>
            <input class="form-control" name="direccion" id="direccion" placeholder="Calle, número..." autocomplete="off">
            <div id="addr_suggestions" class="list-group position-absolute w-100 shadow-sm" style="z-index:20; display:none; max-height:220px; overflow:auto;"></div>
            <div class="form-text">Sugerencias (OpenStreetMap).</div>
          </div>

          <div class="col-md-4">
            <label class="form-label">Código postal</label>
            <input class="form-control" name="postal_code" id="postal_code">
          </div>
          <div class="col-md-4">
            <label class="form-label">Localidad</label>
            <input class="form-control" name="localidad" id="localidad">
          </div>
          <div class="col-md-4">
            <label class="form-label">Provincia</label>
            <input class="form-control" name="provincia" id="provincia">
          </div>

          <div class="col-md-6">
            <label class="form-label">NIF/CIF</label>
            <input class="form-control" name="nif_cif">
          </div>
          <div class="col-md-6">
            <label class="form-label">Teléfono</label>
            <input class="form-control" name="telefono" placeholder="+34...">
          </div>

          <div class="col-12 d-flex gap-2 flex-wrap">
            <button class="btn btn-primary">Crear</button>
            <button type="button" class="btn btn-outline-secondary" id="btn_preview_map">Ver en mapa</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <div class="col-lg-5">
    <div class="card shadow-sm">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-center mb-2">
          <h6 class="mb-0">Mapa</h6>
          <a id="gmaps_link" class="btn btn-sm btn-outline-primary" target="_blank" rel="noopener">Abrir en Google Maps</a>
        </div>
        <div class="ratio ratio-4x3">
          <iframe id="map_iframe" title="Mapa" loading="lazy" referrerpolicy="no-referrer-when-downgrade"
                  src="https://www.openstreetmap.org/export/embed.html?bbox=-3.703%2C40.416%2C-3.703%2C40.416&layer=mapnik&marker=40.416%2C-3.703"></iframe>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
(function(){
  const addr = document.getElementById('direccion');
  const sugg = document.getElementById('addr_suggestions');
  const pc = document.getElementById('postal_code');
  const loc = document.getElementById('localidad');
  const prov = document.getElementById('provincia');
  const iframe = document.getElementById('map_iframe');
  const gmaps = document.getElementById('gmaps_link');
  const btnPreview = document.getElementById('btn_preview_map');

  const NOMINATIM = <?= json_encode(defined('NOMINATIM_ENDPOINT') ? NOMINATIM_ENDPOINT : 'https://nominatim.openstreetmap.org/search?format=json&limit=5&addressdetails=1&q=') ?>;
  let t = null;

  function hide(){ sugg.style.display='none'; sugg.innerHTML=''; }
  function setMap(lat, lon){
    const bbox = (lon-0.01) + ',' + (lat-0.01) + ',' + (lon+0.01) + ',' + (lat+0.01);
    iframe.src = 'https://www.openstreetmap.org/export/embed.html?bbox=' + encodeURIComponent(bbox) + '&layer=mapnik&marker=' + encodeURIComponent(lat + ',' + lon);
    gmaps.href = 'https://www.google.com/maps/search/?api=1&query=' + encodeURIComponent(lat + ',' + lon);
  }
  function fillFromAddressDetails(ad){
    if(ad.postcode && !pc.value) pc.value = ad.postcode;
    const city = ad.city || ad.town || ad.village || ad.municipality;
    if(city && !loc.value) loc.value = city;
    const state = ad.state || ad.province || ad.region;
    if(state && !prov.value) prov.value = state;
  }

  async function search(q){
    const url = NOMINATIM + encodeURIComponent(q);
    const res = await fetch(url, {headers: {'Accept':'application/json'}});
    if(!res.ok) return [];
    const data = await res.json();
    return Array.isArray(data) ? data : [];
  }

  function render(items){
    sugg.innerHTML='';
    if(!items.length){ hide(); return; }
    items.slice(0,5).forEach(it=>{
      const a = document.createElement('button');
      a.type='button';
      a.className='list-group-item list-group-item-action';
      a.textContent = it.display_name;
      a.onclick = ()=>{
        addr.value = it.display_name;
        hide();
        const lat = parseFloat(it.lat), lon = parseFloat(it.lon);
        if(!isNaN(lat) && !isNaN(lon)) setMap(lat, lon);
        if(it.address) fillFromAddressDetails(it.address);
      };
      sugg.appendChild(a);
    });
    sugg.style.display='block';
  }

  addr.addEventListener('input', ()=>{
    clearTimeout(t);
    const q = addr.value.trim();
    if(q.length < 4){ hide(); return; }
    t = setTimeout(async ()=>{
      try{ render(await search(q)); }catch(e){ hide(); }
    }, 250);
  });

  document.addEventListener('click', (e)=>{
    if(!sugg.contains(e.target) && e.target !== addr) hide();
  });

  btnPreview.addEventListener('click', async ()=>{
    const q = addr.value.trim();
    if(q.length < 4) return;
    try{
      const items = await search(q);
      if(items[0]){
        const it = items[0];
        const lat = parseFloat(it.lat), lon = parseFloat(it.lon);
        if(!isNaN(lat) && !isNaN(lon)) setMap(lat, lon);
        if(it.address) fillFromAddressDetails(it.address);
      }
    }catch(e){}
  });
})();
</script>

<?php require_once __DIR__ . '/../inc/footer.php'; ?>
