@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 Tipe 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="#typeRoomModal" id="addTypeRoomBtn">
                    <i class="fas fa-plus"></i> Tambah Tipe Kamar
                </button>
            </div>
            <div class="table-responsive">
                <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Nama Tipe Kamar</th>
                            <th>Harga Per/Malam</th>
                            <th>Harga Per/Orang</th>
                            <th>Harga Per/Jam</th>
                            <th>PPN (%)</th>
                            <th>Deskripsi</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>

                    <tbody>
                        @foreach ($ms_type_rooms as $type)
                        <tr>
                            <td>{{ $loop->iteration }}</td>
                            <td>{{ $type->name ?? '' }}</td>
                            <td>Rp {{ number_format($type->harga_per_malam ?? 0, 0, ',', '.') }}</td>
                            <td>Rp {{ number_format($type->harga_per_orang ?? 0, 0, ',', '.') }}</td>
                            <td>Rp {{ number_format($type->harga_per_jam ?? 0, 0, ',', '.') }}</td>

                            <td>{{ $type->ppn ?? 0 }}%</td>
                            <td>{{ Str::limit($type->description ?? '-', 50) }}</td>
                            <td>
                                <button class="btn btn-info btn-sm" onclick="viewTypeRoom({{$type->id}})">
                                    <i class="fas fa-eye"></i>
                                </button>
                               <button class="btn btn-warning btn-sm"
    onclick="editTypeRoom(
        {{$type->id}},
        '{{ addslashes($type->name) }}',
        {{$type->harga_per_malam ?? 0}},
        {{$type->harga_per_orang ?? 0}},
        {{$type->harga_per_jam ?? 0}},
        {{$type->ppn ?? 0}},
        '{{ addslashes($type->description ?? '') }}'
    )">
    <i class="fas fa-edit"></i>
</button>

                                <button onclick="deleteTypeRoom({{$type->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 Tipe Kamar -->
<div class="modal fade" id="typeRoomModal" tabindex="-1" role="dialog" aria-labelledby="typeRoomModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="typeRoomModalLabel">Tambah Tipe Kamar</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form id="typeRoomForm" method="POST">
                @csrf
                <div id="methodField"></div>
                <input type="hidden" name="id" id="typeRoomId" value="" hidden>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label for="name">Nama Tipe Kamar <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="name" name="name" placeholder="Contoh: Standard Room, Deluxe Room, Suite" required>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="harga_per_malam">Harga Per Malam <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">Rp</span>
                                    </div>
                                    <input type="number" class="form-control" id="harga_per_malam" name="harga_per_malam" min="0" step="1000" placeholder="0" required>
                                </div>
                                <small class="text-muted">Harga dasar per malam untuk tipe kamar ini</small>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="harga_per_orang">Harga Per Orang <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">Rp</span>
                                    </div>
                                    <input type="number" class="form-control" id="harga_per_orang" name="harga_per_orang" min="0" step="1000" placeholder="0" required>
                                </div>
                                <small class="text-muted">Harga tambahan per orang tambahan</small>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                        <div class="form-group">
                                <label for="harga_per_jam">Harga Per Jam <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">Rp</span>
                                    </div>
                                    <input type="number" class="form-control" id="harga_per_jam" name="harga_per_jam" min="0" step="1000" placeholder="0" required>
                                </div>
                                <small class="text-muted">Harga dasar per jam untuk tipe kamar/ruangan ini</small>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="ppn">PPN (%) <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <input type="number" class="form-control" id="ppn" name="ppn" min="0" max="100" step="0.1" placeholder="0" required>
                                    <div class="input-group-append">
                                        <span class="input-group-text">%</span>
                                    </div>
                                </div>
                                <small class="text-muted">Pajak Pertambahan Nilai (biasanya 11%)</small>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Preview Total Harga (1 Malam)</label>
                                <input type="text" class="form-control" id="total_preview" readonly style="background-color: #f8f9fa; font-weight: bold; color: #28a745;">
                                <small class="text-muted">Harga per malam + PPN</small>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="description">Deskripsi Tipe Kamar</label>
                        <textarea class="form-control" id="description" name="description" rows="4" placeholder="Masukkan deskripsi fasilitas dan keunggulan tipe kamar ini..."></textarea>
                        <small class="text-muted">Deskripsikan fasilitas, ukuran kamar, dan keunggulan yang dimiliki</small>
                    </div>

                    <!-- Info Box -->
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        <strong>Informasi:</strong>
                        <ul class="mb-0 mt-2">
                            <li>Harga per malam adalah tarif dasar untuk kamar ini</li>
                            <li>Harga per orang digunakan untuk tamu tambahan di atas kapasitas standar</li>
                            <li>PPN akan otomatis ditambahkan ke total tagihan</li>
                        </ul>
                    </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>

<!-- Modal untuk View Detail -->
<div class="modal fade" id="viewTypeRoomModal" tabindex="-1" role="dialog" aria-labelledby="viewTypeRoomModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="viewTypeRoomModalLabel">Detail Tipe Kamar</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12">
                        <table class="table table-borderless">
                            <tr>
                                <td width="30%"><strong>Nama Tipe Kamar</strong></td>
                                <td>: <span id="view_name"></span></td>
                            </tr>
                            <tr>
                                <td><strong>Harga Per Malam</strong></td>
                                <td>: <span id="view_harga_malam" class="text-success font-weight-bold"></span></td>
                            </tr>
                            <tr>
                                <td><strong>Harga Per Orang</strong></td>
                                <td>: <span id="view_harga_orang" class="text-info font-weight-bold"></span></td>
                            </tr>
                            <tr>
                                <td><strong>Harga Per Jam</strong></td>
                                <td>: <span id="view_harga_perjam" class="text-info font-weight-bold"></span></td>
                            </tr>
                            <tr>
                                <td><strong>PPN</strong></td>
                                <td>: <span id="view_ppn"></span>%</td>
                            </tr>
                            <tr>
                                <td><strong>Total dengan PPN</strong></td>
                                <td>: <span id="view_total" class="text-primary font-weight-bold"></span></td>
                            </tr>
                            <tr>
                                <td><strong>Deskripsi</strong></td>
                                <td>: <span id="view_description"></span></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </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 price calculation
    $('#harga_per_malam, #ppn').on('input', function() {
        calculateTotal();
    });


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

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

// Calculate total price with PPN
function calculateTotal() {
    const hargaPerMalam = parseFloat($('#harga_per_malam').val()) || 0;
    const ppn = parseFloat($('#ppn').val()) || 0;

    const totalPPN = (hargaPerMalam * ppn / 100);
    const total = hargaPerMalam + totalPPN;

    if (hargaPerMalam > 0) {
        $('#total_preview').val('Rp ' + new Intl.NumberFormat('id-ID').format(total));
    } else {
        $('#total_preview').val('');
    }
}

// Add new type room
$('#addTypeRoomBtn').click(function() {
    resetModal();
    $('#typeRoomModalLabel').text('Tambah Tipe Kamar Baru');
    $('#submitBtn').html('<i class="fas fa-save"></i> Simpan');
    isEdit = false;
});

// Edit type room function
function editTypeRoom(id, name, hargaPerMalam, hargaPerOrang, hargaPerJam, ppn, description) {
    isEdit = true;
    editId = id;

    $('#typeRoomModalLabel').text('Edit Tipe Kamar');
    $('#submitBtn').html('<i class="fas fa-save"></i> Update');
    $('#methodField').html('@method("PUT")');

    // Fill form with existing data
    $('#name').val(name);
    $('#typeRoomId').val(id);

    $('#harga_per_malam').val(hargaPerMalam);
    $('#harga_per_jam').val(hargaPerJam);

    $('#harga_per_orang').val(hargaPerOrang);
    $('#ppn').val(ppn);
    $('#description').val(description);

    // Calculate total
    calculateTotal();

    $('#typeRoomModal').modal('show');
}

// View type room function
function viewTypeRoom(id) {
    // Find the row data
    const row = $(`button[onclick="viewTypeRoom(${id})"]`).closest('tr');
    const name = row.find('td:nth-child(2)').text();
    const hargaMalam = row.find('td:nth-child(3)').text();
    const hargaOrang = row.find('td:nth-child(4)').text();
    const hargaPerjam = row.find('td:nth-child(5)').text();

    const ppn = row.find('td:nth-child(5)').text();
    const description = row.find('td:nth-child(6)').text();

    // Calculate total with PPN
    const hargaNumeric = parseFloat(hargaMalam.replace(/[^0-9]/g, ''));
    const ppnNumeric = parseFloat(ppn.replace('%', ''));
    const total = hargaNumeric + (hargaNumeric * ppnNumeric / 100);

    // Fill view modal
    $('#view_name').text(name);
    $('#view_harga_malam').text(hargaMalam);
    $('#view_harga_orang').text(hargaOrang);
    $('#view_harga_perjam').text(hargaPerjam);

    $('#view_ppn').text(ppnNumeric);
    $('#view_total').text('Rp ' + new Intl.NumberFormat('id-ID').format(total));
    $('#view_description').text(description === '-' ? 'Tidak ada deskripsi' : description);

    $('#viewTypeRoomModal').modal('show');
}

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

// Submit form function
function submitForm() {
    const formData = new FormData($('#typeRoomForm')[0]);
    const url = isEdit ? `{{ url('ms-type-rooms') }}/${editId}` : `{{ route('ms-type-rooms.store') }}`;

    // Show loading
    $('#submitBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Menyimpan...');

    $.ajax({
        url: url,
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            Swal.fire({
                title: 'Berhasil!',
                text: isEdit ? 'Data tipe kamar berhasil diupdate!' : 'Data tipe kamar berhasil disimpan!',
                icon: 'success',
                timer: 2000,
                showConfirmButton: false
            }).then(() => {
                location.reload();
            });
        },
        error: function(xhr) {
            let errors = xhr.responseJSON.errors;

            // Clear previous errors
            $('.form-control').removeClass('is-invalid');
            $('.invalid-feedback').text('');

            // Show validation errors
            if (errors) {
                Object.keys(errors).forEach(function(key) {
                    $(`#${key}`).addClass('is-invalid');
                    $(`#${key}`).siblings('.invalid-feedback').text(errors[key][0]);
                });
            }

            Swal.fire({
                title: 'Error!',
                text: 'Terjadi kesalahan saat menyimpan data. Silakan periksa form Anda.',
                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() {
    $('#typeRoomForm')[0].reset();
    $('#methodField').empty();
    $('.form-control').removeClass('is-invalid');
    $('.invalid-feedback').text('');
    $('#total_preview').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
