<?php $__env->startSection('content'); ?>
<div class="bg-body-light">
    <div class="content content-full">
        <div class="d-flex flex-column flex-sm-row justify-content-sm-between align-items-sm-center py-2">
            <div class="flex-grow-1">
                <h1 class="h3 fw-bold mb-2">
                    <i class="fa fa-file-signature text-primary me-2"></i>Nuevo Contrato
                </h1>
                <h2 class="fs-base lh-base fw-medium text-muted mb-0">
                    Generación de contrato de compra-venta — Folio #<span class="text-primary fw-bold"><?php echo e($nuevoId); ?></span>
                </h2>
            </div>
        </div>
    </div>
</div>

<div class="content">
    <form method="POST" action="<?php echo e(route('contratos.store')); ?>" id="formulario">
        <?php echo csrf_field(); ?>
        <input type="hidden" name="id" value="<?php echo e($nuevoId); ?>">
        <input type="hidden" name="idgrupo" value="<?php echo e($nuevoGrupo); ?>">

        <div class="row items-push">
            <div class="col-xl-7">
                <div class="block block-rounded block-bordered shadow-sm">
                    <div class="block-header block-header-default">
                        <h3 class="block-title">Datos Principales</h3>
                    </div>
                    <div class="block-content">
                        
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <label class="form-label fs-xs text-uppercase fw-bold text-muted">Fecha del Contrato</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fa fa-calendar-alt"></i></span>
                                    <input type="text" name="fecha" id="fecha" class="form-control form-control-alt fs-sm" 
                                           value="<?php echo e($hoy); ?>" placeholder="dd/mm/aaaa" required>
                                </div>
                            </div>
                        </div>

                        
                        <div class="mb-4 bg-body-light p-3 rounded border">
                            <label class="form-label fs-xs text-uppercase fw-bold text-muted mb-3 d-block border-bottom pb-2">Partes Interesadas</label>
                            <?php $__empty_1 = true; $__currentLoopData = $clientesTmp; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $tmp): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                <div class="d-flex align-items-center mb-2">
                                    <div class="flex-shrink-0 me-2">
                                        <span class="badge bg-alt-info text-info border border-info-light fs-xs"><?php echo e($tmp->tipo); ?></span>
                                    </div>
                                    <div class="flex-grow-1">
                                        <input type="text" class="form-control form-control-sm border-0 bg-transparent fw-bold" value="<?php echo e($tmp->nombre); ?>" readonly>
                                    </div>
                                </div>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                <div class="alert alert-warning fs-sm mb-0">
                                    <i class="fa fa-exclamation-triangle me-2"></i> Grupo sin clientes. <a href="<?php echo e(route('clientes.create')); ?>" class="alert-link">Registrar aquí</a>.
                                </div>
                            <?php endif; ?>
                        </div>

                        
                        <div class="row g-3 mb-4">
                            <div class="col-md-6">
                                <label class="form-label fs-xs text-uppercase fw-bold text-muted">Urbanización</label>
                                <select name="select1" id="select1" class="form-select form-select-alt fs-sm" required onchange="cargarDistritos(this.value)">
                                    <option value="0">--- Seleccione ---</option>
                                    <?php $__currentLoopData = $urbanizaciones; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $u): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($u->id); ?>"><?php echo e($u->nombre); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fs-xs text-uppercase fw-bold text-muted">Distrito</label>
                                <select name="select2" id="select2" class="form-select form-select-alt fs-sm" disabled required onchange="cargarLotes(this.value)">
                                    <option value="0">--- Seleccione ---</option>
                                </select>
                            </div>
                            <div class="col-12">
                                <label class="form-label fs-xs text-uppercase fw-bold text-muted">Manzano / Lote Disponible</label>
                                <select name="select3" id="select3" class="form-select form-select-alt fs-sm fw-bold border-primary" disabled required onchange="cargarDatosLote(this.value)">
                                    <option value="0">--- Seleccione Lote ---</option>
                                </select>
                            </div>
                        </div>

                        
                        <div class="mb-4">
                            <label class="form-label fs-xs text-uppercase fw-bold text-muted">Precio de Venta ($us)</label>
                            <div class="input-group input-group-lg">
                                <span class="input-group-text">$us</span>
                                <input type="number" step="0.01" name="total" id="total" class="form-control form-control-alt <?php $__errorArgs = ['total'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" placeholder="0.00" onchange="actualizarCuotas()" required>
                                <input type="hidden" name="subtotal" id="subtotal" value="0">
                            </div>
                            <div class="fs-xs mt-2 p-2 bg-body rounded border">
                                Subtotal de Lista: <span class="fw-bold">$us <span id="subtotal-display">0.00</span></span>
                            </div>
                        </div>

                        
                        <div class="block block-rounded block-bordered bg-body-light mb-4">
                            <div class="block-content block-content-full">
                                <div class="d-flex justify-content-center gap-3 mb-4">
                                    <div class="btn-group w-100" role="group">
                                        <input type="radio" class="btn-check" name="pagos" id="pagos1" value="credito" checked onchange="mostrarPlan(0)">
                                        <label class="btn btn-alt-primary fs-sm" for="pagos1"><i class="fa fa-clock me-1"></i> Crédito</label>
                                        
                                        <input type="radio" class="btn-check" name="pagos" id="pagos2" value="contado" onchange="mostrarPlan(1)">
                                        <label class="btn btn-alt-primary fs-sm" for="pagos2"><i class="fa fa-hand-holding-usd me-1"></i> Contado</label>
                                        
                                        <input type="radio" class="btn-check" name="pagos" id="pagos3" value="otros" onchange="mostrarPlan(2)">
                                        <label class="btn btn-alt-primary fs-sm" for="pagos3"><i class="fa fa-star me-1"></i> C.E.</label>
                                    </div>
                                </div>

                                <div id="plan-credito" class="row g-2">
                                    <div class="col-md-4">
                                        <label class="form-label fs-xs text-muted">Cuota Inicial</label>
                                        <input type="number" step="0.01" name="inicial" id="inicial" class="form-control form-control-sm" onchange="actualizarCuotas()">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label fs-xs text-muted">N° Cuotas</label>
                                        <input type="number" name="ncuotas" id="ncuotas" class="form-control form-control-sm" min="1" onchange="actualizarCuotas()">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label fs-xs text-muted text-primary fw-bold">Cuota Mensual</label>
                                        <input type="number" step="0.01" name="mensual" id="mensual" class="form-control form-control-sm fw-bold border-primary" readonly>
                                    </div>
                                </div>

                                <div id="plan-contado" style="display:none;">
                                    <label class="form-label fs-xs text-muted">Monto Único al Contado</label>
                                    <input type="number" step="0.01" name="inicial2" id="inicial2" class="form-control form-control-sm">
                                </div>

                                <div id="plan-otros" style="display:none;" class="alert alert-info py-2 fs-xs mb-0">
                                    <i class="fa fa-info-circle me-1"></i> Contrato especial sin cargo inicial.
                                    <input type="hidden" name="inicial3" id="inicial3" value="0">
                                </div>
                            </div>
                        </div>

                        <div class="mb-4">
                            <label class="form-label fs-xs text-uppercase fw-bold text-muted">Vendedor Responsable</label>
                            <select name="cboVendedores" id="cboVendedores" class="form-select form-select-alt fs-sm" required>
                                <option value="0">--- Seleccione Vendedor ---</option>
                                <?php $__currentLoopData = $vendedores; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $v): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($v->id); ?>"><?php echo e($v->nombre); ?></option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-5">
                <div class="block block-rounded shadow-sm" id="card-lote" style="opacity:0.5; transition: opacity 0.3s ease;">
                    <div class="block-header block-header-default bg-dark">
                        <h3 class="block-title text-white">Especificaciones del Lote</h3>
                    </div>
                    <div class="block-content">
                        <div class="row text-center mb-4">
                            <div class="col-6 border-end">
                                <p class="fs-xs fw-bold text-muted text-uppercase mb-1">Superficie</p>
                                <p class="fs-lg fw-bold mb-0"><span id="lote-superf">—</span> <small>m²</small></p>
                                <input type="hidden" name="select4" id="select4" value="0">
                            </div>
                            <div class="col-6">
                                <p class="fs-xs fw-bold text-muted text-uppercase mb-1">Subtotal Calc.</p>
                                <p class="fs-lg fw-bold text-success mb-0">$us <span id="lote-subtotal">—</span></p>
                            </div>
                        </div>

                        <div class="p-3 bg-body-light rounded border">
                            <h4 class="fs-xs fw-bold text-muted text-uppercase mb-3">Servicios Instalados</h4>
                            <div class="row g-2" id="servicios-lote">
                                <?php $__currentLoopData = ['alcanta'=>'Alcantarillado','luz'=>'Luz','agua'=>'Agua','transpor'=>'Transporte','cordon'=>'Cordón','acera'=>'Acera','muralla'=>'Muralla']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $campo => $lbl): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <div class="col-6">
                                        <div class="form-check form-switch fs-sm">
                                            <input class="form-check-input" type="checkbox" id="svc-<?php echo e($campo); ?>" disabled>
                                            <label class="form-check-label" for="svc-<?php echo e($campo); ?>"><?php echo e($lbl); ?></label>
                                        </div>
                                    </div>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </div>
                        </div>

                        <div class="mt-4">
                            <label class="form-label fs-xs text-uppercase fw-bold text-muted">Glosa / Observaciones</label>
                            <textarea name="observaciones" class="form-control form-control-alt fs-sm" rows="4" maxlength="120" placeholder="Escriba notas adicionales..."></textarea>
                        </div>
                    </div>
                    <div class="block-content block-content-full block-content-sm bg-body-light border-top">
                        <button type="submit" class="btn btn-primary w-100 py-2" onclick="return validarFormulario()">
                            <i class="fa fa-save me-1"></i> FINALIZAR CONTRATO
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<style>
    .bg-alt-info { background-color: rgba(13, 202, 240, 0.1); }
    .form-select-alt:focus { border-color: #0665d0; }
    .btn-check:checked + .btn-alt-primary { background-color: #0665d0 !important; color: white !important; }
</style>
<?php $__env->stopSection(); ?>


<?php $__env->startPush('scripts'); ?>
<script>
const CSRF = '<?php echo e(csrf_token()); ?>';
 
// ── Cascada: cargar distritos ─────────────────────────────────────────────
function cargarDistritos(idUrb) {
  const sel2 = document.getElementById('select2');
  const sel3 = document.getElementById('select3');
  sel2.innerHTML = '<option value="0">Cargando...</option>';
  sel2.disabled = true;
  sel3.innerHTML = '<option value="0">Seleccione Lote</option>';
  sel3.disabled = true;
  limpiarDatosLote();
 
  if (idUrb == 0) { sel2.innerHTML = '<option value="0">Seleccione Distrito</option>'; return; }
 
  fetch(`/lotes/distritos/${idUrb}`)
    .then(r => r.json())
    .then(data => {
      sel2.innerHTML = '<option value="0">Seleccione Distrito</option>';
      data.forEach(d => sel2.innerHTML += `<option value="${d.id}">${d.nombre}</option>`);
      sel2.disabled = false;
    });
}
 
// ── Cascada: cargar lotes disponibles ────────────────────────────────────
function cargarLotes(idDis) {
  const sel3 = document.getElementById('select3');
  sel3.innerHTML = '<option value="0">Cargando...</option>';
  sel3.disabled = true;
  limpiarDatosLote();
 
  if (idDis == 0) { sel3.innerHTML = '<option value="0">Seleccione Lote</option>'; return; }
 
  fetch(`/contratos/lotes-disponibles/${idDis}`)
    .then(r => r.json())
    .then(data => {
      sel3.innerHTML = '<option value="0">Seleccione Lote</option>';
      data.forEach(l => {
        sel3.innerHTML += `<option value="${l.id}">Mzo. ${l.manzano} — Lote ${l.nombre} (${l.superf} m²)</option>`;
      });
      sel3.disabled = false;
    });
}
 
// ── Cargar datos del lote seleccionado ───────────────────────────────────
function cargarDatosLote(idLote) {
  if (idLote == 0) { limpiarDatosLote(); return; }
 
  fetch(`/contratos/datos-lote/${idLote}`)
    .then(r => r.json())
    .then(data => {
      document.getElementById('lote-superf').textContent   = data.superf;
      document.getElementById('lote-subtotal').textContent = parseFloat(data.subtotal).toFixed(2);
      document.getElementById('select4').value             = data.superf;
      document.getElementById('subtotal').value            = data.subtotal;
      document.getElementById('subtotal-display').textContent = parseFloat(data.subtotal).toFixed(2);
 
      // Marcar servicios
      const campos = ['alcanta','luz','agua','transpor','cordon','acera','muralla'];
      campos.forEach(c => {
        const cb = document.getElementById(`svc-${c}`);
        if (cb) cb.checked = data[c] == 1;
      });
 
      document.getElementById('card-lote').style.opacity = '1';
    });
}
 
function limpiarDatosLote() {
  ['lote-superf','lote-subtotal'].forEach(id => {
    const el = document.getElementById(id);
    if (el) el.textContent = '—';
  });
  document.getElementById('subtotal').value = '0';
  document.getElementById('subtotal-display').textContent = '0.00';
  document.getElementById('select4').value = '0';
  document.getElementById('card-lote').style.opacity = '0.5';
}
 
// ── Plan de pagos ────────────────────────────────────────────────────────
// FIX BUG 1 + BUG 3:
//   - Ya no se toca 'total' al cambiar de plan (era lo que rompía los cálculos).
//   - Se limpia 'mensual' correctamente al salir del plan crédito.
//   - Cada plan limpia solo sus propios campos, sin tocar los de los demás.
function mostrarPlan(num) {
  document.getElementById('plan-credito').style.display = num === 0 ? '' : 'none';
  document.getElementById('plan-contado').style.display = num === 1 ? '' : 'none';
  document.getElementById('plan-otros').style.display   = num === 2 ? '' : 'none';
 
  if (num !== 0) {
    // Saliendo de crédito: limpiar sus 3 campos
    document.getElementById('inicial').value  = '';
    document.getElementById('ncuotas').value  = '';
    document.getElementById('mensual').value  = '';   // ← FIX BUG 3
  }
 
  if (num !== 1) {
    // Saliendo de contado: limpiar su campo
    document.getElementById('inicial2').value = '';
  }
 
  // C.E. no necesita limpiar 'total' — el usuario ingresa el precio libremente
  // ← FIX BUG 1: se ELIMINÓ la línea que hacía total = '0'
}
 
// ── Calcular cuota mensual automáticamente ───────────────────────────────
// FIX BUG 2: solo calcula si el plan activo es crédito
function actualizarCuotas() {
  // Si no está en plan crédito, no hacer nada
  if (!document.getElementById('pagos1').checked) return;
 
  const total   = parseFloat(document.getElementById('total').value)   || 0;
  const inicial = parseFloat(document.getElementById('inicial').value) || 0;
  const ncuotas = parseInt(document.getElementById('ncuotas').value)   || 0;
 
  if (ncuotas > 0 && total > 0) {
    const parcial = total - inicial;
    const mensual = Math.floor((parcial / ncuotas) * 100) / 100;
    document.getElementById('mensual').value = mensual.toFixed(2);
  } else {
    // Si faltan datos, dejar mensual en blanco (no dejar el valor anterior)
    document.getElementById('mensual').value = '';
  }
}
 
// ── Validación antes de enviar ────────────────────────────────────────────
function validarFormulario() {
  const u = document.getElementById('select1').value;
  const d = document.getElementById('select2').value;
  const l = document.getElementById('select3').value;
  if (u == 0 || d == 0 || l == 0) {
    alert('Debe seleccionar urbanización, distrito y lote.');
    return false;
  }
 
  const total    = parseFloat(document.getElementById('total').value)    || 0;
  const subtotal = parseFloat(document.getElementById('subtotal').value) || 0;
 
  if (total <= 0) {
    alert('Ingrese el precio de venta.');
    return false;
  }
 
  if (total < subtotal) {
    alert('El total no puede ser menor al subtotal ($us ' + subtotal.toFixed(2) + ')');
    return false;
  }
 
  const pagos1 = document.getElementById('pagos1').checked;
  const pagos2 = document.getElementById('pagos2').checked;
  const pagos3 = document.getElementById('pagos3').checked;
 
  if (pagos1) {
    const inicial = parseFloat(document.getElementById('inicial').value) || 0;
    const ncuotas = parseInt(document.getElementById('ncuotas').value)   || 0;
    if (inicial < 0 || inicial > total) { alert('Cuota inicial inválida.'); return false; }
    if (ncuotas < 1) { alert('Ingrese número de cuotas válido.'); return false; }
    const mensual = parseFloat(document.getElementById('mensual').value) || 0;
    if (mensual <= 0) { alert('La cuota mensual debe ser mayor a cero.'); return false; }
  }
 
  if (pagos2) {
    const inicial2 = parseFloat(document.getElementById('inicial2').value) || 0;
    if (inicial2 <= 0 || inicial2 > total) { alert('Monto al contado inválido.'); return false; }
  }
 
  const vendedor = document.getElementById('cboVendedores').value;
  if (vendedor == 0) { alert('Debe seleccionar un vendedor.'); return false; }
 
  return confirm('¿Guardar el contrato?');
}
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /var/www/proyect-laravel/cosmos-app/resources/views/contratos/create.blade.php ENDPATH**/ ?>