<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Coarca — Registro de Facturas</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body { font-family: 'Inter', sans-serif; background: #f5f5f5; color: #1a1a1a; min-height: 100vh; }

  .header {
    background: #1e293b;
    color: #fff;
    padding: 16px 24px;
    display: flex;
    align-items: center;
    gap: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,.2);
  }
  .header h1 { font-size: 1.25rem; font-weight: 600; }
  .header span { font-size: .8rem; color: #94a3b8; }

  .container { max-width: 900px; margin: 32px auto; padding: 0 16px; }

  .card {
    background: #fff;
    border-radius: 12px;
    padding: 28px;
    box-shadow: 0 1px 4px rgba(0,0,0,.08);
    margin-bottom: 24px;
  }
  .card h2 { font-size: 1rem; font-weight: 600; margin-bottom: 20px; color: #334155; }

  .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
  .form-group { display: flex; flex-direction: column; gap: 6px; }
  .form-group.full { grid-column: 1 / -1; }
  label { font-size: .82rem; font-weight: 500; color: #64748b; }
  input, select, textarea {
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 10px 12px;
    font-size: .9rem;
    font-family: inherit;
    transition: border-color .2s;
    background: #f8fafc;
  }
  input:focus, select:focus, textarea:focus {
    outline: none;
    border-color: #3b82f6;
    background: #fff;
  }

  .upload-zone {
    border: 2px dashed #cbd5e1;
    border-radius: 10px;
    padding: 36px;
    text-align: center;
    cursor: pointer;
    transition: all .2s;
    background: #f8fafc;
  }
  .upload-zone:hover, .upload-zone.drag-over {
    border-color: #3b82f6;
    background: #eff6ff;
  }
  .upload-zone svg { color: #94a3b8; margin-bottom: 10px; }
  .upload-zone p { font-size: .88rem; color: #64748b; }
  .upload-zone strong { color: #3b82f6; }
  #fileInput { display: none; }

  .preview-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 10px;
    margin-top: 16px;
  }
  .preview-item {
    position: relative;
    border-radius: 8px;
    overflow: hidden;
    aspect-ratio: 1;
    background: #e2e8f0;
  }
  .preview-item img { width: 100%; height: 100%; object-fit: cover; }
  .preview-item .remove-btn {
    position: absolute;
    top: 4px; right: 4px;
    background: rgba(0,0,0,.6);
    color: #fff;
    border: none;
    border-radius: 50%;
    width: 22px; height: 22px;
    cursor: pointer;
    font-size: .75rem;
    display: flex; align-items: center; justify-content: center;
  }
  .preview-item .file-name {
    position: absolute;
    bottom: 0; left: 0; right: 0;
    background: rgba(0,0,0,.5);
    color: #fff;
    font-size: .65rem;
    padding: 3px 5px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 12px 24px;
    border-radius: 8px;
    border: none;
    cursor: pointer;
    font-size: .9rem;
    font-weight: 600;
    font-family: inherit;
    transition: all .2s;
  }
  .btn-primary { background: #3b82f6; color: #fff; }
  .btn-primary:hover { background: #2563eb; }
  .btn-primary:disabled { background: #93c5fd; cursor: not-allowed; }

  .status-bar {
    display: none;
    align-items: center;
    gap: 10px;
    padding: 12px 16px;
    border-radius: 8px;
    font-size: .88rem;
    margin-top: 16px;
  }
  .status-bar.success { display: flex; background: #f0fdf4; color: #15803d; border: 1px solid #bbf7d0; }
  .status-bar.error   { display: flex; background: #fef2f2; color: #dc2626; border: 1px solid #fecaca; }
  .status-bar.loading { display: flex; background: #eff6ff; color: #1d4ed8; border: 1px solid #bfdbfe; }

  .spinner {
    width: 16px; height: 16px;
    border: 2px solid #93c5fd;
    border-top-color: #1d4ed8;
    border-radius: 50%;
    animation: spin .8s linear infinite;
  }
  @keyframes spin { to { transform: rotate(360deg); } }

  .google-auth-banner {
    background: #fefce8;
    border: 1px solid #fde047;
    border-radius: 10px;
    padding: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
    font-size: .88rem;
    color: #713f12;
  }
  .btn-google {
    background: #fff;
    border: 1px solid #e2e8f0;
    color: #1a1a1a;
    padding: 8px 16px;
    font-size: .85rem;
  }
  .btn-google:hover { background: #f8fafc; }
</style>
</head>
<body>

<div class="header">
  <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#60a5fa" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
    <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
    <polyline points="14 2 14 8 20 8"/>
    <line x1="16" y1="13" x2="8" y2="13"/>
    <line x1="16" y1="17" x2="8" y2="17"/>
    <polyline points="10 9 9 9 8 9"/>
  </svg>
  <div>
    <h1>Coarca — Registro de Facturas</h1>
    <span>Sube facturas o pedidos → PDF → Google Drive</span>
  </div>
</div>

<div class="container">

  <?php
  require_once __DIR__ . '/config/config.php';
  $googleConnected = file_exists(COARCA_ROOT . '/config/google-token.json');
  if (!$googleConnected): ?>
  <div class="google-auth-banner">
    <span>⚠️ Cuenta Google no conectada. Conecta para activar Google Drive.</span>
    <a href="api/google-auth.php" class="btn btn-google">
      <svg width="16" height="16" viewBox="0 0 48 48"><path fill="#EA4335" d="M24 9.5c3.9 0 6.6 1.7 8.1 3.1l6-6C34.7 3.1 29.8 1 24 1 14.8 1 7 6.7 3.7 14.6l7 5.4C12.3 13.9 17.7 9.5 24 9.5z"/><path fill="#4285F4" d="M46.1 24.5c0-1.6-.1-2.8-.4-4H24v7.6h12.5c-.5 2.9-2.2 5.4-4.7 7l7.3 5.7c4.3-3.9 6.8-9.7 7-16.3z"/><path fill="#FBBC05" d="M10.7 28.8A14.7 14.7 0 0 1 9.5 24c0-1.7.3-3.3.8-4.8L3.4 14c-1.5 3-2.4 6.4-2.4 10s.9 7 2.4 10l7.3-5.2z"/><path fill="#34A853" d="M24 47c5.6 0 10.4-1.9 13.8-5.1l-7.3-5.7c-1.9 1.3-4.3 2-6.5 2-6.3 0-11.7-4.3-13.5-10.1l-7 5.4C7 41.3 14.8 47 24 47z"/></svg>
      Conectar Google
    </a>
  </div>
  <?php endif; ?>

  <div class="card">
    <h2>Nuevo Registro</h2>
    <form id="uploadForm" enctype="multipart/form-data">

      <div class="form-grid">

        <div class="form-group">
          <label>Cliente *</label>
          <input type="text" name="cliente" placeholder="Nombre del cliente" required>
        </div>
        <div class="form-group">
          <label>Fecha *</label>
          <input type="date" name="fecha" value="<?= date('Y-m-d') ?>" required>
        </div>

        <div class="form-group full">
          <label>Comentario <span style="color:#94a3b8;font-weight:400">(aparece en la primera página del PDF)</span></label>
          <textarea name="notas" rows="3" placeholder="Describe el pedido, factura o registro..."></textarea>
        </div>

      </div>

      <div style="margin-top: 24px;">
        <label style="font-size:.82rem;font-weight:500;color:#64748b;display:block;margin-bottom:10px;">
          Fotos / Imágenes de la factura * <span style="font-weight:400">(se unen en un solo PDF)</span>
        </label>
        <div class="upload-zone" id="uploadZone">
          <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
            <polyline points="16 16 12 12 8 16"/>
            <line x1="12" y1="12" x2="12" y2="21"/>
            <path d="M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3"/>
          </svg>
          <p><strong>Haz clic o arrastra</strong> tus archivos aquí</p>
          <p style="margin-top:4px;font-size:.78rem;">JPG, PNG, WEBP, PDF — máximo <?= MAX_FILE_SIZE_MB ?>MB por archivo</p>
          <input type="file" id="fileInput" name="files[]" multiple accept="image/*,application/pdf">
        </div>
        <div class="preview-grid" id="previewGrid"></div>
      </div>

      <div style="margin-top: 24px; display:flex; align-items:center; gap:12px; flex-wrap:wrap;">
        <button type="submit" class="btn btn-primary" id="submitBtn">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg>
          Guardar Registro
        </button>
      </div>

      <div class="status-bar" id="statusBar">
        <div class="spinner" id="statusSpinner" style="display:none;"></div>
        <span id="statusMsg"></span>
      </div>

    </form>
  </div>

</div>

<script>
const zone = document.getElementById('uploadZone');
const input = document.getElementById('fileInput');
const grid  = document.getElementById('previewGrid');
const form  = document.getElementById('uploadForm');
const btn   = document.getElementById('submitBtn');
const bar   = document.getElementById('statusBar');
const msg   = document.getElementById('statusMsg');
const spin  = document.getElementById('statusSpinner');

let files = [];

zone.addEventListener('click', () => input.click());
zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('drag-over'); });
zone.addEventListener('dragleave', () => zone.classList.remove('drag-over'));
zone.addEventListener('drop', e => {
  e.preventDefault();
  zone.classList.remove('drag-over');
  addFiles([...e.dataTransfer.files]);
});
input.addEventListener('change', () => addFiles([...input.files]));

function addFiles(newFiles) {
  newFiles.forEach(f => {
    if (!files.find(x => x.name === f.name && x.size === f.size)) {
      files.push(f);
      renderPreview(f, files.length - 1);
    }
  });
}

function renderPreview(file, idx) {
  const div = document.createElement('div');
  div.className = 'preview-item';
  div.dataset.idx = idx;

  if (file.type.startsWith('image/')) {
    const img = document.createElement('img');
    img.src = URL.createObjectURL(file);
    div.appendChild(img);
  } else {
    div.style.display = 'flex';
    div.style.alignItems = 'center';
    div.style.justifyContent = 'center';
    div.innerHTML = '<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#64748b" stroke-width="1.5"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>';
  }

  const name = document.createElement('div');
  name.className = 'file-name';
  name.textContent = file.name;
  div.appendChild(name);

  const rm = document.createElement('button');
  rm.className = 'remove-btn';
  rm.textContent = '×';
  rm.type = 'button';
  rm.addEventListener('click', () => {
    files.splice(idx, 1);
    grid.innerHTML = '';
    files.forEach((f, i) => renderPreview(f, i));
  });
  div.appendChild(rm);
  grid.appendChild(div);
}

function setStatus(type, text) {
  bar.className = 'status-bar ' + type;
  msg.textContent = text;
  spin.style.display = type === 'loading' ? 'block' : 'none';
}

form.addEventListener('submit', async e => {
  e.preventDefault();
  if (!files.length) { setStatus('error', 'Agrega al menos un archivo.'); return; }

  const data = new FormData(form);
  data.delete('files[]');
  files.forEach(f => data.append('files[]', f));

  btn.disabled = true;
  setStatus('loading', 'Procesando y subiendo a Drive...');

  try {
    const res = await fetch('api/upload.php', { method: 'POST', body: data });
    const json = await res.json();
    if (json.success) {
      bar.className = 'status-bar success';
      spin.style.display = 'none';
      msg.innerHTML = `✓ PDF generado y guardado en Drive.
        ${json.drive_link ? `&nbsp;<a href="${json.drive_link}" target="_blank" style="color:#15803d;font-weight:600;text-decoration:underline">Ver PDF en Drive →</a>` : ''}`;
      form.reset();
      files = [];
      grid.innerHTML = '';
    } else {
      setStatus('error', json.error || 'Error al guardar.');
    }
  } catch (err) {
    setStatus('error', 'Error de conexión: ' + err.message);
  } finally {
    btn.disabled = false;
  }
});
</script>

</body>
</html>
