@extends('admin.layouts.app')

@section('title', 'Daftar Berita')

@push('styles')
    <link href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css" rel="stylesheet">

    <style>
        .soft-card {
            border: 0;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(16, 24, 40, .06);
        }

        .table-hlines {
            --line: #e9edf4;
        }

        .table-hlines> :not(caption)>*>* {
            border-top: 0;
            border-right: 0 !important;
            border-left: 0 !important;
            border-bottom: 1px solid var(--line);
            background: transparent;
        }

        .table-hlines thead th {
            border-bottom: 2px solid var(--line) !important;
        }

        .table-hlines.table-hover tbody tr:hover {
            background: transparent !important;
        }

        table.dataTable.hover>tbody>tr:hover>*,
        table.dataTable.display>tbody>tr:hover>* {
            background: transparent !important;
        }

        .table-sticky thead th {
            position: sticky;
            top: 0;
            background: #fff;
            z-index: 1
        }

        div.dataTables_filter,
        div.dataTables_length {
            display: none
        }

        .badge-status-published {
            background: #a6e7d8;
            color: #008767;
            border: 1px solid rgba(0, 0, 0, .05)
        }

        .badge-status-draft {
            background: #ffd5b6;
            color: #a24c00;
            border: 1px solid rgba(0, 0, 0, .05)
        }

        .badge-status-archived {
            background: #ffc5c5;
            color: #df0404;
            border: 1px solid rgba(0, 0, 0, .05)
        }

        .export-dropdown .dropdown-menu {
            min-width: 160px
        }

        .export-dropdown .dropdown-item i {
            width: 18px
        }

        .action-buttons .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }
    </style>
@endpush

@section('content')
    <div class="card soft-card">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <div>
                    <h4 class="mb-0">Daftar Berita</h4>
                    <small class="text-success">Kelola berita desa</small>
                </div>
                <a href="{{ route('admin.berita.create') }}" class="btn btn-primary">
                    <i class="ti ti-plus"></i> Tambah Berita
                </a>
            </div>

            <div class="d-flex flex-wrap align-items-center gap-2 mb-3">
                <div class="input-group input-group-sm" style="max-width:280px;">
                    <span class="input-group-text bg-white"><i class="ti ti-search"></i></span>
                    <input id="tableSearch" type="text" class="form-control" placeholder="Cari berita...">
                </div>
                <button type="button" class="btn btn-sm btn-light border d-inline-flex align-items-center gap-1">
                    <i class="ti ti-adjustments-horizontal"></i> Filter
                </button>
                <div class="export-dropdown dropdown ms-auto">
                    <button class="btn btn-sm btn-success dropdown-toggle" data-bs-toggle="dropdown">
                        <i class="ti ti-download"></i> Export
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><a class="dropdown-item" href="#" data-export="csv"><i class="ti ti-file-spreadsheet"></i>
                                CSV</a></li>
                        <li><a class="dropdown-item" href="#" data-export="excel"><i class="ti ti-file-type-xls"></i>
                                Excel</a></li>
                        <li><a class="dropdown-item" href="#" data-export="pdf"><i class="ti ti-file-type-pdf"></i>
                                PDF</a></li>
                        <li><a class="dropdown-item" href="#" data-export="print"><i class="ti ti-printer"></i>
                                Print</a></li>
                    </ul>
                </div>
                <div id="dtButtons" class="d-none"></div>
            </div>

            <table id="beritaTable" class="table align-middle w-100 table-sticky table-hlines table-hover">
                <thead>
                    <tr>
                        <th>Judul</th>
                        <th>Kategori</th>
                        <th>Tanggal Dibuat</th>
                        <th>Status</th>
                        <th>Views</th>
                        <th>Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse ($news ?? [] as $berita)
                        @php
                            $status = $berita->status ?? 'draft';
                            $badgeClass = [
                                'published' => 'badge-status-published',
                                'draft' => 'badge-status-draft',
                                'archived' => 'badge-status-archived',
                            ][$status] ?? 'badge-status-draft';
                            $statusText = ucfirst($status);
                        @endphp
                        <tr>
                            <td>
                                <div>
                                    <div class="fw-semibold">{{ $berita->title ?? 'Judul Berita' }}</div>
                                    <small class="text-muted">{{ Str::limit(strip_tags($berita->content ?? 'Konten berita...'), 80) }}</small>
                                </div>
                            </td>
                            <td>{{ $berita->category ?? 'Umum' }}</td>
                            <td data-order="{{ $berita->created_at ?? now() }}">
                                {{ \Carbon\Carbon::parse($berita->created_at ?? now())->format('d M Y') }}
                            </td>
                            <td><span class="badge rounded-pill {{ $badgeClass }}">{{ $statusText }}</span></td>
                            <td>{{ $berita->views ?? 0 }}</td>
                            <td>
                                <div class="action-buttons d-flex gap-1">
                                    <a href="{{ route('news.show', $berita->slug ?? 'sample-slug') }}" 
                                       class="btn btn-sm btn-outline-primary" 
                                       title="Lihat">
                                        <i class="ti ti-eye"></i>
                                    </a>
                                    <a href="{{ route('admin.berita.edit', $berita->id ?? 1) }}" 
                                       class="btn btn-sm btn-outline-warning" 
                                       title="Edit">
                                        <i class="ti ti-edit"></i>
                                    </a>
                                    <button type="button" 
                                            class="btn btn-sm btn-outline-danger" 
                                            title="Hapus"
                                            onclick="deleteNews({{ $berita->id ?? 1 }})">
                                        <i class="ti ti-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="6" class="text-center py-4">
                                <div class="text-muted">
                                    <i class="ti ti-news-off" style="font-size: 2rem;"></i>
                                    <p class="mt-2 mb-0">Belum ada berita</p>
                                    <small>Mulai dengan menambahkan berita pertama</small>
                                </div>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>
@endsection

@push('scripts')
    <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap5.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>

    <script>
        $(function() {
            // DataTable init with Buttons
            var hasData = $('#beritaTable tbody tr').length > 0 && !$('#beritaTable tbody tr td[colspan]').length;
            if (typeof $.fn.DataTable !== 'undefined' && hasData) {
                var table = $('#beritaTable').DataTable({
                    autoWidth: false,
                    responsive: {
                        details: false
                    },
                    paging: true,
                    pageLength: 10,
                    lengthChange: false,
                    info: true,
                    ordering: true,
                    searching: true,
                    order: [
                        [2, 'desc']
                    ],
                    language: {
                        search: "Cari:",
                        searchPlaceholder: "Ketik untuk mencari...",
                        lengthMenu: "Tampilkan _MENU_",
                        info: "Menampilkan _START_ sampai _END_ dari _TOTAL_ data",
                        infoEmpty: "Menampilkan 0 sampai 0 dari 0 data",
                        infoFiltered: "(difilter dari _MAX_ total data)",
                        paginate: {
                            first: "Pertama",
                            last: "Terakhir",
                            next: "Selanjutnya",
                            previous: "Sebelumnya"
                        },
                        emptyTable: "Tidak ada data yang tersedia",
                        zeroRecords: "Tidak ada data yang cocok"
                    },
                    columnDefs: [{
                            targets: [2, 4, 5],
                            className: 'text-nowrap'
                        },
                        {
                            targets: 5,
                            orderable: false
                        }
                    ],
                    dom: "rt<'row align-items-center mt-3'<'col-sm-6'i><'col-sm-6 d-flex justify-content-end'p>>",
                    buttons: [{
                            extend: 'csvHtml5',
                            title: 'daftar-berita'
                        },
                        {
                            extend: 'excelHtml5',
                            title: 'daftar-berita'
                        },
                        {
                            extend: 'pdfHtml5',
                            title: 'daftar-berita',
                            orientation: 'landscape',
                            pageSize: 'A4'
                        },
                        {
                            extend: 'print',
                            title: 'Daftar Berita Desa'
                        }
                    ]
                });

                table.buttons().container().appendTo('#dtButtons');

                $('#tableSearch').on('keyup', function() {
                    table.search(this.value).draw();
                });

                $('[data-export]').on('click', function(e) {
                    e.preventDefault();
                    const type = $(this).data('export');
                    if (type === 'csv') table.button(0).trigger();
                    if (type === 'excel') table.button(1).trigger();
                    if (type === 'pdf') table.button(2).trigger();
                    if (type === 'print') table.button(3).trigger();
                });
            }
        });

        function deleteNews(id) {
            if (confirm('Apakah Anda yakin ingin menghapus berita ini?')) {
                // Implement delete functionality
                console.log('Deleting news with ID:', id);
                // You can add AJAX call here
            }
        }
    </script>
@endpush
