<div x-data="cobroApp()" 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">Cuentas por cobrar</h1>
      <p class="text-sm text-slate-500 mt-1">Facturas y montos pendientes de cobro</p>
    </div>
    <button @click="openCreate()" class="btn-primary flex items-center gap-2">Nuevo cobro</button>
  </div>

  <div class="flex flex-wrap items-center gap-3 mb-4">
    <input x-model="search" @input.debounce.400ms="page=1;load()" type="text" placeholder="Buscar..." class="input-field w-full max-w-xs">
    <select x-model="filtroEstado" @change="page=1;load()" class="input-field">
      <option value="">Todos</option>
      <option value="pendiente">Pendiente</option>
      <option value="pagado">Pagado</option>
      <option value="parcial">Parcial</option>
    </select>
  </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">Fecha</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-right">Valor</th>
          <th class="px-4 py-3 text-left">Vence</th>
          <th class="px-4 py-3 text-left">Estado</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="7" class="text-center py-10 text-slate-400">Cargando...</td></tr>
        </template>
        <template x-for="c in items" :key="c.ID">
          <tr class="hover:bg-slate-50">
            <td class="px-4 py-3 text-xs text-slate-500" x-text="formatDate(c.fecha)"></td>
            <td class="px-4 py-3 text-slate-700 font-medium" x-text="c.cliente?.nombre||'-'"></td>
            <td class="px-4 py-3 text-slate-600" x-text="c.descripcion"></td>
            <td class="px-4 py-3 text-right font-semibold text-amber-600" x-text="formatoCOP(c.valor)"></td>
            <td class="px-4 py-3 text-xs text-slate-500" x-text="formatDate(c.fecha_vencimiento)"></td>
            <td class="px-4 py-3">
              <span class="badge" :class="{'badge-yellow':c.estado==='pendiente','badge-green':c.estado==='pagado','badge-blue':c.estado==='parcial'}" x-text="c.estado"></span>
            </td>
            <td class="px-4 py-3">
              <div class="flex items-center gap-2">
                <button @click="marcarPagado(c)" class="btn-icon text-green-500" title="Marcar pagado" x-show="c.estado!=='pagado'">✓</button>
                <button @click="confirmDelete(c)" class="btn-icon text-red-500">🗑️</button>
              </div>
            </td>
          </tr>
        </template>
      </tbody>
    </table>
  </div>

  <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 -->
  <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">
      <h2 class="text-lg font-bold text-slate-800 mb-4">Nuevo cobro pendiente</h2>
      <form @submit.prevent="save()">
        <div class="grid grid-cols-2 gap-3">
          <div class="col-span-2">
            <label class="label">Cliente (quien debe)</label>
            <select x-model.number="form.cliente_id" class="input-field w-full" required>
              <option value="">Seleccionar...</option>
              <template x-for="cl in clientes" :key="cl.ID">
                <option :value="cl.ID" x-text="cl.nombre + (cl.empresa ? ' — ' + cl.empresa : '')"></option>
              </template>
            </select>
          </div>
          <div class="col-span-2">
            <label class="label">Descripción</label>
            <input x-model="form.descripcion" class="input-field w-full" required>
          </div>
          <div>
            <label class="label">Valor ($)</label>
            <input x-model.number="form.valor" type="number" step="0.01" class="input-field w-full" required>
          </div>
          <div>
            <label class="label">Fecha</label>
            <input x-model="form.fecha" 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">Notas</label>
            <textarea x-model="form.notas" class="input-field w-full" rows="2"></textarea>
          </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 pagado -->
  <div x-show="showPagarModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
    <div @click.outside="showPagarModal=false" class="bg-white rounded-2xl shadow-2xl w-full max-w-sm mx-4 p-6">
      <h2 class="text-lg font-bold text-slate-800 mb-4">Marcar como pagado</h2>
      <form @submit.prevent="doPagar()">
        <label class="label">Fecha de pago</label>
        <input x-model="pagoFecha" type="date" class="input-field w-full mb-4" required>
        <div class="flex justify-end gap-3">
          <button type="button" @click="showPagarModal=false" class="btn-secondary">Cancelar</button>
          <button type="submit" :disabled="saving" class="btn-primary" x-text="saving?'Guardando...':'Confirmar'"></button>
        </div>
      </form>
    </div>
  </div>

  <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 text-slate-800 mb-2">¿Eliminar?</h2>
      <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 cobroApp() {
  return {
    items:[], clientes:[], total:0, totalPages:1, page:1, search:'', filtroEstado:'',
    loading:false, saving:false, showModal:false, showDelete:false, showPagarModal:false,
    deleteId:null, pagarId:null, pagoFecha:'', error:'',
    form:{ cliente_id:'', descripcion:'', valor:0, fecha:'', fecha_vencimiento:'', notas:'' },

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

    async load(){
      this.loading=true;
      try {
        const params=new URLSearchParams({page:this.page,search:this.search});
        if(this.filtroEstado) params.set('estado',this.filtroEstado);
        const r=await axios.get('/app/contabilidad/cuentas-cobro/list?'+params.toString());
        this.items=r.data.items; this.total=r.data.total; this.totalPages=r.data.totalPages;
        const er=await axios.get('/app/api/clientes/select');
        this.clientes=er.data;
      } finally{ this.loading=false; }
    },

    openCreate(){ this.editId=null; this.error=''; this.form={cliente_id:'',descripcion:'',valor:0,fecha:'',fecha_vencimiento:'',notas:''}; this.showModal=true; },
    async save(){
      this.saving=true; this.error='';
      try {
        await axios.post('/app/contabilidad/cuentas-cobro', this.form);
        this.showModal=false; await this.load();
      } catch(e){ this.error=e.response?.data?.error||'Error al guardar'; }
      finally{ this.saving=false; }
    },

    marcarPagado(c){ this.pagarId=c.ID; this.pagoFecha=new Date().toISOString().substring(0,10); this.showPagarModal=true; },
    async doPagar(){
      this.saving=true;
      try {
        await axios.put(`/app/contabilidad/cuentas-cobro/${this.pagarId}`, {estado:'pagado',fecha_pago:this.pagoFecha});
        this.showPagarModal=false; await this.load();
      } catch(e){ this.error=e.response?.data?.error||'Error'; }
      finally{ this.saving=false; }
    },

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

    formatoCOP(n){ if(n==null) return '$0'; return '$ '+Number(n).toLocaleString('es-CO',{minimumFractionDigits:0}); },
    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:0.5rem 1rem; border-radius:0.5rem; font-weight:600; font-size:.875rem; transition:background .15s; }
.btn-primary:hover { background:#6d8c24; }
.btn-secondary { background:#f1f5f9; color:#475569; padding:0.5rem 1rem; border-radius:0.5rem; font-weight:500; font-size:.875rem; border:1px solid #e2e8f0; }
.btn-danger { background:#ef4444; color:#fff; padding:0.5rem 1rem; border-radius:0.5rem; font-weight:600; font-size:.875rem; }
.btn-icon { display:inline-flex; align-items:center; padding:0.25rem; border-radius:0.375rem; }
.btn-icon:hover { background:#f1f5f9; }
.input-field { border:1px solid #e2e8f0; border-radius:0.5rem; padding:0.5rem 0.75rem; font-size:.875rem; outline:none; transition:border-color .15s; }
.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-blue { background:#dbeafe; color:#1d4ed8; }
.badge-slate { background:#f1f5f9; color:#475569; }
.badge-red { background:#fee2e2; color:#991b1b; }
.text-primary { color:#8eb02f; }
</style>
