<!DOCTYPE html>
<html lang="en">
<head>
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Admin Dashboard</title>
	<meta content='width=device-width, initial-scale=1.0, shrink-to-fit=no' name='viewport'>
	
	<!-- Fonts and icons -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
	<script src="{{ asset('admin/js/plugin/webfont/webfont.min.js') }}"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

	<script>
		WebFont.load({
			google: {"families":["Lato:300,400,700,900"]},
			custom: {"families":["Flaticon", "Font Awesome 5 Solid", "Font Awesome 5 Regular", "Font Awesome 5 Brands", "simple-line-icons"], urls: ['../assets/css/fonts.min.css']},
			active: function() {
				sessionStorage.fonts = true;
			}
		});
	</script>

	<!-- CSS Files -->
	<link rel="stylesheet" href="{{ asset('admin/css/bootstrap.min.css') }}">
	<link rel="stylesheet" href="{{ asset('admin/css/atlantis.css') }}">
    
</head>

<body>
	<div class="wrapper">
	<div class="main-header">

	<!-- Logo Header -->
	<div class="logo-header" data-background-color="blue">		
		<div class="nav-toggle">
			<button class="btn btn-toggle toggle-sidebar"><i class="fas fa-bars"></i></button>
		</div>
	</div>
	<!-- End Logo Header -->

	<!-- Navbar Header -->
    @include('admin.navbar')
	<!-- End Navbar -->
	</div>

	<!-- Sidebar -->
    @include('admin.sidebar')
	<!-- End Sidebar -->

    <!-- Main Panel -->
    <div class="main-panel">
    <div class="content">
    <div class="panel-header bg-primary-gradient">
    <div class="page-inner py-5">
    <div class="d-flex align-items-left align-items-md-center flex-column flex-md-row">
    
    </div>
    </div>
    </div>

    <div class="page-inner mt--5">
    <div class="row mt--2">
    <div class="col-12">
    <div class="card">
    <div class="card-header">
    <div class="card-head-row">
    <div class="card-tools">
        <a href="{{ route('download.alternatif') }}" class="btn btn-info btn-border btn-round btn-sm">
        <span class="btn-label"><i class="fa fa-print"></i></span>Cetak</a>
    </div>
    </div>
    </div>

    <div class="card-body">

    <!-- Button -->
    <div class="d-flex justify-content-between align-items-center mb-4 p-3">
    <div>
        <h4 class="card-title mb-1">Manajemen Data Alternatif</h4>
        <p class="card-category text-muted mb-0">Mengelola dan memperbarui informasi sesuai kebutuhan secara tertata dan menyeluruh.</p>
    </div>
    <button class="btn btn-sm btn-primary btn-round" data-toggle="modal" data-target="#addRowModal"><i class="fa fa-plus"></i> Tambah</button>
    </div>

    <!-- Add Modal -->
    <div class="modal fade" id="addRowModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
    <div class="modal-content">
    <div class="modal-header">
        <h4 class="modal-title"><span class="fw-mediumbold">Tambah Data</span></h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    </div>
    <div class="modal-body">
        <p style="font-size: 0.9rem;" class="text-muted mb-3">Gunakan formulir ini untuk menambahkan entri alternatif baru. Pastikan seluruh data diisi dengan benar.</p>
        <form action="{{ route('tambah.alternatif') }}" method="POST">
        @csrf
        <div class="form-group">
            <label for="nama">Nama Alternatif</label>
            <input type="text" name="nama" class="form-control input-square" placeholder="Masukkan nama alternatif" required>
        </div>
        <div class="form-group">
        <label for="kurikulum_id">Pilih Kurikulum</label>
        <select name="kurikulum_id" id="kurikulum_id" class="form-control input-square" required>
            <option value="">Pilih Kurikulum</option>
                @foreach ($kurikulums as $kurikulum)
                <option value="{{ $kurikulum->id }}">{{ $kurikulum->nama }}</option>
                @endforeach
         </select>
        </div>
        <div class="form-group">
        <label for="mapel_id">Pilih Mapel</label>
        <select name="mapel_id[]" id="mapel_id" class="form-control select2" multiple="multiple" required>
        @foreach ($mapels as $mapel)
        @if($kurikulum->nama === 'Kurikulum Merdeka' && $mapel->kategori === 'Mata Pelajaran Pilihan')
            <option value="{{ $mapel->id }}">{{ $mapel->nama }}</option>
        @elseif($kurikulum->nama !== 'Kurikulum Merdeka')
            <option value="{{ $mapel->id }}">{{ $mapel->nama }}</option>
        @endif
        @endforeach
        </select>
        </div>
        <div class="modal-footer">
            <button type="submit" class="btn btn-primary">Tambah</button>
            <button type="button" class="btn btn-danger" data-dismiss="modal">Batal</button>
        </div>
    </form>
    </div>
    </div>
    </div>
    </div>

    <!-- Update Modal -->
    <div class="modal fade" id="updateRowModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
    <div class="modal-content">
    <div class="modal-header">
        <h4 class="modal-title"><span class="fw-mediumbold">Update Data</span></h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    </div>
    <div class="modal-body">
    <p style="font-size: 0.9rem;" class="text-muted mb-3">Gunakan formulir ini untuk mengupdate data alternatif. Pastikan seluruh data diisi dengan benar.</p>
    <form id="formUpdateAlternatif" method="POST">
    @csrf
    @method('PUT')
        <div class="form-group">
            <label for="updateNama">Nama Alternatif</label>
            <input type="text" id="updateNama" name="nama" class="form-control input-square" required>
        </div>
        <div class="form-group">
            <label for="updateKurikulum">Pilih Kurikulum</label>
            <select name="kurikulum_id" id="updateKurikulum" class="form-control input-square" required>
                <option value="">Pilih Kurikulum</option>
                @foreach ($kurikulums as $kurikulum)
                <option value="{{ $kurikulum->id }}">{{ $kurikulum->nama }}</option>
                 @endforeach
            </select>
        </div>
        <div class="form-group">
            <label for="mapel_id">Pilih Mapel</label>
            <select name="mapel_id[]" id="mapelAlternatif" class="form-control select2" multiple="multiple" required>
            @foreach ($mapels as $mapel)
            @if($kurikulum->nama === 'Kurikulum Merdeka' && $mapel->kategori === 'Mata Pelajaran Pilihan')
                <option value="{{ $mapel->id }}">{{ $mapel->nama }}</option>
                @elseif($kurikulum->nama !== 'Kurikulum Merdeka')
                <option value="{{ $mapel->id }}">{{ $mapel->nama }}</option>
            @endif
            @endforeach
            </select>
        </div>
        <div class="modal-footer">
            <button type="submit" class="btn btn-primary">Update</button>
            <button type="button" class="btn btn-danger" data-dismiss="modal">Batal</button>
        </div>
    </form>
    </div>
    </div>
    </div>
    </div>

    <!-- Table -->
    <div class="table-responsive">
    <table id="add-row" class="display table table-striped table-hover">
    <thead>
        <tr>
            <th>No</th>
            <th>Nama Alternatif</th>
            <th>Kurikulum</th>
            <th>Mapel</th>
            <th>Aksi</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>No</th>
            
            <th>Nama Alternatif</th>
            <th>Kurikulum</th>
            <th>Mapel</th>
            <th>Aksi</th>
        </tr>
    </tfoot>
    <tbody>
    @foreach($alternatifs as $index => $alternatif)
    <tr>
        <td>{{ $index + 1 }}</td>
        
        <td>{{ $alternatif->nama }}</td>
        <td>{{ $alternatif->kurikulum->nama }}</td>
        <td>
            @foreach($alternatif->mapels as $mapel)
                {{ $mapel->nama }}@if(!$loop->last), @endif
             @endforeach
        </td>
        <td>
        <div class="form-button-action">
            <button type="button" class="btn btn-link p-3 text-primary editBtn"
                data-id="{{ $alternatif->id }}"
                
                data-nama="{{ $alternatif->nama }}"
                data-kurikulum="{{ $alternatif->kurikulum->id }}"
                data-mapel='@json($alternatif->mapels->pluck("id"))'
                data-toggle="modal"
                data-target="#updateRowModal"
                title="Edit">
                <i class="fa fa-edit"></i>
            </button>
            <a href="{{ route('hapus.alternatif', $alternatif->id) }}" class="btn btn-link p-3 text-danger" data-toggle="tooltip" title="Hapus"><i class="fas fa-trash-alt"></i></a>
        </div>
        </td>
    </tr>
    @endforeach
    </tbody>
    </table>
    </div>
    </div>
    </div>
    </div>
    </div>

    </div>
    </div>
    </div>
    <!-- End Main Panel -->

	</div>
	</div>
<!-- Script Files -->
@include('admin.script')
<script>
// Inisialisasi DataTable
    var table = $('#add-row').DataTable({
            "pageLength": 10,
            "language": {
                "search": "Cari:",
                "lengthMenu": "Tampilkan _MENU_ data per halaman",
                "zeroRecords": "Tidak ada data yang ditemukan",
                "info": "Menampilkan halaman _PAGE_ dari _PAGES_",
                "infoEmpty": "Tidak ada data tersedia",
                "infoFiltered": "(difilter dari _MAX_ total data)"
            }
    });

    // Menambah baris ke DataTable secara dummy (tanpa backend)
    $('#addRowButton').click(function () {
        
        var namaAlternatif = $("#namaAlternatif").val();
        var kurikulumAlternatif = $("#kurikulumSelect option:selected").text();
        var mapelAlternatif = $("#mapelSelect").val() || []; // Pastikan ini array

        // Validasi inputan
        if (namaAlternatif === "" || kurikulumAlternatif === "" || mapelAlternatif.length === 0) {
            alert("Semua kolom harus diisi.");
            return;
        }

        // Menyiapkan text mata pelajaran yang dipilih (ini adalah string yang kita butuhkan)
        var mapelText = $("#mapelSelect option:selected").map(function () {
            return $(this).text();
        }).get().join(', '); // Menggabungkan pilihan mapel jadi string

        // Membuat ID acak untuk baris baru
        var randomId = Math.floor(Math.random() * 1000000); // ID dummy

        // Menambahkan baris baru ke DataTable
        table.row.add([ 
            
            namaAlternatif, 
            kurikulumAlternatif, 
            mapelText, 
            '<td><div class="form-button-action">' +
            '<button type="button" class="btn btn-link btn-simple-primary btn-lg editBtn" ' +
            'data-id="' + randomId + '" ' +
            
            'data-name="' + namaAlternatif + '" ' +
            'data-kurikulum="' + kurikulumAlternatif + '" ' +
            'data-mapel=\'' + JSON.stringify(mapelAlternatif) + '\' ' + // Mengirimkan sebagai JSON string
            'title="Edit"><i class="fa fa-edit"></i></button>' +
            '<button type="button" class="btn btn-link btn-simple-danger removeBtn" title="Remove"><i class="fa fa-times"></i></button>' +
            '</div></td>'
        ]).draw();

        // Menutup modal dan mereset input form
        $('#addRowModal').modal('hide');
        
        $("#namaAlternatif").val('');
        $("#kurikulumSelect").val('').trigger('change');
        $("#mapelSelect").val('').trigger('change'); // Reset select2
    });
</script>

<script>
    // Menangani klik tombol edit
    $(document).on('click', '.editBtn', function () {
        let id = $(this).data('id');  // Mendapatkan ID dari data-id tombol
        
        let nama = $(this).data('nama');
        let kurikulum = $(this).data('kurikulum');
        let mapel = $(this).data('mapel');

        // Set nilai input dengan data dari tombol Edit
        
        $('#updateNama').val(nama);
        $('#updateKurikulum').val(kurikulum);
        $('#mapelAlternatif').val(mapel).trigger('change'); // Update select2

        // Mengubah action form sesuai dengan ID yang dipilih
        $('#formUpdateAlternatif').attr('action', '/admin/alternatif/update/' + id);
    });
</script>

<script>
    // Fungsi untuk menghapus data
    $(document).on('click', '.hapusBtn', function (e) {
        if (confirm("Apakah Anda yakin ingin menghapus data ini?")) {
            $.ajax({
                url: '/admin/alternatif/hapus/' + id, 
                type: 'DELETE',
                data: {
                    _token: '{{ csrf_token() }}', // Token CSRF untuk Laravel
                },
                success: function(response) {
                    alert('Data berhasil dihapus');
                    location.reload(); // Reload halaman setelah penghapusan
                },
                error: function(xhr, status, error) {
                    alert('Terjadi kesalahan: ' + error); // Menampilkan pesan kesalahan
                }
            });
        }
    });
</script>
<!-- Select2 JS -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
 $(document).ready(function() {
        $('.select2').select2({
            placeholder: "Pilih Mata Pelajaran",
            width: '100%',
            allowClear: true
        });
    });
</script>

<!-- End Script Files -->
</body>
</html>