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

if($_SERVER['REQUEST_METHOD']==='POST'){
  csrf_check();
  $nombre=trim($_POST['nombre']??'');
  $apellidos=trim($_POST['apellidos']??'');
  $direccion=trim($_POST['direccion']??'');
  $postal=trim($_POST['postal_code']??'');
  $localidad=trim($_POST['localidad']??'');
  $provincia=trim($_POST['provincia']??'');
  $nif=trim($_POST['nif_cif']??'');
  $tel=trim($_POST['telefono']??'');

  if($nombre===''){ flash_set('danger','El nombre es obligatorio.'); redirect('clientes/new.php'); }

  // número aleatorio
  $num = random_int(100000, 999999);

  $st=$pdo->prepare("INSERT INTO clients(customer_no,nombre,apellidos,direccion,postal_code,localidad,provincia,nif_cif,telefono)
                     VALUES(?,?,?,?,?,?,?,?,?)");
  $st->execute([$num,$nombre,$apellidos,$direccion,$postal?:null,$localidad?:null,$provincia?:null,$nif?:null,$tel?:null]);

  flash_set('success','Cliente creado.');
  redirect('clientes/list.php');
}

$client=['nombre'=>'','apellidos'=>'','direccion'=>'','postal_code'=>'','localidad'=>'','provincia'=>'','nif_cif'=>'','telefono'=>''];
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="mb-0">Nuevo cliente</h4>
    <div class="text-muted">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-6">
    <div class="card shadow-sm"><div class="card-body">
      <form method="post" autocomplete="off">
        <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">

        <div class="mb-3">
          <label class="form-label">Nombre *</label>
          <input class="form-control" name="nombre" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Apellidos</label>
          <input class="form-control" name="apellidos">
        </div>

        <div class="mb-2">
          <label class="form-label">Dirección</label>
          <input class="form-control" name="direccion" id="direccion" placeholder="Calle, número...">
          <div id="addrSug" class="list-group position-absolute" style="z-index:9999; display:none; max-height:220px; overflow:auto;"></div>
        </div>
        <div class="row g-2 mb-3">
          <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>

        <div class="row g-2 mb-3">
          <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">
          </div>
        </div>

        <button class="btn btn-primary">Guardar</button>
      </form>
    </div></div>
  </div>

  <div class="col-lg-6">
    <?php require __DIR__ . '/../inc/client_map_widget.php'; ?>
  </div>
</div>

<script>
const dirEl = document.getElementById('direccion');
const cpEl  = document.getElementById('postal_code');
const locEl = document.getElementById('localidad');
const provEl= document.getElementById('provincia');
const sug   = document.getElementById('addrSug');

let t=null;
function fullAddress(){
  return [dirEl.value, cpEl.value, locEl.value, provEl.value].map(s=>s.trim()).filter(Boolean).join(', ');
}

async function searchSuggest(q){
  const url = 'https://nominatim.openstreetmap.org/search?format=json&addressdetails=1&limit=6&q='+encodeURIComponent(q);
  const res = await fetch(url, {headers:{'Accept':'application/json'}});
  return await res.json();
}

function hideSug(){ sug.style.display='none'; sug.innerHTML=''; }

function showSug(items){
  if(!items || items.length===0){ hideSug(); return; }
  sug.innerHTML='';
  items.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.addEventListener('click', ()=>{
      // rellenar con algo razonable
      dirEl.value = it.address?.road ? ((it.address.road||'') + (it.address.house_number?(' '+it.address.house_number):'')) : dirEl.value;
      cpEl.value  = it.address?.postcode || cpEl.value;
      locEl.value = it.address?.city || it.address?.town || it.address?.village || locEl.value;
      provEl.value= it.address?.state || provEl.value;
      hideSug();
      // recargar mapa por reinicio simple
      location.hash = '#map';
      location.reload();
    });
    sug.appendChild(a);
  });
  sug.style.display='block';
}

function debounceSuggest(){
  clearTimeout(t);
  t=setTimeout(async ()=>{
    const q = fullAddress();
    if(q.length < 6) { hideSug(); return; }
    try{
      const data=await searchSuggest(q);
      showSug(data);
    }catch(e){ hideSug(); }
  }, 450);
}

[dirEl,cpEl,locEl,provEl].forEach(el=>{
  el.addEventListener('input', debounceSuggest);
});
document.addEventListener('click', (e)=>{
  if(!sug.contains(e.target) && e.target!==dirEl) hideSug();
});
</script>

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