@extends('layouts.master')

@section('header')
	@include('common.header')
	<meta name="csrf-token" content="{{ csrf_token() }}">
@stop

@section('content')

<div class="row">
    {{-- Left Sidebar Controls --}}
    <div class="col-md-3">
        <div class="widget widget-classic">
            <div class="widget-content">
                {{-- Add New Quote Button --}}
                <button type="button" class="btn btn-primary btn-block mb-3" data-toggle="modal" data-target="#addQuoteModal">
                    <i class="fa fa-plus"></i> Add New Quote
                </button>

                {{-- Fetch Quotes Button --}}
                <button type="button" id="fetchQuotesBtn" class="btn btn-success btn-block mb-3">
                    <i class="fa fa-download"></i> Fetch from Real Inspire API
                </button>

                {{-- Stats Panel --}}
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4 class="panel-title"><i class="fa fa-info-circle"></i> Quote Statistics</h4>
                    </div>
                    <div class="panel-body">
                        <p><strong>Total Quotes:</strong> <span id="totalQuotes">{{ $totalQuotes }}</span></p>
                        @if(isset($currentPage))
                        <p><strong>Next API Fetch:</strong> Page {{ $currentPage }} of 541 <small class="text-muted">(~20 quotes per page)</small></p>
                        @endif
                    </div>
                </div>

                {{-- Success/Error Messages Panel --}}
                <div id="messagesPanel" style="display: none;">
                    <div id="successMessage" class="alert alert-success" style="display: none;">
                        <button type="button" class="close" onclick="hideMessage('success')">
                            <span>&times;</span>
                        </button>
                        <span id="successText"></span>
                    </div>
                    <div id="errorMessage" class="alert alert-danger" style="display: none;">
                        <button type="button" class="close" onclick="hideMessage('error')">
                            <span>&times;</span>
                        </button>
                        <span id="errorText"></span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- Main Content Area --}}
    <div class="col-md-9">
        <div class="widget widget-classic">
            <div class="widget-content">
                <div class="section-header">
                    <h4><i class="fa fa-quote-left"></i> Quote of the Day Management</h4>
                </div>

                {{-- Server-side Messages (for form submissions) --}}
                @if(session('success'))
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        {{ session('success') }}
                        <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">
                        {{ session('error') }}
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                @endif

                {{-- Loading Spinner --}}
                <div id="loadingSpinner" class="text-center" style="display: none;">
                    <i class="fa fa-spinner fa-spin fa-2x"></i>
                    <p>Fetching quotes from Real Inspire API...</p>
                </div>

                {{-- Quotes Table --}}
                <div class="table-responsive">
                    <table class="table table-striped table-bordered">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Quote</th>
                                <th>Author</th>
                                <th>Category</th>
                                <th>Created</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="quotesTableBody">
                            @forelse($quotes as $quote)
                                <tr id="quote-{{ $quote->id }}">
                                    <td>{{ $quote->id }}</td>
                                    <td>
                                        <div style="max-width: 400px; word-wrap: break-word;">
                                            "{{ \Illuminate\Support\Str::limit($quote->text, 100) }}"
                                        </div>
                                    </td>
                                    <td>{{ $quote->author }}</td>
                                    <td>{{ $quote->category ?? 'N/A' }}</td>
                                    <td>{{ $quote->created_at->format('M d, Y') }}</td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <button type="button" class="btn btn-info btn-sm" onclick="editQuote({{ $quote->id }}, {{ json_encode($quote->text) }}, {{ json_encode($quote->author) }}, {{ json_encode($quote->category) }})">
                                                <i class="fa fa-edit"></i>
                                            </button>
                                            <button type="button" class="btn btn-danger btn-sm" onclick="deleteQuote({{ $quote->id }})">
                                                <i class="fa fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            @empty
                                <tr id="noQuotesRow">
                                    <td colspan="6" class="text-center">
                                        <p class="text-muted">No quotes found. <a href="#" data-toggle="modal" data-target="#addQuoteModal">Add your first quote</a> or <a href="#" onclick="fetchQuotes()">fetch quotes from Real Inspire API</a>.</p>
                                    </td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>

                {{-- Pagination --}}
                @if($quotes->hasPages())
                    <div class="text-center">
                        {{ $quotes->links('quotes::pagination') }}
                    </div>
                @endif
            </div>
        </div>
    </div>
</div>

{{-- Add Quote Modal --}}
<div class="modal fade" id="addQuoteModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Add New Quote</h4>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <form method="POST" action="{{ route('admin.quotes.store') }}">
                @csrf
                <div class="modal-body">
                    <div class="form-group">
                        <label for="text">Quote Text</label>
                        <textarea class="form-control" name="text" id="text" rows="3" required maxlength="1000"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="author">Author</label>
                        <input type="text" class="form-control" name="author" id="author" required maxlength="255">
                    </div>
                    <div class="form-group">
                        <label for="category">Category (Optional)</label>
                        <input type="text" class="form-control" name="category" id="category" maxlength="100">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Quote</button>
                </div>
            </form>
        </div>
    </div>
</div>

{{-- Edit Quote Modal --}}
<div class="modal fade" id="editQuoteModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Edit Quote</h4>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <form method="POST" id="editQuoteForm">
                @csrf
                @method('PUT')
                <div class="modal-body">
                    <div class="form-group">
                        <label for="edit_text">Quote Text</label>
                        <textarea class="form-control" name="text" id="edit_text" rows="3" required maxlength="1000"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="edit_author">Author</label>
                        <input type="text" class="form-control" name="author" id="edit_author" required maxlength="255">
                    </div>
                    <div class="form-group">
                        <label for="edit_category">Category (Optional)</label>
                        <input type="text" class="form-control" name="category" id="edit_category" maxlength="100">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Quote</button>
                </div>
            </form>
        </div>
    </div>
</div>

@stop

@section('js')
<script>
$(document).ready(function() {
    console.log('Quotes management script loaded');
    
    // Edit form submission
    $('#editQuoteForm').on('submit', function(e) {
        e.preventDefault();
        
        const form = this;
        const formData = new FormData(form);
        const url = form.action;
        
        console.log('Submitting edit form to:', url);
        
        CSRFManager.handleRequest(url, {
            method: 'POST',
            body: formData,
            headers: {                
                'X-HTTP-Method-Override': 'PUT'
            }
        })
        .then(response => {
            if (response.redirected) {
                window.location.href = response.url;
                return;
            }
            return response.json();
        })
        .then(data => {
            if (data && data.success) {
                $('#editQuoteModal').modal('hide');
                showMessage('success', 'Quote updated successfully!');
                setTimeout(() => window.location.reload(), 1500);
            } else if (data && !data.success) {
                showMessage('error', data.message || 'Error updating quote');
            }
        })
        .catch(error => {
            console.error('Error updating quote:', error);
            showMessage('error', 'Error updating quote');
        });
    });
    
    // Fetch quotes button
    $('#fetchQuotesBtn').on('click', function(e) {
        e.preventDefault();
        fetchQuotes();
    });
});

// Edit quote function
function editQuote(id, text, author, category) {
    console.log('Editing quote:', id, text, author, category);
    
    // Data is already properly encoded as JSON, just assign directly
    document.getElementById('edit_text').value = text || '';
    document.getElementById('edit_author').value = author || '';
    document.getElementById('edit_category').value = category || '';
    document.getElementById('editQuoteForm').action = '{{ url('admin/general/quote-of-the-day') }}/' + id;
    $('#editQuoteModal').modal('show');
}

// Delete quote function
function deleteQuote(id) {
    console.log('Deleting quote:', id);
    
    if (!confirm('Are you sure you want to delete this quote?')) {
        return;
    }
    
    CSRFManager.handleRequest('{{ url('admin/general/quote-of-the-day') }}/' + id, {
        method: 'DELETE',
        headers: {            
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    })
    .then(response => {
        console.log('Delete response status:', response.status);
        return response.json();
    })
    .then(data => {
        console.log('Delete response:', data);
        if (data.success) {
            // Remove the table row
            const row = document.getElementById('quote-' + id);
            if (row) {
                row.style.transition = 'opacity 0.3s';
                row.style.opacity = '0';
                setTimeout(() => {
                    row.remove();
                    updateQuoteCount(-1);
                    
                    // Check if table is empty
                    const tbody = document.getElementById('quotesTableBody');
                    if (tbody && tbody.children.length === 0) {
                        tbody.innerHTML = '<tr id="noQuotesRow"><td colspan="6" class="text-center"><p class="text-muted">No quotes found. <a href="#" data-toggle="modal" data-target="#addQuoteModal">Add your first quote</a> or <a href="#" onclick="fetchQuotes()">fetch quotes from Real Inspire API</a>.</p></td></tr>';
                    }
                }, 300);
            }
            showMessage('success', 'Quote deleted successfully!');
        } else {
            showMessage('error', data.message || 'Error deleting quote');
        }
    })
    .catch(error => {
        console.error('Error deleting quote:', error);
        showMessage('error', 'Error deleting quote');
    });
}

// Async fetch quotes function
function fetchQuotes() {
    console.log('Fetching quotes...');
    
    const button = document.getElementById('fetchQuotesBtn');
    const spinner = document.getElementById('loadingSpinner');
    
    if (!button || !spinner) {
        console.error('Button or spinner element not found');
        return;
    }
    
    // Disable button and show spinner
    button.disabled = true;
    button.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Fetching...';
    spinner.style.display = 'block';
    
    CSRFManager.handleRequest('{{ route('admin.quotes.fetch') }}', {
        method: 'POST',
        headers: {            
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    })
    .then(response => {
        console.log('Fetch response status:', response.status);
        return response.json();
    })
    .then(data => {
        console.log('Fetch response:', data);
        if (data.success) {
            showMessage('success', data.message);
            setTimeout(() => {
                window.location.reload();
            }, 2000);
        } else {
            showMessage('error', data.message || 'Error fetching quotes');
        }
    })
    .catch(error => {
        console.error('Error fetching quotes:', error);
        showMessage('error', 'Error fetching quotes from Real Inspire API');
    })
    .finally(() => {
        // Re-enable button and hide spinner
        button.disabled = false;
        button.innerHTML = '<i class="fa fa-download"></i> Fetch Quotes from Real Inspire API';
        spinner.style.display = 'none';
    });
}

// Show message function
function showMessage(type, message) {
    console.log('Showing message:', type, message);
    
    const messagesPanel = document.getElementById('messagesPanel');
    const messageDiv = document.getElementById(type + 'Message');
    const messageText = document.getElementById(type + 'Text');
    
    if (!messagesPanel || !messageDiv || !messageText) {
        console.error('Message elements not found');
        alert(message); // Fallback
        return;
    }
    
    messageText.textContent = message;
    messagesPanel.style.display = 'block';
    messageDiv.style.display = 'block';
    
    // Hide other message type
    const otherType = type === 'success' ? 'error' : 'success';
    const otherMessage = document.getElementById(otherType + 'Message');
    if (otherMessage) {
        otherMessage.style.display = 'none';
    }
    
    // Auto-hide after 5 seconds
    setTimeout(() => {
        hideMessage(type);
    }, 5000);
}

// Hide message function
function hideMessage(type) {
    const messageDiv = document.getElementById(type + 'Message');
    if (messageDiv) {
        messageDiv.style.display = 'none';
    }
    
    // Hide panel if no messages are visible
    const successVisible = document.getElementById('successMessage') && document.getElementById('successMessage').style.display !== 'none';
    const errorVisible = document.getElementById('errorMessage') && document.getElementById('errorMessage').style.display !== 'none';
    
    if (!successVisible && !errorVisible) {
        const messagesPanel = document.getElementById('messagesPanel');
        if (messagesPanel) {
            messagesPanel.style.display = 'none';
        }
    }
}

// Update quote count
function updateQuoteCount(change) {
    const countElement = document.getElementById('totalQuotes');
    if (countElement) {
        const currentCount = parseInt(countElement.textContent) || 0;
        countElement.textContent = currentCount + change;
    }
}
</script>
@stop