<?php
$title='Editar cliente';
require_once __DIR__ . '/../inc/header.php';
$pdo=db();
$id=(int)($_GET['id']??0);

$st=$pdo->prepare("SELECT * FROM clients WHERE id=?");
$st->execute([$id]);
$client=$st->fetch();
if(!$client){ http_response_code(404); exit('Cliente no encontrado'); }

if($_SERVER['REQUEST_METHOD']==='POST'){
  csrf_check();
  $nombre=trim($_POST['nombre']??'');
  if($nombre===''){ flash_set('danger','El nombre es obligatorio.'); redirect('clientes/edit.php?id='.$id); }

  $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']??'');

  $pdo->prepare("UPDATE clients SET nombre=?, apellidos=?, direccion=?, postal_code=?, localidad=?, provincia=?, nif_cif=?, telefono=? WHERE id=?")
      ->execute([$nombre,$apellidos,$direccion,$postal?:null,$localidad?:null,$provincia?:null,$nif?:null,$tel?:null,$id]);

  flash_set('success','Cliente actualizado.');
  redirect('clientes/view.php?id='.$id);
}

?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="mb-0">Editar cliente</h4>
    <div class="text-muted">Nº cliente: <?= h($client['customer_no'] ?? '') ?></div>
  </div>
  <div class="d-flex gap-2">
    <a class="btn btn-outline-secondary" href="<?= url('clientes/view.php?id='.$id) ?>">Volver</a>
  </div>
</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" value="<?= h($client['nombre']) ?>" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Apellidos</label>
          <input class="form-control" name="apellidos" value="<?= h($client['apellidos'] ?? '') ?>">
        </div>

        <div class="mb-2 position-relative">
          <label class="form-label">Dirección</label>
          <input class="form-control" name="direccion" id="direccion" value="<?= h($client['direccion'] ?? '') ?>">
          <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" value="<?= h($client['postal_code'] ?? '') ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label">Localidad</label>
            <input class="form-control" name="localidad" id="localidad" value="<?= h($client['localidad'] ?? '') ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label">Provincia</label>
            <input class="form-control" name="provincia" id="provincia" value="<?= h($client['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" value="<?= h($client['nif_cif'] ?? '') ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label">Teléfono</label>
            <input class="form-control" name="telefono" value="<?= h($client['telefono'] ?? '') ?>">
          </div>
        </div>

        <button class="btn btn-primary">Guardar cambios</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', ()=>{
      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();
    });
    sug.appendChild(a);
  });
  sug.style.display='block';
}
function debounceSuggest(){
  clearTimeout(t);
  t=setTimeout(async ()=>{
    const q = fullAddress();
    if(q.length < 6) { hideSug(); return; }
    try{ showSug(await searchSuggest(q)); }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'; ?>
