@extends('layouts.admin-simple')

@section('title', 'News Management')
@section('page-title', 'News Management')

@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('admin.dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item active" aria-current="page">News</li>
@endsection

@section('page-actions')
    <div class="ml-auto">
        <a href="{{ route('admin.news.create') }}" class="btn btn-primary">
            <i class="material-icons">add</i> Create Article
        </a>
    </div>
@endsection

@section('content')
    <!-- Filters -->
    <div class="card mb-3">
        <div class="card-body">
            <form method="GET" class="row align-items-end">
                <div class="col-md-3">
                    <label for="search" class="form-label">Search</label>
                    <input type="text" class="form-control" id="search" name="search" 
                           value="{{ request('search') }}" placeholder="Title, content...">
                </div>
                <div class="col-md-2">
                    <label for="category" class="form-label">Category</label>
                    <select class="form-control" id="category" name="category">
                        <option value="">All Categories</option>
                        @foreach($categories as $category)
                            <option value="{{ $category->slug }}" {{ request('category') == $category->slug ? 'selected' : '' }}>
                                {{ $category->name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2">
                    <label for="status" class="form-label">Status</label>
                    <select class="form-control" id="status" name="status">
                        <option value="">All Status</option>
                        <option value="published" {{ request('status') == 'published' ? 'selected' : '' }}>Published</option>
                        <option value="draft" {{ request('status') == 'draft' ? 'selected' : '' }}>Draft</option>
                        <option value="featured" {{ request('status') == 'featured' ? 'selected' : '' }}>Featured</option>
                    </select>
                </div>
                <div class="col-md-5">
                    <button type="submit" class="btn btn-outline-primary">
                        <i class="material-icons">search</i> Search
                    </button>
                    <a href="{{ route('admin.news') }}" class="btn btn-outline-secondary">
                        <i class="material-icons">clear</i> Clear
                    </a>
                </div>
            </form>
        </div>
    </div>

    <!-- News Table -->
    <div class="card">
        <div class="card-header card-header-large bg-white d-flex align-items-center">
            <div class="flex">
                <h4 class="card-header__title">News Articles</h4>
                <div class="card-subtitle text-muted">Manage news articles and announcements</div>
            </div>
            <div class="ml-auto">
                <span class="badge badge-light">{{ $news->total() }} total articles</span>
            </div>
        </div>
        
        <div class="table-responsive">
            <table class="table mb-0">
                <thead>
                    <tr>
                        <th>Article</th>
                        <th>Category</th>
                        <th>Author</th>
                        <th>Status</th>
                        <th>Published</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($news as $article)
                    <tr>
                        <td>
                            <div class="media align-items-center">
                                <div class="mr-3">
                                    <img src="{{ $article->featured_image_url }}" 
                                         alt="{{ $article->title }}" 
                                         class="rounded" style="width: 60px; height: 40px; object-fit: cover;">
                                </div>
                                <div class="media-body">
                                    <strong>{{ $article->title }}</strong>
                                    <div class="text-muted small">{{ Str::limit($article->excerpt, 60) }}</div>
                                    @if($article->is_featured)
                                        <span class="badge badge-warning badge-sm">Featured</span>
                                    @endif
                                </div>
                            </div>
                        </td>
                        <td>
                            @if($article->categoryModel)
                                <span class="badge badge-soft-info" style="background-color: {{ $article->categoryModel->color }}20; color: {{ $article->categoryModel->color }};">
                                    @if($article->categoryModel->icon)
                                        <i class="material-icons" style="font-size: 14px; vertical-align: middle;">{{ $article->categoryModel->icon }}</i>
                                    @endif
                                    {{ $article->categoryModel->name }}
                                </span>
                            @else
                                <span class="badge badge-soft-secondary">{{ ucfirst($article->category ?? 'Uncategorized') }}</span>
                            @endif
                        </td>
                        <td>
                            @if($article->author)
                                <div>{{ $article->author->full_name }}</div>
                                <div class="text-muted small">{{ $article->author->email }}</div>
                            @else
                                <span class="text-muted">Unknown</span>
                            @endif
                        </td>
                        <td>
                            @if($article->is_published)
                                <span class="badge badge-soft-success">Published</span>
                            @else
                                <span class="badge badge-soft-warning">Draft</span>
                            @endif
                        </td>
                        <td>
                            @if($article->published_at)
                                <div>{{ $article->published_at->format('M d, Y') }}</div>
                                <div class="text-muted small">{{ $article->published_at->format('H:i') }}</div>
                            @else
                                <span class="text-muted">-</span>
                            @endif
                        </td>
                        <td>
                            <div class="dropdown">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown" data-caret="false">
                                    <i class="material-icons">more_vert</i>
                                </a>
                                <div class="dropdown-menu dropdown-menu-right">
                                    <a href="{{ route('news.show', $article->slug) }}" class="dropdown-item" target="_blank">
                                        <i class="material-icons mr-2">visibility</i> View Article
                                    </a>
                                    <a href="{{ route('admin.news.edit', $article) }}" class="dropdown-item">
                                        <i class="material-icons mr-2">edit</i> Edit
                                    </a>
                                    <div class="dropdown-divider"></div>
                                    <a href="#" class="dropdown-item" onclick="toggleFeatured({{ $article->id }})">
                                        <i class="material-icons mr-2">{{ $article->is_featured ? 'star_border' : 'star' }}</i>
                                        {{ $article->is_featured ? 'Remove Featured' : 'Mark Featured' }}
                                    </a>
                                    <a href="#" class="dropdown-item" onclick="togglePublished({{ $article->id }})">
                                        <i class="material-icons mr-2">{{ $article->is_published ? 'visibility_off' : 'visibility' }}</i>
                                        {{ $article->is_published ? 'Unpublish' : 'Publish' }}
                                    </a>
                                    <div class="dropdown-divider"></div>
                                    <a href="#" class="dropdown-item text-danger" 
                                       data-toggle="modal" data-target="#deleteModal{{ $article->id }}">
                                        <i class="material-icons mr-2">delete</i> Delete
                                    </a>
                                </div>
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="6" class="text-center py-4">
                            <div class="empty-state">
                                <i class="material-icons mb-3" style="font-size: 48px; color: #ddd;">article</i>
                                <h5 class="text-muted">No news articles found</h5>
                                <p class="text-muted">
                                    @if(request()->hasAny(['search', 'category', 'status']))
                                        Try adjusting your search criteria or <a href="{{ route('admin.news') }}">clear filters</a>.
                                    @else
                                        Start by creating your first news article.
                                    @endif
                                </p>
                                <a href="{{ route('admin.news.create') }}" class="btn btn-primary">
                                    <i class="material-icons">add</i> Create First Article
                                </a>
                            </div>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        
        @if($news->hasPages())
            <div class="card-footer">
                {{ $news->appends(request()->query())->links('pagination::flowdash') }}
            </div>
        @endif
    </div>
@endsection

@push('scripts')
<script>
function toggleFeatured(articleId) {
    fetch(`/admin/news/${articleId}/toggle-featured`, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            'Accept': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToastMessage(data.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToastMessage(data.message || 'An error occurred', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToastMessage('An error occurred', 'error');
    });
}

function togglePublished(articleId) {
    fetch(`/admin/news/${articleId}/toggle-published`, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            'Accept': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToastMessage(data.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToastMessage(data.message || 'An error occurred', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToastMessage('An error occurred', 'error');
    });
}

function confirmDeleteArticle(articleId) {
    // Close the modal first
    $(`#deleteModal${articleId}`).modal('hide');
    
    fetch(`/admin/news/${articleId}`, {
        method: 'DELETE',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            'Accept': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToastMessage(data.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToastMessage(data.message || 'Failed to delete article', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToastMessage('An error occurred', 'error');
    });
}
</script>
@endpush

@section('modals')
    <!-- Delete Confirmation Modals -->
    @foreach($news as $article)
    <div class="modal fade" id="deleteModal{{ $article->id }}" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel{{ $article->id }}" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content border-0 shadow">
                <div class="modal-header border-0 pb-0">
                    <h5 class="modal-title font-weight-bold" id="deleteModalLabel{{ $article->id }}">Delete News Article</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body pt-2">
                    <div class="text-center">
                        <div class="mb-3">
                            <div class="bg-danger-light d-flex align-items-center justify-content-center rounded-circle mx-auto" style="width: 64px; height: 64px; background-color: rgba(220, 53, 69, 0.1);">
                                <i class="material-icons text-danger" style="font-size: 32px;">warning</i>
                            </div>
                        </div>
                        <h5 class="mb-3">Are you sure?</h5>
                        <p class="text-muted mb-3">You are about to delete the news article:</p>
                        <div class="card border-left-danger shadow-sm mb-3">
                            <div class="card-body py-3">
                                <div class="d-flex align-items-center">
                                    <img src="{{ $article->featured_image_url }}" alt="{{ $article->title }}" class="rounded mr-3" style="width: 60px; height: 40px; object-fit: cover;">
                                    <div>
                                        <strong>{{ Str::limit($article->title, 50) }}</strong>
                                        <div class="text-muted small">
                                            @if($article->categoryModel)
                                                {{ $article->categoryModel->name }}
                                            @else
                                                {{ ucfirst($article->category ?? 'General') }}
                                            @endif
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <p class="text-muted small">
                            <i class="material-icons" style="font-size: 16px; vertical-align: middle;">info_outline</i>
                            This action cannot be undone. The article and all associated data will be permanently deleted.
                        </p>
                    </div>
                </div>
                <div class="modal-footer border-0 pt-0">
                    <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">
                        <i class="material-icons mr-1" style="font-size: 18px;">close</i>
                        Cancel
                    </button>
                    <button type="button" class="btn btn-danger delete-btn" onclick="confirmDeleteArticle({{ $article->id }})">
                        <i class="material-icons mr-1" style="font-size: 18px;">delete</i>
                        Delete Article
                    </button>
                </div>
            </div>
        </div>
    </div>
    @endforeach
@endsection