@extends('layouts.master')

@section('styles')
    <style>
        .card-body label {
            font-size: 13px;
            color: #6c757d;
        }

        .card-body .form-control,
        .card-body .form-select {
            font-size: 14px;
        }

        #search-button {
            font-weight: 600;
            letter-spacing: .3px;
        }
        .table-garis, .garis {
            border: 0.1px solid black; /* Sets a 1px solid black border */
            border-collapse: collapse;
        }

        .text-label {
            color: #000000;
        }
/* 
        .table-selectable tbody tr {
            cursor: pointer;
            transition: 0.15s;
        }

        .table-selectable tbody tr:hover {
            background-color: #f2f6ff;
        }

        .table-selectable tbody tr.selected {
            background-color: #0d6efd !important;
            color: #fff;
        }

        .table-selectable tbody tr.selected td {
            color: #fff !important;
        } */
    </style>
@endsection

@section('content')
    <!-- partial -->
    <div class="container-fluid page-body-wrapper">
        <div class="main-panel">
            <div class="content-wrapper">
                <div class="row">
                    <div class="col-2">
                    </div>
                    <div class="col-12 col-md-8 grid-margin justify-content-center stretch-card">
                        <div class="card">
                            <div class="card-body">
                            <h4 class="card-title">Daftar Pintu/Pos</h4>
                            <div class="table-responsive mb-2">
                                <table class="table table-bordered table-selectable" id="example" data-url="{{ route('getMember') }}">
                                    <thead>
                                        <tr>
                                            <th class="p-3" width="5%">No.</th>
                                            <th style="text-align: center;">Nama Pintu</th>
                                            <th style="text-align: center;">Mode Pintu</th>
                                            <th style="text-align: center;">Grace Periode</th>
                                            <th style="text-align: center;">Manless?</th>
                                            <th style="text-align: center;">Pengaturan</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach ($Gate as $pintu)
                                            @php
                                                if ($pintu->jenis === 0 ) {
                                                    $jenis = 'Masuk';
                                                } elseif ($pintu->jenis === 1) {
                                                    $jenis = 'Keluar';
                                                } 

                                                $isManless = $pintu->manless === 1 
                                                ? '<span class="d-inline-block rounded-circle bg-success" style="width:12px;height:12px;"></span>' 
                                                : '<span class="d-inline-block rounded-circle bg-danger" style="width:12px;height:12px;"></span>';
                                            @endphp
                                            <tr>
                                                <td class="text-center">{{ $loop->iteration }}</td>
                                                {{-- <td class="text-center" width="7%">{{ $pintu->id }}</td> --}}
                                                <td>{{ $pintu->nama }} <strong> - ({{ $pintu->id }})</strong></td>
                                                <td width="10%">{{
                                                        match($pintu->jenis) {
                                                            0 => 'Masuk',
                                                            1 => 'Keluar',
                                                            2 => 'Transit',
                                                            3 => 'Emergency',
                                                            default => '-'
                                                        }
                                                    }}</td>
                                                <td class="text-center" width="7%"><span class="d-inline-block rounded-circle 
                                                        {{ $pintu->grace_period === 1 ? 'bg-success' : 'bg-danger' }}"
                                                        style="width:12px;height:12px;">
                                                    </span></td>
                                                <td class="text-center" width="7%"><span class="d-inline-block rounded-circle 
                                                        {{ $pintu->manless === 1 ? 'bg-success' : 'bg-danger' }}"
                                                        style="width:12px;height:12px;">
                                                    </span>
                                                </td>
                                                <td class="text-center" width="12%">
                                                    <a class="btn btn-warning btn-sm parameter-button" id="parameter" data-bs-toggle="modal" data-bs-target=".bd-ubah-modal-lg">Pos</a>
                                                    <button class="btn btn-primary btn-sm hardware-button" data-id="{{ $pintu->id }}" data-nama="{{ $pintu->nama }}">Hardware</button>
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                            <div class="d-flex justify-content-center align-items-center mt-2">
                                <div>
                                    <button class="btn btn-primary btn-sm add-button" data-bs-toggle="modal" data-bs-target=".bd-example-modal-lg">Tambah</button>
                                {{-- </div>
                                <div id="rowActions" class="d-none"> --}}
                                    <button class="btn btn-warning btn-sm edit-button" id="btnEdit" data-bs-toggle="modal" data-bs-target=".bd-ubah-modal-lg">Tambah</button>
                                    <button class="btn btn-danger btn-sm" id="btnDelete">Hapus</button>
                                    <button class="btn btn-info btn-sm" id="btnDetail">Detail</button>
                                </div>
                            </div>
                                <!-- ADD MEMMBER MODAL -->
                                    {{-- @include('stiker.tambah-stiker')
                                    @include('stiker.ubah-stiker') --}}
                                <!-- END MEMMBER MODAL -->
                            </div>
                        </div>
                    </div>
                    <div class="col-2">
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('javascript')
<!--********* Scripts *********-->
    <!-- Datatable -->
    <!--********* Scripts *********-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/metisMenu/3.0.7/metisMenu.min.js"></script>
    <script src="{{asset ('vendor/moment/moment.min.js') }}"></script>
    <script src="{{asset ('vendor/bootstrap-daterangepicker/daterangepicker.js') }}"></script>
	<script src="{{asset ('vendor/bootstrap-select/dist/js/bootstrap-select.min.js') }}"></script>
    <script src="{{asset ('vendor/sweetalert2/dist/sweetalert2.min.js') }}"></script>
    <script src="{{asset ('js/custom.min.js') }}"></script>
	<script src="{{asset ('js/dlabnav-init.js') }}"></script>
    <script src="{{asset ('js/member/index.js') }}"></script>
    <script src="{{asset ('js/member/member-register.js') }}"></script>
    <script>
        $(document).ready(function () {

            $(document).on('click', '.hardware-button', function () {
                let row = $(this).closest('tr');

                // kalau sudah ada baris edit, hapus dulu
                $('.edit-row').remove();

                let id   = $(this).data('id');
                let nama = $(this).data('nama');
                $.ajax({
                    url: "{{ route('hardware.show', '') }}/" + id,
                    type: 'GET',
                    success: function (r) {
                        console.log(r);

                        let colSpan = row.children('td').length;

                        // Field yang mau ditampilkan (pilih sendiri mau yang mana)
                        let fields = [
                            ['printer1_avail', 'Printer Status'],
                            ['printer1_conn', 'Printer Connection'],
                            ['printer1_spd', 'Printer Speed/Baudrate'],
                            ['video1_avail', 'Kamera Status'],
                            ['video1_conn', 'Kamera URL/Path'],
                            ['sound_avail', 'Sound Status'],
                            ['bg_avail', 'BGate Status'],
                            ['bg_conn', 'BGate Connection'],
                            ['bank_reader_avail', 'Reader BANK Status'],
                            ['bank_reader_comm', 'Reader BANK Connection'],
                            ['bank_reader_key', 'Reader BANK Key/Parameter'],
                        ];

                        let rows = '';

                        for (let i = 0; i < fields.length; i ++) {

                            let f1 = fields[i];

                            rows += `
                                <tr>
                                    <td class="fw-semibold text-muted text-label"><strong>${f1[1]}</strong></td>
                                    <td>
                                        <span class="view-mode">${formatValue(f1[0], r[f1[0]])}</span>
                                        <input type="text"
                                            class="form-control form-control-sm edit-mode d-none"
                                            data-key="${f1[0]}"
                                            value="${r[f1[0]] ?? ''}">
                                    </td>
                                </tr>
                            `;
                        }

                        let editHtml = `
                        <tr class="edit-row" data-id="${id}">
                            <td colspan="${colSpan}">
                                <div class="card shadow-sm">
                                    <div class="card-header d-flex justify-content-between align-items-center">
                                        <strong>Hardware Configuration</strong>
                                        <div>
                                            <button class="btn btn-sm btn-primary btn-edit">Edit</button>
                                            <button class="btn btn-sm btn-success btn-save d-none">Save</button>
                                            <button class="btn btn-sm btn-secondary btn-cancel d-none">Cancel</button>
                                        </div>
                                    </div>
                                    <div class="card-body p-2">
                                        <table class="table table-bordered table-sm align-middle mb-0">
                                            <thead class="table-light">
                                                <tr>
                                                    <th width="15%">Setting</th>
                                                    <th width="85%">Value</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                ${rows}
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        `;

                        row.after(editHtml);
                    },
                    error: function (xhr) {
                        console.error(xhr.responseText);
                    }        
                });
            });

            // MODE EDIT
            $(document).on('click', '.btn-edit', function () {

                $('.view-mode').addClass('d-none');
                $('.edit-mode').removeClass('d-none');

                $('.btn-edit').addClass('d-none');
                $('.btn-save, .btn-cancel').removeClass('d-none');
            });

            // CANCEL
            $(document).on('click', '.btn-cancel', function () {

                $('.edit-mode').addClass('d-none');
                $('.view-mode').removeClass('d-none');

                $('.btn-save, .btn-cancel').addClass('d-none');
                $('.btn-edit').removeClass('d-none');
            });

            // SAVE
            $(document).on('click', '.btn-save', function () {

                let dataToSend = {};

                $('.edit-mode').each(function () {
                    let key = $(this).data('key');
                    dataToSend[key] = $(this).val();
                });

                console.log(dataToSend);
                let gateId = $('.edit-row').data('id');

                $.ajax({
                    url: "{{ route('hardware.update', '') }}/" + gateId,
                    type: "PUT",
                    data: {
                        _token: "{{ csrf_token() }}",
                        data: dataToSend
                    },
                    success: function () {

                        $('.edit-mode').each(function () {
                            let val = $(this).val();
                            $(this).siblings('.view-mode').text(val);
                        });

                        $('.btn-cancel').click();
                        alert('Berhasil disimpan 🔥');
                    }
                });
            });

            function formatValue(key, value) {

                // kalau field *_avail kita kasih badge
                if (key.includes('_avail')) {

                    if (value == 1) {
                        return `<span class="badge rounded-pill bg-success px-3">ON</span>`;
                    } else {
                        return `<span class="badge rounded-pill bg-danger px-3">OFF</span>`;
                    }
                }

                // default
                return value ?? '-';
            }
        });

    </script>
@endsection