@php
use App\Models\Kriteria;
@endphp

@extends('layouts.app')

@section('title', 'Politeknik Negeri Jember - Manajemen Sub Kriteria')
@section('css')

<link href="{{ asset('vendor/datatables/dataTables.bootstrap4.min.css') }}" rel="stylesheet">
<link href="{{ asset('vendor/fontawesome-free/css/all.min.css') }}" rel="stylesheet">
<style>
    :root {
        --primary: rgb(0, 122, 153);
        --secondary: #858796;
        --success: #1cc88a;
        --danger: #e74a3b;
        --warning: #f6c23e;
        --light: #f8f9fc;
    }
    
    .card {
        border: none;
        border-radius: 0.5rem;
        box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
    }
    
    .card-header {
        background-color: var(--primary);
        color: white;
        border-radius: 0.5rem 0.5rem 0 0 !important;
        padding: 1rem;
    }
    
    .btn-circle {
        width: 35px;
        height: 35px;
        border-radius: 50%;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        margin: 0 3px;
    }
    
    .table-responsive {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }
    
    .table {
        width: 100%;
        border-collapse: collapse;
        font-size: 1rem;
    }
    
    .table thead th {
        border: none;
        background-color: #f8f9fc;
        color: #5a5c69;
        font-weight: 600;
        padding: 1rem;
        font-size: 1rem;
    }
    
    .table tbody tr {
        background-color: white;
        border-bottom: 1px solid #e3e6f0;
    }
    
    .table tbody tr.group-row {
        background-color: rgba(0, 122, 153, 0.1);
        font-weight: bold;
    }
    
    .table tbody td {
        vertical-align: middle;
        padding: 1rem;
        font-size: 1rem;
    }
    
    .badge-nilai {
        background-color: var(--primary);
        color: white;
        padding: 0.5rem 0.75rem;
        border-radius: 50rem;
        font-size: 0.9rem;
        font-weight: 600;
    }

    .badge-success {
        background-color: var(--success);
        color: white;
    }

    .badge-danger {
        background-color: var(--danger);
        color: white;
    }
    
    /* Responsive styles for small screens */
    @media (max-width: 576px) {
        .card-header {
            flex-direction: column;
            align-items: flex-start;
        }
        
        .card-header .btn {
            width: 100%;
            margin-top: 0.5rem;
        }
        
        .table thead {
            display: none;
        }
        
        .table tbody tr {
            display: block;
            margin-bottom: 1rem;
            border: 1px solid #e3e6f0;
            border-radius: 0.5rem;
        }
        
        .table tbody tr.group-row {
            padding: 0.75rem 1rem;
            background-color: rgba(0, 122, 153, 0.2);
        }
        
        .table tbody td {
            display: block;
            text-align: right;
            padding: 0.5rem 1rem;
            border-bottom: 1px solid #e3e6f0;
        }
        
        .table tbody td:last-child {
            border-bottom: none;
        }
        
        .table tbody td:before {
            content: attr(data-label);
            float: left;
            font-weight: bold;
            color: var(--primary);
        }
        
        .table tbody td .btn-group {
            display: flex;
            justify-content: flex-end;
        }
        
        .btn-circle {
            width: 30px;
            height: 30px;
            font-size: 0.9rem;
        }
    }
</style>
@endsection

@section('content')
<div class="container-fluid">
    @if (session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <div class="d-flex align-items-center">
            <i class="fas fa-check-circle mr-3"></i>
            <div>
                <strong>Sukses!</strong> {{ session('success') }}
            </div>
        </div>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    @endif
    
    @if (session('error'))
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <div class="d-flex align-items-center">
            <i class="fas fa-exclamation-circle mr-3"></i>
            <div>
                <strong>Error!</strong> {{ session('error') }}
            </div>
        </div>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    @endif

    <div class="card mb-4">
        <div class="card-header d-flex flex-row align-items-center justify-content-between">
            <div class="d-flex align-items-center">
                <i class="fas fa-list-alt mr-3"></i>
                @if($kriteria)
                    <h5 class="m-0 font-weight-bold">Sub Kriteria: {{ $kriteria->nama_kriteria }}</h5>
                @else
                    <h5 class="m-0 font-weight-bold">Daftar Semua Sub Kriteria</h5>
                @endif
            </div>
            <div class="d-flex flex-wrap">
                <a href="{{ route('subkriteria.create', $kriteria ? ['kriteria_id' => $kriteria->id] : []) }}" 
                   class="btn btn-light mr-2">
                    <i class="fas fa-plus-circle mr-2"></i> Tambah
                </a>
                <a href="{{ route('subkriteria.download.pdf', $kriteria->id ?? null) }}" 
                    class="btn btn-light" target="_blank">
                    <i class="fas fa-file-pdf mr-2"></i> PDF
                </a>
            </div>
        </div>
        
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table" id="DataTable">
                    <thead>
                        <tr>
                            <th width="5%">No</th>
                            @if(!$kriteria)
                            <th>Kriteria</th>
                            <th>Tipe</th>
                            @endif
                            <th>Sub Kriteria</th>
                            <th width="15%">Nilai</th>
                            <th width="15%">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        @php
                            $currentKriteria = null;
                            $rowNumber = 1;
                        @endphp
                        
                        @forelse($subkriterias as $sub)
                            @if(!$kriteria && $currentKriteria != $sub->kriteria_id)
                                <tr class="group-row">
                                    <td colspan="{{ $kriteria ? 4 : 6 }}">
                                        <i class="fas fa-folder-open mr-2"></i>
                                        {{ $sub->kriteria->nama_kriteria }}
                                    </td>
                                </tr>
                                @php $currentKriteria = $sub->kriteria_id; @endphp
                            @endif
                            
                            <tr>
                                <td data-label="No" class="text-center">{{ $rowNumber++ }}</td>
                                @if(!$kriteria)
                                <td data-label="Kriteria">
                                    <span class="badge badge-primary">
                                        {{ $sub->kriteria->nama_kriteria }}
                                    </span>
                                </td>
                                <td data-label="Tipe">
                                    <span class="badge {{ $sub->kriteria->attribut == 'benefit' ? 'badge-success' : 'badge-danger' }}">
                                        {{ strtoupper($sub->kriteria->attribut) }}
                                     </span>
                                </td>
                                @endif
                                <td data-label="Sub Kriteria">
                                    <i class="fas fa-caret-right mr-2 text-primary"></i>
                                    {{ $sub->nama_subkriteria }}
                                </td>
                                <td data-label="Nilai">
                                    <span class="badge-nilai">
                                        {{ number_format($sub->nilai) }}
                                    </span>
                                </td>
                                <td data-label="Aksi" class="text-center">
                                    <div class="btn-group">
                                        <a href="{{ route('subkriteria.edit', $sub->id) }}" 
                                           class="btn btn-circle btn-warning"
                                           data-toggle="tooltip" 
                                           title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <button type="button" 
                                                class="btn btn-circle btn-danger delete-btn" 
                                                data-url="{{ route('subkriteria.destroy', $sub->id) }}"
                                                title="Hapus">
                                            <i class="fas fa-trash-alt"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="{{ $kriteria ? 4 : 6 }}" class="text-center py-4">
                                    <i class="fas fa-info-circle mr-2"></i> Belum ada data subkriteria
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
@endsection

@section('js')
<script src="{{ asset('vendor/jquery/jquery.min.js') }}"></script>
<script src="{{ asset('vendor/bootstrap/js/bootstrap.bundle.min.js') }}"></script>
<!-- DataTables -->
<script src="{{ asset('vendor/datatables/jquery.dataTables.min.js') }}"></script>
<script src="{{ asset('vendor/datatables/dataTables.bootstrap4.min.js') }}"></script>
<!-- SweetAlert -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(document).ready(function() {
     // Delete functionality
    $(document).on('click', '.delete-btn', function() {
        var deleteUrl = $(this).data('url');
        var row = $(this).closest('tr');
        
        Swal.fire({
            title: 'Apakah kamu yakin?',
            text: "Data akan dihapus secara permanen!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#e74a3b',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, hapus!',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: deleteUrl,
                    type: 'POST',
                    data: {
                        _method: 'DELETE',
                        _token: $('meta[name="csrf-token"]').attr('content')
                    },
                    success: function(response) {
                        if (response.success) {
                            Swal.fire(
                                'Berhasil!',
                                response.message,
                                'success'
                            ).then(() => {
                                if (response.redirect) {
                                    window.location.href = response.redirect;
                                } else {
                                    row.fadeOut(300, function() {
                                        $(this).remove();
                                    });
                                }
                            });
                        }
                    },
                    error: function(xhr) {
                        Swal.fire('Error', 'Terjadi kesalahan saat menghapus', 'error');
                    }
                });
            }
        });
    });
    
    // Initialize DataTable with responsive extension
    $('#DataTable').DataTable({
        responsive: {
            details: {
                display: $.fn.dataTable.Responsive.display.modal({
                    header: function(row) {
                        return 'Detail Sub Kriteria';
                    }
                }),
                renderer: $.fn.dataTable.Responsive.renderer.tableAll({
                    tableClass: 'table'
                })
            }
        },
        paging: false,
        searching: true,
        ordering: false,
        info: false,
        language: {
            search: "Cari:",
            zeroRecords: "Tidak ada data yang ditemukan",
            infoEmpty: "Tidak ada data yang tersedia",
        },
        order: []
    });

    // Initialize tooltips
    $('[data-toggle="tooltip"]').tooltip();

    // Setup responsive labels for mobile view
    function setupResponsiveLabels() {
        if ($(window).width() <= 576) {
            $('thead th').each(function(i) {
                var header = $(this).text();
                $('tbody td:nth-child(' + (i + 1) + ')').attr('data-label', header);
            });
        } else {
            $('tbody td').removeAttr('data-label');
        }
    }

    // Run on load and resize
    setupResponsiveLabels();
    $(window).resize(setupResponsiveLabels);
});
</script>
@endsection