@extends('admin-layouts.master')
@section('content')
<div class="container-fluid">

    <!-- Page Heading --> 

    <!-- DataTales Example -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Data Tamu</h6>
        </div>
        <div class="card-body">
            <div class="text-right px-3 py-3">
                <a href="{{route('guests.create')}}" type="button" class="btn btn-outline-primary">
                    <i class="fas fa-plus"></i> Tambah Tamu
                </a>
            </div>
            <div class="table-responsive">
                <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Nama</th>
                            <th>No. Identitas</th>
                            <th>Telepon</th>
                            <th>Email</th>
                            <th>Alamat</th>
                            <th>Tgl Daftar</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    
                    <tbody>
                        @foreach ($guests as $g)
                        <tr>
                            <td>{{ $loop->iteration }}</td>
                            <td>{{$g->name ?? ''}}</td>
                            <td>{{ $g->identity_number ?? '-' }}</td>
                            <td>{{ $g->phone ?? '-' }}</td>
                            <td>{{ $g->email ?? '-' }}</td>
                            <td>{{ Str::limit($g->address ?? '-', 30) }}</td>
                            <td>{{ $g->created_at ? $g->created_at->format('d/m/Y') : '-' }}</td>
                            <td>
                                {{-- <button class="btn btn-info btn-sm" onclick="viewGuest({{$g->id}})">
                                    <i class="fas fa-eye"></i>
                                </button> --}}
                                <a href="{{ route('guests.edit', $g->id) }}" class="btn btn-warning btn-sm">
                                    <i class="fas fa-edit"></i>
                                    
                                </a>
                                {{-- <button class="btn btn-warning btn-sm" onclick="editGuest({{$g->id}}, '{{addslashes($g->name ?? '')}}', '{{$g->identity_number ?? ''}}', '{{$g->phone ?? ''}}', '{{$g->email ?? ''}}', '{{addslashes($g->address ?? '')}}')">
                                    <i class="fas fa-edit"></i>
                                </button> --}}
                                <button onclick="deleteGuest({{$g->id}})" class="btn btn-danger btn-sm">
                                    <i class="fas fa-trash"></i>
                                </button>
                                <button class="btn btn-success btn-sm" onclick="viewBookingHistory({{$g->id}})">
                                    <i class="fas fa-history"></i>
                                </button>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>



<!-- Modal untuk Detail Tamu -->
<div class="modal fade" id="viewGuestModal" tabindex="-1" role="dialog" aria-labelledby="viewGuestModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="viewGuestModalLabel">Detail Tamu</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="guestDetailContent">
                <!-- Content will be loaded here -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>

<!-- Form untuk Delete -->
<form action="" method="post" id="deleteForm">
    @csrf
    @method("DELETE")
    <input type="submit" value="Hapus" style="display:none">
</form>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>

<script>
// Global variables
let isEdit = false;
let editId = null;

// Event listeners
$(document).ready(function() {
    // Handle form submission
    $('#guestForm').submit(function(e) {
        e.preventDefault();
        submitForm();
    });

    // Reset modal when closed
    $('#guestModal').on('hidden.bs.modal', function() {
        resetModal();
    });

    // Format phone number input
    $('#phone').on('input', function() {
        let value = $(this).val();
        // Allow only numbers, +, -, and spaces
        value = value.replace(/[^\d+\-\s]/g, '');
        $(this).val(value);
    });

    // Format identity number input
    $('#identity_number').on('input', function() {
        let value = $(this).val();
        // Allow only alphanumeric characters
        value = value.replace(/[^a-zA-Z0-9]/g, '');
        $(this).val(value);
    });
});

// Add new guest
$('#addGuestBtn').click(function() {
    resetModal();
    $('#guestModalLabel').text('Tambah Tamu Baru');
    $('#submitBtn').html('<i class="fas fa-save"></i> Simpan');
    $('#guestForm').attr('action', '{{ route("guests.store") }}');
    isEdit = false;
});

// Edit guest function
function editGuest(id, name, identityNumber, phone, email, address) {
    isEdit = true;
    editId = id;
    
    $('#guestModalLabel').text('Edit Data Tamu');
    $('#submitBtn').html('<i class="fas fa-save"></i> Update');
    $('#methodField').html('@method("PUT")');
    $('#guestForm').attr('action', `{{ url('guests') }}/${id}`);
    
    // Fill form with existing data
    $('#name').val(name);
    $('#identity_number').val(identityNumber);
    $('#phone').val(phone);
    $('#email').val(email);
    $('#address').val(address);
    $('#guest_id').val(id);
    
    $('#guestModal').modal('show');
}

// View guest function
function viewGuest(id) {
    // Show loading
    $('#guestDetailContent').html('<div class="text-center"><i class="fas fa-spinner fa-spin"></i> Memuat data...</div>');
    $('#viewGuestModal').modal('show');
    
    // Fetch guest details via AJAX
    $.ajax({
        url: `{{ url('guests') }}/${id}`,
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        },
        success: function(response) {
            if (response.success) {
                const guest = response.data;
                const content = `
                    <div class="row">
                        <div class="col-md-6">
                            <table class="table table-borderless">
                                <tr>
                                    <th width="40%">Nama:</th>
                                    <td>${guest.name || '-'}</td>
                                </tr>
                                <tr>
                                    <th>No. Identitas:</th>
                                    <td>${guest.identity_number || '-'}</td>
                                </tr>
                                <tr>
                                    <th>Telepon:</th>
                                    <td>${guest.phone || '-'}</td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <table class="table table-borderless">
                                <tr>
                                    <th width="40%">Email:</th>
                                    <td>${guest.email || '-'}</td>
                                </tr>
                                <tr>
                                    <th>Tgl Daftar:</th>
                                    <td>${guest.created_at_formatted || '-'}</td>
                                </tr>
                                <tr>
                                    <th>Update Terakhir:</th>
                                    <td>${guest.updated_at_formatted || '-'}</td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-12">
                            <table class="table table-borderless">
                                <tr>
                                    <th width="20%">Alamat:</th>
                                    <td>${guest.address || '-'}</td>
                                </tr>
                            </table>
                        </div>
                    </div>
                `;
                $('#guestDetailContent').html(content);
            }
        },
        error: function() {
            $('#guestDetailContent').html('<div class="alert alert-danger">Gagal memuat data tamu.</div>');
        }
    });
}

// View booking history function
function viewBookingHistory(id) {
    Swal.fire({
        title: 'Riwayat Booking',
        text: 'Fitur riwayat booking akan diimplementasikan setelah modul booking selesai',
        icon: 'info'
    });
}

// Delete guest function
function deleteGuest(id) {
    Swal.fire({
        title: 'Apakah Anda yakin?',
        text: "Data tamu yang sudah dihapus tidak dapat dikembalikan!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Ya, Hapus!',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.value) {
            // Set form action and submit
            $('#deleteForm').attr('action', `{{ url('guests') }}/${id}`);
            $('#deleteForm').submit();
        }
    });
}

// Submit form function
function submitForm() {
    const formData = new FormData($('#guestForm')[0]);
    const url = $('#guestForm').attr('action');
    
    // Show loading
    $('#submitBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Menyimpan...');
    
    // Clear previous errors
    $('.form-control').removeClass('is-invalid');
    $('.invalid-feedback').text('');
    
    $.ajax({
        url: url,
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        },
        success: function(response) {
            $('#guestModal').modal('hide');
            Swal.fire({
                title: 'Berhasil!',
                text: response.message || (isEdit ? 'Data tamu berhasil diupdate!' : 'Data tamu berhasil disimpan!'),
                icon: 'success',
                timer: 2000,
                showConfirmButton: false
            }).then(() => {
                location.reload();
            });
        },
        error: function(xhr) {
            console.log('Error response:', xhr);
            
            if (xhr.status === 422) {
                // Validation errors
                const errors = xhr.responseJSON.errors;
                if (errors) {
                    Object.keys(errors).forEach(function(key) {
                        const field = $(`#${key}`);
                        field.addClass('is-invalid');
                        field.siblings('.invalid-feedback').text(errors[key][0]);
                    });
                }
                
                Swal.fire({
                    title: 'Validasi Error!',
                    text: 'Silakan periksa form Anda.',
                    icon: 'error'
                });
            } else {
                // Other errors
                const message = xhr.responseJSON?.message || 'Terjadi kesalahan saat menyimpan data.';
                Swal.fire({
                    title: 'Error!',
                    text: message,
                    icon: 'error'
                });
            }
        },
        complete: function() {
            $('#submitBtn').prop('disabled', false).html(isEdit ? '<i class="fas fa-save"></i> Update' : '<i class="fas fa-save"></i> Simpan');
        }
    });
}

// Reset modal function
function resetModal() {
    $('#guestForm')[0].reset();
    $('#methodField').empty();
    $('.form-control').removeClass('is-invalid');
    $('.invalid-feedback').text('');
    $('#guest_id').val('');
    isEdit = false;
    editId = null;
}



@if(session('error'))
    Swal.fire({
        title: 'Error!',
        text: '{{ session("error") }}',
        icon: 'error'
    });
@endif
</script>

@endpush

@endsection