<?php
$title='Cliente';
require_once __DIR__ . '/../inc/header.php';
require_once __DIR__ . '/../inc/docs.php';
ensure_part2_tables();
ensure_schema_safe();

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

function phone_digits(string $p): string {
  $d = preg_replace('/[^0-9+]/','', $p);
  return $d ?: $p;
}
function whatsapp_link(string $p): string {
  $d = preg_replace('/[^0-9]/','', $p);
  if($d==='') return '#';
  // si empieza por 34 ya ok; si no, no forzamos
  return "https://wa.me/".$d;
}

// Subir archivo
if($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action']??'')==='upload_file'){
  csrf_check();
  if(!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK){
    flash_set('danger','Error al subir el archivo.');
    redirect('clientes/view.php?id='.$id);
  }
  $file=$_FILES['file'];
  if($file['size'] > 20*1024*1024){
    flash_set('danger','Archivo máximo 20MB.');
    redirect('clientes/view.php?id='.$id);
  }
  $dir = __DIR__ . '/../uploads/clients/'.$id;
  if(!is_dir($dir)) @mkdir($dir, 0775, true);
  $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
  $safe = preg_replace('/[^a-zA-Z0-9._-]/','_', pathinfo($file['name'], PATHINFO_FILENAME));
  $stored = $safe.'_'.time().($ext?'.'.$ext:'');
  $dest = $dir.'/'.$stored;
  if(!move_uploaded_file($file['tmp_name'],$dest)){
    flash_set('danger','No se pudo guardar el archivo.');
    redirect('clientes/view.php?id='.$id);
  }
  $webPath = '/uploads/clients/'.$id.'/'.$stored;
  $pdo->prepare("INSERT INTO client_files(client_id,original_name,stored_path,uploaded_by) VALUES(?,?,?,?)")
      ->execute([$id,$file['name'],$webPath,(int)(current_user()['id']??0)]);
  flash_set('success','Archivo adjuntado.');
  redirect('clientes/view.php?id='.$id);
}

// Cargar adjuntos
$fs=$pdo->prepare("SELECT * FROM client_files WHERE client_id=? ORDER BY uploaded_at DESC, id DESC");
$fs->execute([$id]);
$files=$fs->fetchAll();

// Pagos para pendientes
$pdo->exec("
  CREATE TABLE IF NOT EXISTS invoice_payments(
    id INT AUTO_INCREMENT PRIMARY KEY,
    invoice_id INT NOT NULL,
    paid_at DATE NOT NULL,
    amount DECIMAL(12,2) NOT NULL DEFAULT 0,
    note VARCHAR(255) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_inv (invoice_id),
    CONSTRAINT fk_pay_invoice FOREIGN KEY (invoice_id) REFERENCES documents(id) ON DELETE CASCADE
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

// Docs (facturas y presupuestos)
$docs=$pdo->prepare("
  SELECT d.*,
         IFNULL(p.paid_total,0) AS paid_total,
         ROUND(GREATEST(d.total - IFNULL(p.paid_total,0), 0), 2) AS pending_total
  FROM documents d
  LEFT JOIN (
     SELECT invoice_id, SUM(amount) AS paid_total
     FROM invoice_payments
     GROUP BY invoice_id
  ) p ON p.invoice_id=d.id
  WHERE d.client_id=?
  ORDER BY d.issue_date DESC, d.id DESC
");
$docs->execute([$id]);
$docRows=$docs->fetchAll();

$fact_total=0.0; $debe=0.0;
foreach($docRows as $d){
  if($d['doc_type']==='invoice'){
    $fact_total += (float)$d['total'];
    $debe += (float)$d['pending_total'];
  }
}

$telefono = trim((string)($client['telefono'] ?? ''));
$telDigits = $telefono ? phone_digits($telefono) : '';
$wa = $telefono ? whatsapp_link($telefono) : '#';
?>
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
  <div>
    <h4 class="mb-0"><?= h(trim(($client['nombre']??'').' '.($client['apellidos']??''))) ?></h4>
    <div class="text-muted">Nº cliente: <?= h($client['customer_no'] ?? '') ?></div>
  </div>
  <div class="d-flex gap-2 flex-wrap">
    <a class="btn btn-outline-secondary" href="<?= url('clientes/edit.php?id='.$id) ?>">Editar</a>
    <a class="btn btn-outline-primary" href="<?= url('presupuestos/new.php?client_id='.$id) ?>">Crear presupuesto</a>
    <a class="btn btn-primary" href="<?= url('facturas/new.php?client_id='.$id) ?>">Crear factura</a>
    <a class="btn btn-outline-secondary" href="<?= url('clientes/list.php') ?>">Volver</a>
  </div>
</div>

<div class="row g-3">
  <div class="col-lg-5">
    <div class="card shadow-sm"><div class="card-body">
      <div class="row g-2">
        <div class="col-12">
          <div class="text-muted small">Resumen</div>
          <div class="d-flex justify-content-between">
            <div><span class="text-muted small">Facturado</span><div class="fw-semibold"><?= eur($fact_total) ?></div></div>
            <div class="text-end"><span class="text-muted small">Debe</span><div class="fw-semibold <?= $debe>0?'text-warning':'text-success' ?>"><?= eur($debe) ?></div></div>
          </div>
        </div>
        <div class="col-12"><div class="text-muted small">Dirección</div><div class="fw-semibold"><?= h($client['direccion'] ?? '') ?></div></div>
        <div class="col-md-4"><div class="text-muted small">CP</div><div class="fw-semibold"><?= h($client['postal_code'] ?? '') ?></div></div>
        <div class="col-md-4"><div class="text-muted small">Localidad</div><div class="fw-semibold"><?= h($client['localidad'] ?? '') ?></div></div>
        <div class="col-md-4"><div class="text-muted small">Provincia</div><div class="fw-semibold"><?= h($client['provincia'] ?? '') ?></div></div>
        <div class="col-md-6"><div class="text-muted small">NIF/CIF</div><div class="fw-semibold"><?= h($client['nif_cif'] ?? '') ?></div></div>

        <div class="col-md-6">
          <div class="text-muted small">Teléfono</div>
          <?php if($telefono): ?>
            <div class="d-flex gap-2 flex-wrap align-items-center">
              <a class="fw-semibold text-decoration-none" href="tel:<?= h($telDigits) ?>"><?= h($telefono) ?></a>
              <a class="btn btn-sm btn-success btn-whatsapp" target="_blank" rel="noopener" href="<?= h($wa) ?>">WhatsApp</a>
            </div>
          <?php else: ?>
            <div class="fw-semibold text-muted">—</div>
          <?php endif; ?>
        </div>
      </div>
    </div></div>

    <?php require __DIR__ . '/../inc/client_map_widget.php'; ?>
  </div>

  <div class="col-lg-7">
    <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">Documentos</h6>
        <span class="text-muted small">Facturas y presupuestos del cliente</span>
      </div>
      <div class="table-responsive">
        <table class="table table-sm align-middle">
          <thead>
            <tr>
              <th>Tipo</th><th>Código</th><th>Fecha</th>
              <th class="text-end">Total</th>
              <th class="text-end">Pendiente</th>
              <th class="text-end"></th>
            </tr>
          </thead>
          <tbody>
            <?php foreach($docRows as $d): ?>
              <tr>
                <td><?= $d['doc_type']==='invoice'?'Factura':'Presupuesto' ?></td>
                <td class="fw-semibold"><?= h($d['doc_code']) ?></td>
                <td><?= h($d['issue_date']) ?></td>
                <td class="text-end"><?= eur($d['total']) ?></td>
                <td class="text-end">
                  <?php if($d['doc_type']!=='invoice'): ?>
                    <span class="text-muted">—</span>
                  <?php else: ?>
                    <?php $pend=(float)$d['pending_total']; ?>
                    <span class="badge <?= $pend>0?'text-bg-warning':'text-bg-success' ?>"><?= eur($pend) ?></span>
                  <?php endif; ?>
                </td>
                <td class="text-end">
                  <?php if($d['doc_type']==='invoice'): ?>
                    <a class="btn btn-sm btn-outline-secondary" href="<?= url('facturas/edit.php?id='.(int)$d['id']) ?>">Ver</a>
                  <?php else: ?>
                    <a class="btn btn-sm btn-outline-secondary" href="<?= url('presupuestos/edit.php?id='.(int)$d['id']) ?>">Ver</a>
                    <a class="btn btn-sm btn-outline-primary" target="_blank" href="<?= url('presupuestos/pdf.php?id='.(int)$d['id']) ?>">PDF</a>
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; ?>
            <?php if(count($docRows)===0): ?>
              <tr><td colspan="6" class="text-muted">Aún no hay documentos.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div></div>

    <div class="card shadow-sm mt-3"><div class="card-body">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <h6 class="mb-0">Archivos del cliente</h6>
        <span class="text-muted small">Adjunta contratos, fotos, etc.</span>
      </div>

      <form method="post" enctype="multipart/form-data" class="d-flex gap-2 align-items-end mb-3 flex-wrap">
        <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
        <input type="hidden" name="action" value="upload_file">
        <div class="flex-grow-1" style="min-width:240px">
          <input class="form-control" type="file" name="file" required>
          <div class="form-text">Máx 20MB.</div>
        </div>
        <button class="btn btn-primary">Subir</button>
      </form>

      <div class="table-responsive">
        <table class="table table-sm align-middle">
          <thead><tr><th>Archivo</th><th>Fecha</th><th class="text-end">Acciones</th></tr></thead>
          <tbody>
            <?php foreach($files as $f): ?>
              <tr>
                <td><a target="_blank" href="<?= h($f['stored_path']) ?>"><?= h($f['original_name']) ?></a></td>
                <td><?= h($f['uploaded_at']) ?></td>
                <td class="text-end">
                  <form method="post" action="<?= url('clientes/files_delete.php?id='.(int)$f['id'].'&client_id='.$id) ?>"
                        onsubmit="return confirm('¿Eliminar este archivo?');" style="display:inline">
                    <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                    <button class="btn btn-sm btn-outline-danger">Eliminar</button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
            <?php if(count($files)===0): ?>
              <tr><td colspan="3" class="text-muted">Sin archivos adjuntos.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div></div>
  </div>
</div>

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