
<?php $__env->startSection('title', 'Infografis Admin'); ?>

<?php $__env->startSection('styles'); ?>
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
<style>
    body { background: #f4f4f4; }
    .admin-dashboard { display: flex; min-height: 100vh; background: #f4f4f4; }
    .sidebar {
        width: 260px;
        background: #23272b;
        color: #fff;
        display: flex;
        flex-direction: column;
        padding: 24px 0 0 0;
        border-right: 1px solid #e5e7eb;
    }
    .sidebar .sidebar-header {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 0 24px 24px 24px;
        font-size: 1.1rem;
        font-weight: 700;
    }
    .sidebar .sidebar-header i {
        font-size: 1.6rem;
        color: #22c1b6;
    }
    .sidebar .sidebar-header span {
        font-size: 1.1rem;
        font-weight: 700;
        color: #fff;
    }
    .sidebar-nav {
        flex: 1;
        padding: 0 0 0 0;
    }
    .sidebar-nav ul {
        list-style: none;
        padding: 0;
        margin: 0;
    }
    .sidebar-nav li {
        margin-bottom: 4px;
    }
    .sidebar-nav a {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 10px 28px;
        color: #bfc5c9;
        text-decoration: none;
        border-radius: 8px 0 0 8px;
        font-size: 1rem;
        transition: background 0.2s, color 0.2s;
    }
    .sidebar-nav a.active,
    .sidebar-nav a:hover {
        background: #22c1b6;
        color: #fff;
    }
    .main { flex: 1; display: flex; flex-direction: column; background: #f4f4f4; }
    .main-header { background: #fff; padding: 24px 32px 16px 32px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid #e5e7eb; }

    /* Keep admin header/navbar white regardless of site dark/light mode */
    body.dark-mode .admin-dashboard .main-header,
    .admin-dashboard .main-header {
        background: #ffffff !important;
        color: #222 !important;
        border-bottom: 1px solid #e5e7eb !important;
    }

    /* Ensure header child elements keep their intended colors in dark mode */
    body.dark-mode .admin-dashboard .main-header .title,
    body.dark-mode .admin-dashboard .main-header .subtitle,
    body.dark-mode .admin-dashboard .main-header .header-actions,
    body.dark-mode .admin-dashboard .main-header .header-actions * {
        color: inherit !important;
        background: transparent !important;
    }
    
    .title { font-size: 1.4rem; font-weight: 700; color: #222; }
    .subtitle { color: #6b7280; font-size: 1.05rem; margin-top: 2px; }
    .header-actions { display: flex; align-items: center; gap: 16px; }
    .btn-primary { background: linear-gradient(135deg, #667eea 0%, #22c1b6 100%); color: #fff; border: none; border-radius: 8px; padding: 10px 28px; font-weight: 600; font-size: 1rem; cursor: pointer; transition: all 0.2s; }
    .btn-primary:hover { background: #1da89c; transform: translateY(-1px); box-shadow: 0 4px 12px rgba(34,193,182,0.3); }
    .btn-secondary { background: #6b7280; color: #fff; border: none; border-radius: 8px; padding: 8px 22px; font-weight: 600; font-size: 1rem; cursor: pointer; transition: background 0.2s; margin-right: 12px; }
    .btn-secondary:hover { background: #4b5563; }
    .btn-danger { background: #ef4444; color: #fff; border: none; border-radius: 8px; padding: 8px 22px; font-weight: 600; font-size: 1rem; cursor: pointer; transition: all 0.2s; }
    .btn-danger:hover { background: #dc2626; transform: translateY(-1px); }
    .main-content { padding: 32px; }
    .content-section { background: #fff; border-radius: 12px; box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04); padding: 32px; margin-top: 2rem; }
    .section-title { font-size: 1.3rem; font-weight: 700; color: #23272b; margin-bottom: 1.5rem; }
    .badge { display: inline-block; padding: 6px 16px; border-radius: 8px; font-weight: 600; font-size: 0.95rem; }
    .alert-success { background: #d1fae5; color: #065f46; border-radius: 8px; padding: 10px 18px; margin-bottom: 1rem; }
    .alert-error { background: #fee2e2; color: #991b1b; border-radius: 8px; padding: 10px 18px; margin-bottom: 1rem; }
    
    /* DataTables Enhanced Styling */
    .dataTables_wrapper {
        padding: 1.5rem;
        background: #ffffff;
        border-radius: 12px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.05);
    }
    
    .dataTables_filter input {
        border: 2px solid #e5e7eb !important;
        border-radius: 8px !important;
        padding: 8px 16px !important;
        font-size: 14px !important;
        width: 250px !important;
        transition: all 0.3s ease !important;
    }
    
    .dataTables_filter input:focus {
        border-color: #22c1b6 !important;
        outline: none !important;
        box-shadow: 0 0 0 3px rgba(34, 193, 182, 0.1) !important;
    }
    
    #infographicTable thead th {
        background: linear-gradient(135deg, #f2f2f2ff) !important;
        color: black !important;
        font-weight: 600 !important;
        padding: 12px 8px !important;
        border: none !important;
        text-align: center !important;
        font-size: 14px !important;
    }
    
    #infographicTable tbody td {
        padding: 12px 8px !important;
        vertical-align: middle !important;
        border-bottom: 1px solid #f3f4f6 !important;
        font-size: 13px !important;
        text-align: center !important;
    }
    
    #infographicTable tbody tr:hover {
        background-color: #f8fafc !important;
    }
    
    .dataTables_info {
        color: #6b7280 !important;
        font-size: 14px !important;
        font-weight: 500 !important;
    }
    
    .dataTables_paginate .paginate_button {
        border: 1px solid #e5e7eb !important;
        border-radius: 6px !important;
        margin: 0 2px !important;
        padding: 6px 12px !important;
        color: #374151 !important;
        background: white !important;
    }
    
    .dataTables_paginate .paginate_button:hover {
        background: #22c1b6 !important;
        border-color: #22c1b6 !important;
        color: white !important;
    }
    
    .dataTables_paginate .paginate_button.current {
        background: #22c1b6 !important;
        border-color: #22c1b6 !important;
        color: white !important;
    }
    
    .img-thumb { 
        max-width: 100px; 
        max-height: 80px; 
        border-radius: 8px; 
        box-shadow: 0 2px 8px rgba(34,193,182,0.12); 
        transition: all 0.3s ease; 
        cursor: pointer; 
        object-fit: cover;
    }
    .img-thumb:hover { 
        transform: scale(1.05); 
        box-shadow: 0 4px 16px rgba(102,126,234,0.25); 
    }
    
    .modal { 
        display: none; 
        position: fixed; 
        z-index: 1000; 
        left: 0; 
        top: 0; 
        width: 100%; 
        height: 100%; 
        background: rgba(0,0,0,0.5); 
        align-items: center; 
        justify-content: center; 
    }
    .modal-content { 
        background: #fff; 
        border-radius: 12px; 
        padding: 32px 28px; 
        max-width: 450px; 
        width: 90%; 
        margin: auto; 
        box-shadow: 0 8px 32px rgba(34,193,182,0.18); 
        animation: modalSlideIn 0.3s ease;
    }
    
    @keyframes modalSlideIn {
        from { opacity: 0; transform: translateY(-20px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    .modal-header { 
        font-size: 1.3rem; 
        font-weight: 700; 
        margin-bottom: 20px; 
        color: #23272b; 
        text-align: center;
    }
    .form-group { 
        margin-bottom: 20px; 
    }
    .form-group label { 
        font-weight: 600; 
        margin-bottom: 8px; 
        display: block; 
        color: #374151; 
    }
    .form-group input[type="text"], 
    .form-group input[type="file"] { 
        width: 100%; 
        padding: 12px 16px; 
        border-radius: 8px; 
        border: 2px solid #e5e7eb; 
        background: #fff; 
        font-size: 1rem; 
        margin-top: 4px; 
        box-sizing: border-box; 
        transition: border-color 0.3s ease;
    }
    .form-group input:focus {
        border-color: #22c1b6;
        outline: none;
        box-shadow: 0 0 0 3px rgba(34, 193, 182, 0.1);
    }
    .modal-actions { 
        display: flex; 
        gap: 12px; 
        justify-content: center; 
        margin-top: 24px; 
    }
    .alert { 
        padding: 12px 20px; 
        border-radius: 8px; 
        margin-bottom: 1rem; 
        font-weight: 600; 
        animation: alertSlideIn 0.3s ease;
    }
    
    @keyframes alertSlideIn {
        from { opacity: 0; transform: translateY(-10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    .alert-success { 
        background: #d1fae5; 
        color: #065f46; 
        border-left: 4px solid #22c1b6;
    }
    .alert-error { 
        background: #fee2e2; 
        color: #991b1b; 
        border-left: 4px solid #ef4444;
    }
</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
<div class="admin-dashboard">
    <?php echo $__env->make('admin.components.sidebar', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
    <main class="main">
        <div class="main-header">
            <div>
                <div class="title">Manajemen Infografis</div>
                <div class="subtitle">Kelola infografis untuk konten visual</div>
            </div>
            <div class="header-actions">
                <button class="btn-secondary" onclick="loadInfographics()">
                    <i class="fas fa-sync-alt"></i> Refresh
                </button>
                <button class="btn-primary" onclick="openAddInfographicModal()">
                    <i class="fas fa-plus"></i> Tambah Infografis
                </button>
            </div>
        </div>
        <div class="main-content">
            <div id="alert-container"></div>
            <div class="content-section">
                <div class="section-title">Daftar Infografis</div>
                <div id="infographicListContainer"></div>
            </div>
        </div>

        <!-- Modal Add/Edit Infografis -->
        <div id="infographicModal" class="modal">
            <div class="modal-content">
                <div class="modal-header" id="infographicModalTitle">Tambah Infografis</div>
                <form id="infographicForm">
                    <input type="hidden" id="infographic_id">
                    <div class="form-group">
                        <label for="infographic_title">Judul Infografis</label>
                        <input type="text" id="infographic_title" required placeholder="Masukkan judul infografis">
                    </div>
                    <div class="form-group">
                        <label for="infographic_image">Gambar Infografis</label>
                        <input type="file" id="infographic_image" accept="image/*">
                        <small style="color: #6b7280; font-size: 0.9rem;">Format: JPG, PNG, WebP (Max: 5MB)</small>
                    </div>
                    <div class="modal-actions">
                        <button type="submit" class="btn-primary">
                            <i class="fas fa-save"></i> Simpan
                        </button>
                        <button type="button" class="btn-danger" onclick="closeInfographicModal()">
                            <i class="fas fa-times"></i> Batal
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </main>
</div>

<script>
const baseUrl = '<?php echo e(env('BASE_URL')); ?>';
let infographicList = [];

function showAlert(message, type = 'success') {
    const alertContainer = document.getElementById('alert-container');
    const alertClass = type === 'success' ? 'alert-success' : 'alert-error';
    alertContainer.innerHTML = `<div class="alert ${alertClass}">${message}</div>`;
    setTimeout(() => { alertContainer.innerHTML = ''; }, 4000);
}

function getAuthToken() {
    return localStorage.getItem('accessToken') || 
           sessionStorage.getItem('accessToken') ||
           localStorage.getItem('auth_token') ||
           sessionStorage.getItem('auth_token') || '';
}

async function loadInfographics() {
    try {
        const token = getAuthToken();
        console.log('=== LOADING INFOGRAPHICS ===');
        console.log('Token:', token ? 'Present' : 'Missing');
        console.log('Base URL:', baseUrl);
        
        const url = `${baseUrl}/api/admin/infographic`;
        console.log('Full URL:', url);
        
        const res = await fetch(url, {
            headers: { 'Authorization': `Bearer ${token}` }
        });
        
        console.log('Response status:', res.status);
        console.log('Response URL:', res.url);
        
        if (!res.ok) {
            const errorText = await res.text();
            console.error('Error response:', errorText);
            throw new Error(`HTTP error! status: ${res.status} - ${errorText}`);
        }
        
        const data = await res.json();
        console.log('Infographics data:', data);
        
        infographicList = Array.isArray(data) ? data : (data.data || []);
        console.log('Processed infographicList:', infographicList);
        renderInfographicList();
    } catch (err) {
        console.error('Error loading infographics:', err);
        showAlert('Gagal memuat infografis: ' + err.message, 'error');
    }
}

function renderInfographicList() {
    const container = document.getElementById('infographicListContainer');
    if (!infographicList.length) {
        container.innerHTML = '<div style="padding:2rem;text-align:center;color:#9ca3af;">Belum ada infografis.</div>';
        return;
    }
    
    console.log('=== RENDERING INFOGRAPHIC LIST ===');
    console.log('infographicList length:', infographicList.length);
    if (infographicList.length > 0) {
        console.log('First item keys:', Object.keys(infographicList[0]));
        console.log('First item sample:', infographicList[0]);
    }
    
    container.innerHTML = `<table id="infographicTable" class="display" style="width:100%;border-radius:12px;overflow:hidden;">
        <thead>
            <tr>
                <th>Judul</th>
                <th>Gambar</th>
                <th>Tanggal</th>
                <th>Aksi</th>
            </tr>
        </thead>
        <tbody>
        ${infographicList.map(info => {
            console.log('Processing infographic:', info.id, info.title);
            
            // Clean and validate ID
            const infographicId = info.id ? String(info.id).trim() : '';
            if (!infographicId) {
                console.warn('Infographic missing ID:', info);
                return '';
            }
            
            const createdDate = info.createdAt ? new Date(info.createdAt).toLocaleDateString('id-ID') : 'N/A';
            
            return `
            <tr>
                <td style="font-weight:600;font-size:1.05rem;text-align:left;">${info.title || 'No Title'}</td>
                <td>
                    ${info.path_image ? 
                        `<img src="${baseUrl}/${info.path_image}" class="img-thumb" alt="Infografis" onclick="window.open('${baseUrl}/${info.path_image}','_blank')">` : 
                        '<span style="color:#9ca3af;">No Image</span>'
                    }
                </td>
                <td style="color:#6b7280;">${createdDate}</td>
                <td>
                    <button class="btn-primary" style="padding:6px 16px;border-radius:8px;font-size:0.9rem;margin-right:6px;" onclick="openEditInfographicModal('${infographicId}')">
                        <i class="fas fa-edit"></i> Edit
                    </button>
                    <button class="btn-danger" style="padding:6px 16px;border-radius:8px;font-size:0.9rem;" onclick="deleteInfographic('${infographicId}')">
                        <i class="fas fa-trash"></i> Hapus
                    </button>
                </td>
            </tr>
        `;}).join('')}
        </tbody>
    </table>`;
    
    if (window.$ && window.$.fn.dataTable) {
        $('#infographicTable').DataTable({
            "order": [[ 2, "desc" ]], // Sort by date descending
            "pageLength": 10,
            "responsive": true,
            "language": {
                "search": "Cari:",
                "lengthMenu": "Tampilkan _MENU_ data per halaman",
                "info": "Menampilkan _START_ sampai _END_ dari _TOTAL_ data",
                "paginate": {
                    "first": "Pertama",
                    "last": "Terakhir", 
                    "next": "Selanjutnya",
                    "previous": "Sebelumnya"
                }
            }
        });
    } else {
        // Load DataTables if not available
        const scriptJq = document.createElement('script');
        scriptJq.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
        scriptJq.onload = () => {
            const scriptDt = document.createElement('script');
            scriptDt.src = 'https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js';
            scriptDt.onload = () => {
                $('#infographicTable').DataTable({
                    "order": [[ 2, "desc" ]],
                    "pageLength": 10,
                    "responsive": true
                });
            };
            document.body.appendChild(scriptDt);
        };
        document.body.appendChild(scriptJq);
    }
}

function openAddInfographicModal() {
    document.getElementById('infographicForm').reset();
    document.getElementById('infographic_id').value = '';
    document.getElementById('infographicModalTitle').textContent = 'Tambah Infografis';
    document.getElementById('infographicModal').style.display = 'flex';
}

function openEditInfographicModal(id) {
    console.log('=== OPENING EDIT MODAL ===');
    console.log('Received ID:', id, 'Type:', typeof id);
    
    // Clean and validate ID
    const cleanId = String(id).trim();
    if (!cleanId || cleanId === 'undefined' || cleanId === 'null') {
        console.error('Invalid ID for edit:', id);
        showAlert('ID tidak valid untuk edit', 'error');
        return;
    }
    
    // Convert to number for comparison if needed
    const numericId = parseInt(cleanId);
    const info = infographicList.find(i => i.id == numericId || i.id == cleanId);
    
    console.log('Looking for infographic with ID:', cleanId, 'or', numericId);
    console.log('Found infographic:', info);
    
    if (!info) {
        console.error('Infographic not found with ID:', cleanId);
        showAlert('Infografis tidak ditemukan', 'error');
        return;
    }
    
    document.getElementById('infographic_id').value = info.id;
    document.getElementById('infographic_title').value = info.title;
    document.getElementById('infographicModalTitle').textContent = 'Edit Infografis';
    document.getElementById('infographicModal').style.display = 'flex';
}

function closeInfographicModal() {
    document.getElementById('infographicModal').style.display = 'none';
}

document.getElementById('infographicForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const id = document.getElementById('infographic_id').value;
    const title = document.getElementById('infographic_title').value.trim();
    const imageInput = document.getElementById('infographic_image');
    const token = getAuthToken();
    
    console.log('=== FORM SUBMISSION ===');
    console.log('ID:', id);
    console.log('Title:', title);
    console.log('Image file:', imageInput.files[0] ? imageInput.files[0].name : 'None');
    console.log('Token:', token ? 'Present' : 'Missing');
    
    if (!title) {
        showAlert('Judul harus diisi!', 'error');
        return;
    }
    
    const formData = new FormData();
    formData.append('title', title);
    if (imageInput.files[0]) {
        formData.append('infographic_image', imageInput.files[0]);
    }
    
    // Log FormData contents
    console.log('=== FORMDATA CONTENTS ===');
    for (let [key, value] of formData.entries()) {
        console.log(key, ':', value);
    }
    
    try {
        let url = `${baseUrl}/api/admin/infographic`;
        let method = 'POST';
        
        if (id) {
            // Clean ID for URL
            const cleanId = String(id).trim();
            url += `/${cleanId}`;
            method = 'PUT';
        }
        
        console.log('Submitting to:', url);
        console.log('Method:', method);
        
        const res = await fetch(url, {
            method: method,
            headers: { 'Authorization': `Bearer ${token}` },
            body: formData
        });
        
        console.log('Response status:', res.status);
        console.log('Response URL:', res.url);
        
        if (res.ok) {
            const responseData = await res.json();
            console.log('Success response:', responseData);
            showAlert('Infografis berhasil disimpan!', 'success');
            closeInfographicModal();
            loadInfographics();
        } else {
            const errorData = await res.text();
            console.error('Error response:', errorData);
            showAlert('Gagal simpan data: ' + errorData, 'error');
        }
    } catch (err) {
        console.error('Submit error:', err);
        showAlert('Gagal simpan: ' + err.message, 'error');
    }
});

async function deleteInfographic(id) {
    console.log('=== DELETE INFOGRAPHIC ===');
    console.log('Infographic ID to delete:', id);
    console.log('ID type:', typeof id);
    
    // Validate and clean ID
    const cleanId = String(id).trim();
    if (!cleanId || cleanId === 'undefined' || cleanId === 'null') {
        console.error('Invalid ID:', id);
        showAlert('ID infografis tidak valid', 'error');
        return;
    }
    
    if (!confirm('Yakin ingin menghapus infografis ini?')) return;
    
    const token = getAuthToken();
    const url = `${baseUrl}/api/admin/infographic/${cleanId}`;
    
    try {
        console.log('Sending DELETE request to:', url);
        console.log('Token:', token ? 'Present' : 'Missing');
        
        const res = await fetch(url, {
            method: 'DELETE',
            headers: { 
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });
        
        console.log('DELETE response status:', res.status);
        console.log('DELETE response URL:', res.url);
        console.log('DELETE response headers:', Object.fromEntries(res.headers.entries()));
        
        if (res.ok) {
            // Try to parse as JSON, but handle cases where response might be empty or not JSON
            let responseData = null;
            try {
                const responseText = await res.text();
                console.log('DELETE response text:', responseText);
                
                if (responseText.trim()) {
                    responseData = JSON.parse(responseText);
                    console.log('DELETE success response:', responseData);
                } else {
                    console.log('DELETE response is empty (which is fine for delete operations)');
                }
            } catch (jsonError) {
                console.warn('DELETE response is not JSON (which is fine for delete operations):', jsonError);
            }
            
            showAlert('Infografis berhasil dihapus!', 'success');
            loadInfographics();
        } else {
            let errorData;
            try {
                const errorText = await res.text();
                console.error('DELETE error response text:', errorText);
                errorData = errorText;
            } catch (err) {
                console.error('Error reading error response:', err);
                errorData = `HTTP ${res.status}`;
            }
            showAlert(`Gagal hapus data (${res.status}): ${errorData}`, 'error');
        }
    } catch (err) {
        console.error('Delete error:', err);
        showAlert('Gagal hapus: ' + err.message, 'error');
    }
}

// Close modal when clicking outside
window.onclick = function(event) {
    const modal = document.getElementById('infographicModal');
    if (event.target === modal) {
        closeInfographicModal();
    }
}

document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded, loading infographics...');
    loadInfographics();
});
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.layoutadmin', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH D:\laravel\krs-jawa3-template\krs-jawa3-web-template\resources\views/admin/infografisAdmin.blade.php ENDPATH**/ ?>