@extends('admin-layouts.master')

@section('content')
<div class="container-fluid">

    

    <!-- DataTales Example -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Data Kamar</h6>
        </div>
        <div class="card-body">
            <div class="text-right px-3 py-3">
                <button type="button" class="btn btn-outline-primary" data-toggle="modal" data-target="#roomModal" id="addRoomBtn">
                    <i class="fas fa-plus"></i> Tambah Kamar
                </button>
            </div>
            <div class="table-responsive">
                <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Nomor Kamar</th>
                            <th>Tipe Kamar</th>
                            <th>Harga Per/Malam</th>
                            <th>Max Dewasa</th>
                            <th>Max Anak-anak</th>
                            <th>Status</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    
                    <tbody>
                        @foreach ($ms_rooms as $u)
                        <tr>
                            <td>{{ $loop->iteration }}</td>
                            <td>{{$u->room_number ?? ''}}</td>
                            <td>{{ $u->typeRoom->name ?? '' }}</td>
                            <td>Rp {{ number_format($u->typeRoom->harga_per_malam ?? 0, 0, ',', '.') }}</td>
                            <td>{{ $u->max_capacity_adult }}</td>
                            <td>{{ $u->max_capacity_child }}</td>
                            <td>
                                @if($u->status == 'available')
                                    <span class="badge badge-success">Tersedia</span>
                                @elseif($u->status == 'occupied')
                                    <span class="badge badge-danger">Terisi</span>
                                @else
                                    <span class="badge badge-warning">Maintenance</span>
                                @endif
                            </td>
                            <td>
                                <button class="btn btn-info btn-sm" onclick="viewRoom({{$u->id}})">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <button class="btn btn-warning btn-sm" onclick="editRoom({{$u->id}}, '{{$u->room_number}}', {{$u->type_room_id}}, {{$u->max_capacity_adult}}, {{$u->max_capacity_child}}, '{{$u->status}}', '{{addslashes($u->description ?? '')}}')">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button onclick="deleteRoom({{$u->id}})" class="btn btn-danger btn-sm">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>

<!-- Modal untuk Tambah/Edit Kamar -->
<div class="modal fade" id="roomModal" tabindex="-1" role="dialog" aria-labelledby="roomModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="roomModalLabel">Tambah Kamar</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form id="roomForm" method="POST" action="{{ route('ms-rooms.store') }}">
                @csrf
                <div id="methodField"></div>
                <input type="hidden" name="id" id="room_id" value="">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="room_number">Nomor Kamar <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="room_number" name="room_number" required>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="type_room_id">Tipe Kamar <span class="text-danger">*</span></label>
                                <select class="form-control" id="type_room_id" name="type_room_id" required>
                                    <option value="">Pilih Tipe Kamar</option>
                                    @foreach($ms_type_rooms as $type)
                                        <option value="{{$type->id}}" data-price="{{$type->harga_per_malam}}">
                                            {{$type->name}} - Rp {{number_format($type->harga_per_malam, 0, ',', '.')}}
                                        </option>
                                    @endforeach
                                </select>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="max_capacity_adult">Kapasitas Maksimal Dewasa <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="max_capacity_adult" name="max_capacity_adult" min="1" required>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="max_capacity_child">Kapasitas Maksimal Anak-anak <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="max_capacity_child" name="max_capacity_child" min="0" value="0" required>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="status">Status <span class="text-danger">*</span></label>
                                <select class="form-control" id="status" name="status" required>
                                    <option value="">Pilih Status</option>
                                    <option value="available">Tersedia</option>
                                    <option value="occupied">Terisi</option>
                                    <option value="maintenance">Maintenance</option>
                                </select>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Harga per Malam</label>
                                <input type="text" class="form-control" id="display_price" readonly style="background-color: #f8f9fa;">
                                <small class="text-muted">Harga akan otomatis terisi berdasarkan tipe kamar</small>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="description">Deskripsi (Opsional)</label>
                        <textarea class="form-control" id="description" name="description" rows="3" placeholder="Masukkan deskripsi kamar..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary" id="submitBtn">
                        <i class="fas fa-save"></i> Simpan
                    </button>
                </div>
            </form>
        </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 type room change to update price display
    $('#type_room_id').change(function() {
        const selectedOption = $(this).find('option:selected');
        const price = selectedOption.data('price');
        if (price) {
            $('#display_price').val('Rp ' + new Intl.NumberFormat('id-ID').format(price));
        } else {
            $('#display_price').val('');
        }
    });

    // Handle form submission
    $('#roomForm').submit(function(e) {
        e.preventDefault();
        submitForm();
    });

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

// Add new room
$('#addRoomBtn').click(function() {
    resetModal();
    $('#roomModalLabel').text('Tambah Kamar Baru');
    $('#submitBtn').html('<i class="fas fa-save"></i> Simpan');
    $('#roomForm').attr('action', '{{ route("ms-rooms.store") }}');
    isEdit = false;
});

// Edit room function - Fixed parameter order and added description
function editRoom(id, roomNumber, typeRoomId, maxAdult, maxChild, status, description = '') {
    isEdit = true;
    editId = id;
    
    $('#roomModalLabel').text('Edit Kamar');
    $('#submitBtn').html('<i class="fas fa-save"></i> Update');
    $('#methodField').html('@method("PUT")');
    $('#roomForm').attr('action', `{{ url('ms-rooms') }}/${id}`);
    
    // Fill form with existing data
    $('#room_number').val(roomNumber);
    $('#type_room_id').val(typeRoomId).trigger('change');
    $('#max_capacity_adult').val(maxAdult);
    $('#max_capacity_child').val(maxChild);
    $('#status').val(status);
    $('#description').val(description);
    $('#room_id').val(id);
    
    $('#roomModal').modal('show');
}

// View room function
function viewRoom(id) {
    // You can implement view functionality here
    // For now, just show an alert
    Swal.fire({
        title: 'Detail Kamar',
        text: 'Fungsi view akan diimplementasikan sesuai kebutuhan',
        icon: 'info'
    });
}

// Delete room function
function deleteRoom(id) {
    Swal.fire({
        title: 'Apakah Anda yakin?',
        text: "Data 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('ms-rooms') }}/${id}`);
            $('#deleteForm').submit();
        }
    });
}

// Submit form function
function submitForm() {
    const formData = new FormData($('#roomForm')[0]);
    const url = $('#roomForm').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) {
            $('#roomModal').modal('hide');
            Swal.fire({
                title: 'Berhasil!',
                text: response.message || (isEdit ? 'Data kamar berhasil diupdate!' : 'Data kamar 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() {
    $('#roomForm')[0].reset();
    $('#methodField').empty();
    $('.form-control').removeClass('is-invalid');
    $('.invalid-feedback').text('');
    $('#display_price').val('');
    $('#room_id').val('');
    isEdit = false;
    editId = null;
}

// Handle success messages from server
@if(session('success'))
    Swal.fire({
        title: 'Berhasil!',
        text: '{{ session("success") }}',
        icon: 'success',
        timer: 3000,
        showConfirmButton: false
    });
@endif

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

@endpush

@endsection