@extends('layouts.layoutadmin')
@section('title', 'Banner Admin')

@section('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;
    }
    
    #bannerTable 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;
    }
    
    #bannerTable tbody td {
        padding: 12px 8px !important;
        vertical-align: middle !important;
        border-bottom: 1px solid #f3f4f6 !important;
        font-size: 13px !important;
        text-align: center !important;
    }
    
    #bannerTable 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>
@endsection

@section('content')
<div class="admin-dashboard">
    @include('admin.components.sidebar')
    <main class="main">
        <div class="main-header">
            <div>
                <div class="title">Manajemen Banner</div>
                <div class="subtitle">Kelola banner untuk konten visual</div>
            </div>
            <div class="header-actions">
                <button class="btn-secondary" onclick="loadBanners()">
                    <i class="fas fa-sync-alt"></i> Refresh
                </button>
                <button class="btn-primary" onclick="openAddBannerModal()">
                    <i class="fas fa-plus"></i> Tambah Banner
                </button>
            </div>
        </div>
        <div class="main-content">
            <div id="alert-container"></div>
            <div class="content-section">
                <div class="section-title">Daftar Banner</div>
                <div id="bannerListContainer"></div>
            </div>
        </div>

        <!-- Modal Add/Edit Banner -->
        <div id="bannerModal" class="modal">
            <div class="modal-content">
                <div class="modal-header" id="bannerModalTitle">Tambah Banner</div>
                <form id="bannerForm">
                    <input type="hidden" id="banner_id">
                    <div class="form-group">
                        <label for="banner_title">Judul Banner</label>
                        <input type="text" id="banner_title" required placeholder="Masukkan judul banner">
                    </div>
                    <div class="form-group">
                        <label for="banner_image">Gambar Banner</label>
                        <input type="file" id="banner_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="closeBannerModal()">
                            <i class="fas fa-times"></i> Batal
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </main>
</div>

<script>
const baseUrl = '{{ env('BASE_URL') }}';
let bannerList = [];

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 '{{ session("auth.token") }}';
}

async function loadBanners() {
    try {
        const token = getAuthToken();
        console.log('=== LOADING BANNERS ===');
        console.log('Token:', token ? 'Present' : 'Missing');
        console.log('Base URL:', baseUrl);
        
        const url = `${baseUrl}/api/admin/banner`;
        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('Banners data:', data);
        
        bannerList = Array.isArray(data) ? data : (data.data || []);
        console.log('Processed bannerList:', bannerList);
        renderBannerList();
    } catch (err) {
        console.error('Error loading banners:', err);
        showAlert('Gagal memuat banner: ' + err.message, 'error');
    }
}

function renderBannerList() {
    const container = document.getElementById('bannerListContainer');
    if (!bannerList.length) {
        container.innerHTML = '<div style="padding:2rem;text-align:center;color:#9ca3af;">Belum ada banner.</div>';
        return;
    }
    
    console.log('=== RENDERING BANNER LIST ===');
    console.log('bannerList length:', bannerList.length);
    if (bannerList.length > 0) {
        console.log('First item keys:', Object.keys(bannerList[0]));
        console.log('First item sample:', bannerList[0]);
    }
    
    container.innerHTML = `<table id="bannerTable" 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>
        ${bannerList.map(banner => {
            console.log('Processing banner:', banner.id, banner.title);
            
            // Clean and validate ID
            const bannerId = banner.id ? String(banner.id).trim() : '';
            if (!bannerId) {
                console.warn('Banner missing ID:', banner);
                return '';
            }
            
            const createdDate = banner.createdAt ? new Date(banner.createdAt).toLocaleDateString('id-ID') : 'N/A';
            
            return `
            <tr>
                <td style="font-weight:600;font-size:1.05rem;text-align:left;">${banner.title || 'No Title'}</td>
                <td>
                    ${banner.path_image ? 
                        `<img src="${baseUrl}/${banner.path_image}" class="img-thumb" alt="Banner" onclick="window.open('${baseUrl}/${banner.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="openEditBannerModal('${bannerId}')">
                        <i class="fas fa-edit"></i> Edit
                    </button>
                    <button class="btn-danger" style="padding:6px 16px;border-radius:8px;font-size:0.9rem;" onclick="deleteBanner('${bannerId}')">
                        <i class="fas fa-trash"></i> Hapus
                    </button>
                </td>
            </tr>
        `;}).join('')}
        </tbody>
    </table>`;
    
    if (window.$ && window.$.fn.dataTable) {
        $('#bannerTable').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 = () => {
                $('#bannerTable').DataTable({
                    "order": [[ 2, "desc" ]],
                    "pageLength": 10,
                    "responsive": true
                });
            };
            document.body.appendChild(scriptDt);
        };
        document.body.appendChild(scriptJq);
    }
}

function openAddBannerModal() {
    document.getElementById('bannerForm').reset();
    document.getElementById('banner_id').value = '';
    document.getElementById('bannerModalTitle').textContent = 'Tambah Banner';
    document.getElementById('bannerModal').style.display = 'flex';
}

function openEditBannerModal(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 banner = bannerList.find(b => b.id == numericId || b.id == cleanId);
    
    console.log('Looking for banner with ID:', cleanId, 'or', numericId);
    console.log('Found banner:', banner);
    
    if (!banner) {
        console.error('Banner not found with ID:', cleanId);
        showAlert('Banner tidak ditemukan', 'error');
        return;
    }
    
    document.getElementById('banner_id').value = banner.id;
    document.getElementById('banner_title').value = banner.title;
    document.getElementById('bannerModalTitle').textContent = 'Edit Banner';
    document.getElementById('bannerModal').style.display = 'flex';
}

function closeBannerModal() {
    document.getElementById('bannerModal').style.display = 'none';
}

document.getElementById('bannerForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const id = document.getElementById('banner_id').value;
    const title = document.getElementById('banner_title').value.trim();
    const imageInput = document.getElementById('banner_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;
    }
    
    // Validate file for new banner
    if (!id && !imageInput.files[0]) {
        showAlert('Gambar banner harus dipilih!', 'error');
        return;
    }
    
    // Validate file size and type if file is selected
    if (imageInput.files[0]) {
        const file = imageInput.files[0];
        const maxSize = 5 * 1024 * 1024; // 5MB
        const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
        
        if (file.size > maxSize) {
            showAlert('Ukuran file terlalu besar! Maksimal 5MB.', 'error');
            return;
        }
        
        if (!allowedTypes.includes(file.type)) {
            showAlert('Format file tidak didukung! Gunakan JPG, PNG, GIF, atau WebP.', 'error');
            return;
        }
    }
    
    const formData = new FormData();
    formData.append('title', title);
    if (imageInput.files[0]) {
        formData.append('banner_image', imageInput.files[0]);
    }
    
    // Log FormData contents
    console.log('=== FORMDATA CONTENTS ===');
    for (let [key, value] of formData.entries()) {
        console.log(key, ':', value instanceof File ? `${value.name} (${value.size} bytes)` : value);
    }
    
    try {
        let url = `${baseUrl}/api/admin/banner`;
        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('Banner berhasil disimpan!', 'success');
            closeBannerModal();
            loadBanners();
        } 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 deleteBanner(id) {
    console.log('=== DELETE BANNER ===');
    console.log('Banner 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 banner tidak valid', 'error');
        return;
    }
    
    if (!confirm('Yakin ingin menghapus banner ini?')) return;
    
    const token = getAuthToken();
    const url = `${baseUrl}/api/admin/banner/${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('Banner berhasil dihapus!', 'success');
            loadBanners();
        } 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('bannerModal');
    if (event.target === modal) {
        closeBannerModal();
    }
}

document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded, loading banners...');
    console.log('Auth token:', getAuthToken() ? 'Present' : 'Missing');
    loadBanners();
});
</script>
@endsection
