@extends('layouts.master')
@section('title') Inicio @endsection
@section('content')
<!-- this is breadcrumbs -->
@component('components.breadcrumb')
@slot('li_1') Inicio @endslot
@slot('li_2') Panel Catastro @endslot
@slot('title') Terrenos @endslot
@endcomponent

<!-- start page content -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-body mb-n3">
                <button type="button" class="btn btn-primary btn-sm px-4 mt-0 mb-3" 
                    data-bs-toggle="modal" 
                    data-bs-target="#modalCrearTerreno">
                    <i class="fas fa-plus"></i>  Nuevo Terrenos
                </button>
                <div class="table-responsive">
                    <table id="tablaSectores" class="table table-striped mb-0 table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>ID</th>
                                <th>Lotización</th>
                                <th>Vía</th>
                                <th>Manzana</th>
                                <th>Lote</th>
                                <th>Área (m²)</th>
                                <th>Estado</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($terrenos as $t)
                                <tr id="fila-terreno-{{ $t->id_terreno }}">
                                    <td>{{ $t->id_terreno }}</td>
                                    <td>{{ $t->lotizacion->nombre_lotizacion ?? 'N/A' }}</td>
                                    <td>{{ $t->via->nombre_via ?? 'N/A' }}</td>
                                    <td>{{ $t->manzana }}</td>
                                    <td>{{ $t->lote }}</td>
                                    <td>{{ $t->area }}</td>
                                    <td>
                                        <span class="badge bg-{{ $t->estado == 'Activo' ? 'success' : 'secondary' }}">
                                            {{ $t->estado }}
                                        </span>
                                    </td>
                                    <td>
                                        <button class="btn btn-sm text-warning btn-editar"
                                                data-id="{{ $t->id_terreno }}"
                                                data-id_lotizacion="{{ $t->id_lotizacion }}"
                                                data-id_via="{{ $t->id_via }}"
                                                data-manzana="{{ $t->manzana }}"
                                                data-lote="{{ $t->lote }}"
                                                data-area="{{ $t->area }}"
                                                data-estado="{{ $t->estado }}"
                                                data-bs-toggle="modal"
                                                data-bs-target="#modalEditarTerreno">
                                            <i class="las la-pen font-18"></i>
                                        </button>
                                        <button class="btn btn-sm text-danger btn-eliminar" data-id="{{ $t->id_terreno }}">
                                            <i class="las la-trash-alt font-18"></i>
                                        </button>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>



                </div>
            </div>
            <!--end card-body-->
        </div>
        <!--end card-->
    </div>
    <!--end col-->
</div>

<!-- Modal Crear -->
<div class="modal fade" id="modalCrearTerreno" tabindex="-1">
  <div class="modal-dialog">
    <form id="formCrearTerreno" class="modal-content">
      @csrf
      <div class="modal-header">
        <h5 class="modal-title">Nuevo Terreno</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="mb-3">
          <label class="form-label">Lotización</label>
          <select name="id_lotizacion" class="form-select" required>
            <option value="">Seleccione</option>
            @foreach ($lotizaciones as $l)
              <option value="{{ $l->id_lotizacion }}">{{ $l->nombre_lotizacion }}</option>
            @endforeach
          </select>
        </div>

        <div class="mb-3">
          <label class="form-label">Vía</label>
          <select name="id_via" class="form-select" required>
            <option value="">Seleccione</option>
            @foreach ($vias as $v)
              <option value="{{ $v->id_via }}">{{ $v->nombre_via }}</option>
            @endforeach
          </select>
        </div>

        <div class="mb-3">
          <label class="form-label">Manzana</label>
          <input type="text" name="manzana" class="form-control" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Lote</label>
          <input type="text" name="lote" class="form-control" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Área (m²)</label>
          <input type="number" name="area" step="0.01" class="form-control" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Estado</label>
          <select name="estado" class="form-select" required>
            <option value="Activo">Activo</option>
            <option value="Inactivo">Inactivo</option>
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" type="submit">Guardar</button>
        <button class="btn btn-secondary" type="button" data-bs-dismiss="modal">Cancelar</button>
      </div>
    </form>
  </div>
</div>


<!-- Modal Editar -->
<div class="modal fade" id="modalEditarTerreno" tabindex="-1">
  <div class="modal-dialog">
    <form id="formEditarTerreno" class="modal-content">
      @csrf
      @method('PUT')
      <input type="hidden" id="edit_id">
      <div class="modal-header">
        <h5 class="modal-title">Editar Terreno</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="mb-3">
          <label class="form-label">Lotización</label>
          <select name="id_lotizacion" id="edit_id_lotizacion" class="form-select" required>
            <option value="">Seleccione</option>
            @foreach ($lotizaciones as $l)
              <option value="{{ $l->id_lotizacion }}">{{ $l->nombre_lotizacion }}</option>
            @endforeach
          </select>
        </div>
        <div class="mb-3">
          <label class="form-label">Vía</label>
          <select name="id_via" id="edit_id_via" class="form-select" required>
            <option value="">Seleccione</option>
            @foreach ($vias as $via)
              <option value="{{ $via->id_via }}">{{ $via->nombre_via }}</option>
            @endforeach
          </select>
        </div>

        <div class="mb-3">
          <label class="form-label">Manzana</label>
          <input type="text" name="manzana" id="edit_manzana" class="form-control" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Lote</label>
          <input type="text" name="lote" id="edit_lote" class="form-control" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Área (m²)</label>
          <input type="number" name="area" id="edit_area" step="0.01" class="form-control" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Estado</label>
          <select name="estado" id="edit_estado" class="form-select" required>
            <option value="Activo">Activo</option>
            <option value="Inactivo">Inactivo</option>
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-warning" type="submit">Actualizar</button>
        <button class="btn btn-secondary" type="button" data-bs-dismiss="modal">Cancelar</button>
      </div>
    </form>
  </div>
</div>









<!--end row-->


@endsection
@section('script')
<!-- jQuery y DataTables -->

<!-- jQuery y DataTables -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

<!-- DataTables Buttons -->
<script src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.colVis.min.js"></script>

<!-- DataTables CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.dataTables.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- tablas -->
<script>
    $(document).ready(function () {
        $("#tablaSectores").DataTable({
            "responsive": true,
            "lengthChange": true,
            "autoWidth": false,
            "buttons": [
                {
                    extend: 'collection',
                    text: 'Opciones',
                    buttons: [
                        { extend: 'copy', text: 'Copiar' },
                        { extend: 'csv', text: 'CSV' },
                        { extend: 'excel', text: 'Excel', title: 'Periodos Académicos' },
                        { extend: 'pdf', text: 'PDF' },
                        { extend: 'print', text: 'Imprimir' }
                    ]
                },
                { extend: 'colvis', text: 'Visibilidad de Columna' }
            ],
            "paging": true,
            "searching": true,
            "info": true,
            "language": {
                "search": "Buscar:",
                "lengthMenu": "Mostrar _MENU_ registros por página",
                "info": "Mostrando _START_ a _END_ de _TOTAL_ entradas",
                "paginate": {
                    "first": "Primero",
                    "previous": "Anterior",
                    "next": "Siguiente",
                    "last": "Último"
                }
            }
        }).buttons().container().appendTo('#tablaSectores_wrapper .col-md-6:eq(0)');
    });
</script>
<!-- agregar -->
<script>
    $(document).ready(function () {

        // CREAR
        $('#formCrearTerreno').submit(function (e) {
            e.preventDefault();
            $.ajax({
                url: "{{ route('terrenos.store') }}",
                method: "POST",
                data: $(this).serialize(),
                success: function () {
                    $('#modalCrearTerreno').modal('hide');
                    Swal.fire('¡Registrado!', 'Terreno creado correctamente.', 'success').then(() => location.reload());
                },
                error: function (xhr) {
                    mostrarErrores(xhr);
                }
            });
        });

        // RELLENAR MODAL EDITAR
        $('.btn-editar').click(function () {
            $('#edit_id').val($(this).data('id'));
            $('#edit_id_lotizacion').val($(this).data('id_lotizacion'));
            $('#edit_manzana').val($(this).data('manzana'));
            $('#edit_lote').val($(this).data('lote'));
            $('#edit_area').val($(this).data('area'));
            $('#edit_estado').val($(this).data('estado'));
            $('#edit_id_via').val($(this).data('id_via'));
        });

        // EDITAR
        $('#formEditarTerreno').submit(function (e) {
            e.preventDefault();
            const id = $('#edit_id').val();
            $.ajax({
                url: `/terrenos/${id}`,
                method: 'POST',
                data: $(this).serialize(),
                success: function () {
                    $('#modalEditarTerreno').modal('hide');
                    Swal.fire('¡Actualizado!', 'Terreno actualizado correctamente.', 'success').then(() => location.reload());
                },
                error: function (xhr) {
                    mostrarErrores(xhr);
                }
            });
        });

        // ELIMINAR
        $('.btn-eliminar').click(function () {
            const id = $(this).data('id');
            Swal.fire({
                title: '¿Eliminar terreno?',
                text: "Esta acción no se puede deshacer",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Sí, eliminar',
                cancelButtonText: 'Cancelar'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: `/terrenos/${id}`,
                        method: 'POST',
                        data: {
                            _token: "{{ csrf_token() }}",
                            _method: "DELETE"
                        },
                        success: function () {
                            Swal.fire('¡Eliminado!', 'Terreno eliminado correctamente.', 'success')
                                .then(() => location.reload());
                        },
                        error: function () {
                            Swal.fire('Error', 'No se pudo eliminar.', 'error');
                        }
                    });
                }
            });
        });

        function mostrarErrores(xhr) {
            let errores = xhr.responseJSON.errors;
            let mensaje = 'Ocurrió un error.';
            if (errores) {
                mensaje = Object.values(errores).map(e => `• ${e}`).join('<br>');
            }
            Swal.fire({ icon: 'error', title: 'Error', html: mensaje });
        }

    });
</script>




@endsection
