<div x-data="facturasApp()" x-init="init()" class="p-6">

  <div class="flex items-center justify-between mb-6">
    <div>
      <h1 class="text-2xl font-bold text-slate-800">Facturas</h1>
      <p class="text-sm text-slate-500 mt-1">Gestión de facturas por cliente y proyecto</p>
    </div>
    <button @click="openCreate()" class="btn-primary flex items-center gap-2">
      <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4"/></svg>
      Nueva factura
    </button>
  </div>

  <div class="mb-4">
    <input x-model="search" @input.debounce.400ms="page=1;load()" type="text" placeholder="Buscar por número, cliente..." class="input-field w-full max-w-sm">
  </div>

  <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-x-auto">
    <table class="w-full text-sm">
      <thead class="bg-slate-50 text-slate-500 text-xs uppercase tracking-wide">
        <tr>
          <th class="px-4 py-3 text-left">#</th>
          <th class="px-4 py-3 text-left">Cliente</th>
          <th class="px-4 py-3 text-left">Descripción</th>
          <th class="px-4 py-3 text-left">Monto</th>
          <th class="px-4 py-3 text-left">Estado</th>
          <th class="px-4 py-3 text-left">Vencimiento</th>
          <th class="px-4 py-3 text-left">Visible</th>
          <th class="px-4 py-3 text-left">PDF</th>
          <th class="px-4 py-3 text-left">Acciones</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-slate-100">
        <template x-if="loading">
          <tr><td colspan="9" class="text-center py-10 text-slate-400">Cargando...</td></tr>
        </template>
        <template x-for="f in items" :key="f.ID">
          <tr class="hover:bg-slate-50">
            <td class="px-4 py-3 font-mono text-xs text-slate-500" x-text="f.numero||`#${f.ID}`"></td>
            <td class="px-4 py-3 text-slate-700" x-text="f.cliente?.empresa||f.cliente?.nombre||'-'"></td>
            <td class="px-4 py-3 text-slate-600 max-w-xs truncate" x-text="f.descripcion"></td>
            <td class="px-4 py-3 font-semibold text-slate-800" x-text="`${f.moneda} ${Number(f.monto).toLocaleString('es-CO')}`"></td>
            <td class="px-4 py-3">
              <span class="badge" :class="estadoBadge(f.estado)" x-text="f.estado"></span>
            </td>
            <td class="px-4 py-3 text-xs text-slate-500" x-text="formatDate(f.fecha_vencimiento)"></td>
            <td class="px-4 py-3">
              <span :class="f.visible ? 'text-green-500' : 'text-slate-300'">
                <svg class="w-4 h-4 inline" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
              </span>
            </td>
            <td class="px-4 py-3">
              <div class="flex items-center gap-1">
                <template x-if="f.archivo">
                  <a :href="`/app/facturas/${f.ID}/download`" class="btn-icon text-blue-500" title="Descargar">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
                  </a>
                </template>
                <button @click="openUpload(f)" class="btn-icon text-slate-500" title="Subir PDF">
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l4-4m0 0l4 4m-4-4v12"/></svg>
                </button>
              </div>
            </td>
            <td class="px-4 py-3">
              <div class="flex items-center gap-2">
                <button @click="openEdit(f)" class="btn-icon text-yellow-500">
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                </button>
                <button @click="confirmDelete(f)" class="btn-icon text-red-500">
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                </button>
              </div>
            </td>
          </tr>
        </template>
      </tbody>
    </table>
  </div>

  <!-- Paginación -->
  <div class="flex justify-between items-center mt-4 text-sm text-slate-500">
    <span>Total: <strong x-text="total"></strong></span>
    <div class="flex gap-1">
      <button @click="page--;load()" :disabled="page<=1" class="px-3 py-1 rounded border border-slate-200 disabled:opacity-40">Ant</button>
      <span class="px-3 py-1" x-text="`${page} / ${totalPages||1}`"></span>
      <button @click="page++;load()" :disabled="page>=totalPages" class="px-3 py-1 rounded border border-slate-200 disabled:opacity-40">Sig</button>
    </div>
  </div>

  <!-- Modal crear/editar -->
  <div x-show="showModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
    <div @click.outside="showModal=false" class="bg-white rounded-2xl shadow-2xl w-full max-w-lg mx-4 p-6 max-h-screen overflow-y-auto">
      <h2 class="text-lg font-bold mb-4" x-text="editId ? 'Editar factura' : 'Nueva factura'"></h2>
      <form @submit.prevent="save()">
        <div class="grid grid-cols-2 gap-3">
          <div class="col-span-2">
            <label class="label">Cliente</label>
            <select x-model.number="form.cliente_id" class="input-field w-full" required>
              <option value="">Seleccionar...</option>
              <template x-for="c in clientes" :key="c.ID">
                <option :value="c.ID" x-text="c.empresa||c.nombre"></option>
              </template>
            </select>
          </div>
          <div class="col-span-2">
            <label class="label">Proyecto (opcional)</label>
            <select x-model.number="form.proyecto_id" class="input-field w-full">
              <option value="">Sin proyecto</option>
              <template x-for="p in proyectos" :key="p.ID">
                <option :value="p.ID" x-text="p.nombre"></option>
              </template>
            </select>
          </div>
          <div><label class="label">N° Factura</label><input x-model="form.numero" class="input-field w-full" placeholder="FAC-001"></div>
          <div>
            <label class="label">Moneda</label>
            <select x-model="form.moneda" class="input-field w-full">
              <option value="COP">COP</option>
              <option value="USD">USD</option>
              <option value="MXN">MXN</option>
              <option value="EUR">EUR</option>
            </select>
          </div>
          <div><label class="label">Monto</label><input x-model.number="form.monto" type="number" step="0.01" class="input-field w-full" required></div>
          <div>
            <label class="label">Estado</label>
            <select x-model="form.estado" class="input-field w-full">
              <option value="pendiente">Pendiente</option>
              <option value="pagada">Pagada</option>
              <option value="vencida">Vencida</option>
              <option value="cancelada">Cancelada</option>
            </select>
          </div>
          <div><label class="label">Fecha emisión</label><input x-model="form.fecha_emision" type="date" class="input-field w-full"></div>
          <div><label class="label">Fecha vencimiento</label><input x-model="form.fecha_vencimiento" type="date" class="input-field w-full"></div>
          <div class="col-span-2"><label class="label">Descripción</label><textarea x-model="form.descripcion" class="input-field w-full" rows="2"></textarea></div>
          <div class="col-span-2"><label class="label">Notas internas</label><textarea x-model="form.notas" class="input-field w-full" rows="2"></textarea></div>
          <div class="col-span-2 flex items-center gap-2">
            <input type="checkbox" x-model="form.visible" id="fv" class="w-4 h-4">
            <label for="fv" class="text-sm text-slate-600">Visible al cliente en el portal</label>
          </div>
        </div>
        <p x-show="error" x-text="error" class="text-red-500 text-sm mt-3"></p>
        <div class="flex justify-end gap-3 mt-5">
          <button type="button" @click="showModal=false" class="btn-secondary">Cancelar</button>
          <button type="submit" :disabled="saving" class="btn-primary" x-text="saving?'Guardando...':'Guardar'"></button>
        </div>
      </form>
    </div>
  </div>

  <!-- Modal subir PDF -->
  <div x-show="showUploadModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
    <div @click.outside="showUploadModal=false" class="bg-white rounded-2xl shadow-2xl w-full max-w-sm mx-4 p-6">
      <h2 class="text-lg font-bold mb-4">Subir PDF de factura</h2>
      <input type="file" accept=".pdf" @change="pdfFile=$event.target.files[0]" class="input-field w-full mb-4">
      <p x-show="uploadError" x-text="uploadError" class="text-red-500 text-sm mb-3"></p>
      <div class="flex justify-end gap-3">
        <button @click="showUploadModal=false" class="btn-secondary">Cancelar</button>
        <button @click="doUpload()" :disabled="!pdfFile||saving" class="btn-primary" x-text="saving?'Subiendo...':'Subir'"></button>
      </div>
    </div>
  </div>

  <!-- Modal eliminar -->
  <div x-show="showDelete" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
    <div @click.outside="showDelete=false" class="bg-white rounded-2xl shadow-2xl w-full max-w-sm mx-4 p-6">
      <h2 class="text-lg font-bold mb-2">¿Eliminar factura?</h2>
      <p class="text-slate-500 text-sm mb-5">Esta acción no se puede deshacer.</p>
      <div class="flex justify-end gap-3">
        <button @click="showDelete=false" class="btn-secondary">Cancelar</button>
        <button @click="doDelete()" :disabled="saving" class="btn-danger" x-text="saving?'Eliminando...':'Eliminar'"></button>
      </div>
    </div>
  </div>

</div>

<script>
function facturasApp() {
  return {
    items:[], clientes:[], proyectos:[], total:0, totalPages:1, page:1, search:'',
    loading:false, saving:false, showModal:false, showDelete:false, showUploadModal:false,
    editId:null, deleteId:null, uploadId:null, error:'', uploadError:'', pdfFile:null,
    form:{ cliente_id:'', proyecto_id:'', numero:'', descripcion:'', monto:0, moneda:'COP', estado:'pendiente', fecha_emision:'', fecha_vencimiento:'', visible:true, notas:'' },

    async init(){ await this.load(); },

    async load(){
      this.loading=true;
      try {
        const r=await axios.get(`/app/loadfacturas?page=${this.page}&search=${encodeURIComponent(this.search)}`);
        this.items=r.data.items||[];
        this.total=r.data.total;
        this.totalPages=r.data.totalPages;
        this.clientes=r.data.clientes||[];
        this.proyectos=r.data.proyectos||[];
      } finally{ this.loading=false; }
    },

    openCreate(){
      this.editId=null; this.error='';
      this.form={cliente_id:'',proyecto_id:'',numero:'',descripcion:'',monto:0,moneda:'COP',estado:'pendiente',fecha_emision:'',fecha_vencimiento:'',visible:true,notas:''};
      this.showModal=true;
    },
    openEdit(f){
      this.editId=f.ID; this.error='';
      const fv=f.fecha_vencimiento?f.fecha_vencimiento.substring(0,10):'';
      const fe=f.fecha_emision?f.fecha_emision.substring(0,10):'';
      this.form={cliente_id:f.cliente_id,proyecto_id:f.proyecto_id||'',numero:f.numero||'',descripcion:f.descripcion||'',monto:f.monto,moneda:f.moneda||'COP',estado:f.estado,fecha_emision:fe,fecha_vencimiento:fv,visible:f.visible,notas:f.notas||''};
      this.showModal=true;
    },
    async save(){
      this.saving=true; this.error='';
      const payload={...this.form};
      if(!payload.proyecto_id) payload.proyecto_id=null;
      try {
        if(this.editId) await axios.put(`/app/facturas/${this.editId}`, payload);
        else await axios.post('/app/facturas', payload);
        this.showModal=false; await this.load();
      } catch(e){ this.error=e.response?.data?.error||'Error al guardar'; }
      finally{ this.saving=false; }
    },

    confirmDelete(f){ this.deleteId=f.ID; this.showDelete=true; },
    async doDelete(){
      this.saving=true;
      try{ await axios.delete(`/app/facturas/${this.deleteId}`); this.showDelete=false; await this.load(); }
      finally{ this.saving=false; }
    },

    openUpload(f){ this.uploadId=f.ID; this.pdfFile=null; this.uploadError=''; this.showUploadModal=true; },
    async doUpload(){
      if(!this.pdfFile) return;
      this.saving=true; this.uploadError='';
      try {
        const fd=new FormData(); fd.append('pdf', this.pdfFile);
        await axios.post(`/app/facturas/${this.uploadId}/upload-pdf`, fd, {headers:{'Content-Type':'multipart/form-data'}});
        this.showUploadModal=false; await this.load();
      } catch(e){ this.uploadError=e.response?.data?.error||'Error al subir'; }
      finally{ this.saving=false; }
    },

    estadoBadge(e){ return {pendiente:'badge-yellow',pagada:'badge-green',vencida:'badge-red',cancelada:'badge-slate'}[e]||'badge-slate'; },
    formatDate(d){ if(!d) return ''; return new Date(d).toLocaleDateString('es-CO',{day:'2-digit',month:'short',year:'numeric'}); },
  }
}
</script>

<style>
.btn-primary{background:#8eb02f;color:#fff;padding:.5rem 1rem;border-radius:.5rem;font-weight:600;font-size:.875rem;}
.btn-primary:hover{background:#6d8c24;}
.btn-secondary{background:#f1f5f9;color:#475569;padding:.5rem 1rem;border-radius:.5rem;font-weight:500;font-size:.875rem;border:1px solid #e2e8f0;}
.btn-danger{background:#ef4444;color:#fff;padding:.5rem 1rem;border-radius:.5rem;font-weight:600;font-size:.875rem;}
.btn-icon{display:inline-flex;align-items:center;padding:.25rem;border-radius:.375rem;}
.btn-icon:hover{background:#f1f5f9;}
.input-field{border:1px solid #e2e8f0;border-radius:.5rem;padding:.5rem .75rem;font-size:.875rem;outline:none;}
.input-field:focus{border-color:#8eb02f;}
.label{display:block;font-size:.75rem;font-weight:600;color:#475569;margin-bottom:.25rem;text-transform:uppercase;letter-spacing:.05em;}
.badge{display:inline-block;padding:.15rem .6rem;border-radius:9999px;font-size:.7rem;font-weight:600;text-transform:capitalize;}
.badge-green{background:#dcfce7;color:#15803d;}
.badge-yellow{background:#fef9c3;color:#854d0e;}
.badge-slate{background:#f1f5f9;color:#475569;}
.badge-red{background:#fee2e2;color:#991b1b;}
</style>
