@extends('admin.layouts.app')

@section('title', 'Edit Student Success Stories')

@section('content')
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1 class="h3 mb-0 text-gray-800">Edit Student Success Stories</h1>
                    <a href="{{ route('admin.testimonials.index') }}" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Back to List
                    </a>
                </div>

                @if (session('success'))
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        {{ session('success') }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                @endif

                @if (session('error'))
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        {{ session('error') }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                @endif

                @if ($errors->any())
                    <div class="alert alert-danger">
                        <ul class="mb-0">
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif

                <form id="testimonialsForm" action="{{ route('admin.testimonials.update') }}" method="POST">
                    @csrf
                    @method('PUT')

                    <!-- Section Information -->
                    <div class="card shadow mb-4">
                        <div class="card-header py-3">
                            <h6 class="m-0 font-weight-bold text-primary">Section Information</h6>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="title" class="form-label">Section Title <span
                                                class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="title" name="title"
                                            value="{{ old('title', $testimonialsSection->title ?? '') }}" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="content" class="form-label">Section Description <span
                                                class="text-danger">*</span></label>
                                        <textarea class="form-control" id="content" name="content" rows="3" required>{{ old('content', $testimonialsSection->content ?? '') }}</textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Testimonials Management -->
                    <div class="card shadow mb-4">
                        <div class="card-header py-3 d-flex justify-content-between align-items-center">
                            <h6 class="m-0 font-weight-bold text-primary">Manage Testimonials</h6>
                            <button type="button" class="btn btn-success btn-sm" data-bs-toggle="modal"
                                data-bs-target="#addTestimonialModal">
                                <i class="fas fa-plus"></i> Add Testimonial
                            </button>
                        </div>
                        <div class="card-body">
                            <div id="testimonialsContainer">
                                @if ($testimonialsSection && $testimonialsSection->data && isset($testimonialsSection->data['testimonials']))
                                    @foreach ($testimonialsSection->data['testimonials'] as $index => $testimonial)
                                        <div class="testimonial-item border rounded p-3 mb-3"
                                            data-index="{{ $index }}">
                                            <div class="row align-items-center">
                                                <div class="col-md-8">
                                                    <div class="row">
                                                        <div class="col-md-6">
                                                            <h6 class="mb-1 text-primary">
                                                                {{ $testimonial['name'] ?? 'Unknown' }}</h6>
                                                            <p class="mb-1 text-muted small">
                                                                {{ $testimonial['position'] ?? 'No position' }}</p>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <div class="text-warning mb-1">
                                                                @for ($i = 1; $i <= 5; $i++)
                                                                    @if ($i <= ($testimonial['rating'] ?? 0))
                                                                        <i class="fas fa-star"></i>
                                                                    @else
                                                                        <i class="far fa-star"></i>
                                                                    @endif
                                                                @endfor
                                                                <span
                                                                    class="text-muted small">({{ $testimonial['rating'] ?? 0 }}/5)</span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <p class="mb-0 small">
                                                        {{ Str::limit($testimonial['message'] ?? 'No message', 150) }}</p>
                                                </div>
                                                <div class="col-md-4 text-end">
                                                    <button type="button" class="btn btn-danger btn-sm remove-testimonial"
                                                        data-index="{{ $index }}">
                                                        <i class="fas fa-trash"></i> Remove
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    @endforeach
                                @else
                                    <div class="text-center py-4 text-muted">
                                        <i class="fas fa-comments fa-3x mb-3"></i>
                                        <p>No testimonials added yet. Click "Add Testimonial" to get started.</p>
                                    </div>
                                @endif
                            </div>
                        </div>
                    </div>

                    <div class="text-end">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Save Changes
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Testimonial Modal -->
    <div class="modal fade" id="addTestimonialModal" tabindex="-1" aria-labelledby="addTestimonialModalLabel"
        aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addTestimonialModalLabel">Add New Testimonial</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="addTestimonialForm">
                    @csrf
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label for="testimonial_name" class="form-label">Student Name <span
                                            class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="testimonial_name" name="name"
                                        required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label for="testimonial_position" class="form-label">Position/Course <span
                                            class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="testimonial_position" name="position"
                                        placeholder="e.g., Computer Science Graduate" required>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group mb-3">
                                    <label for="testimonial_message" class="form-label">Testimonial Message <span
                                            class="text-danger">*</span></label>
                                    <textarea class="form-control" id="testimonial_message" name="message" rows="4"
                                        placeholder="Share the student's success story..." required></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label for="testimonial_rating" class="form-label">Rating <span
                                            class="text-danger">*</span></label>
                                    <select class="form-control" id="testimonial_rating" name="rating" required>
                                        <option value="">Select Rating</option>
                                        <option value="5">5 Stars - Excellent</option>
                                        <option value="4">4 Stars - Very Good</option>
                                        <option value="3">3 Stars - Good</option>
                                        <option value="2">2 Stars - Fair</option>
                                        <option value="1">1 Star - Poor</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" id="saveTestimonial">
                            <i class="fas fa-plus"></i> Add Testimonial
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        $(document).ready(function() {
            console.log('Testimonials edit page loaded');

            // Add testimonial functionality
            $('#addTestimonialForm').on('submit', function(e) {
                e.preventDefault(); // Prevent form submission immediately
                console.log('Add testimonial form submitted');

                try {
                    const formData = new FormData(this);
                    const submitBtn = $('#saveTestimonial');
                    const originalText = submitBtn.html();

                    // Show loading state
                    submitBtn.prop('disabled', true).html(
                        '<i class="fas fa-spinner fa-spin"></i> Adding...');

                    $.ajax({
                        url: '{{ route('admin.testimonials.add-testimonial') }}',
                        method: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(response) {
                            console.log('Add testimonial success:', response);

                            if (response.success) {
                                // Close modal
                                $('#addTestimonialModal').modal('hide');

                                // Reset form
                                $('#addTestimonialForm')[0].reset();

                                // Show success message
                                alert('Testimonial added successfully!');

                                // Reload page to show new testimonial
                                window.location.reload();
                            } else {
                                alert('Error: ' + (response.message ||
                                    'Failed to add testimonial'));
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('Add testimonial error:', xhr.responseText);

                            let errorMessage =
                            'An error occurred while adding the testimonial.';

                            if (xhr.responseJSON && xhr.responseJSON.message) {
                                errorMessage = xhr.responseJSON.message;
                            } else if (xhr.responseJSON && xhr.responseJSON.errors) {
                                const errors = Object.values(xhr.responseJSON.errors).flat();
                                errorMessage = errors.join('\n');
                            }

                            alert('Error: ' + errorMessage);
                        },
                        complete: function() {
                            // Restore button state
                            submitBtn.prop('disabled', false).html(originalText);
                        }
                    });
                } catch (error) {
                    console.error('Form submission error:', error);
                    alert('An unexpected error occurred. Please try again.');
                }
            });

            // Remove testimonial functionality
            $(document).on('click', '.remove-testimonial', function() {
                const index = $(this).data('index');
                const testimonialItem = $(this).closest('.testimonial-item');

                console.log('Remove testimonial clicked, index:', index);

                if (confirm('Are you sure you want to remove this testimonial?')) {
                    try {
                        $.ajax({
                            url: '{{ route('admin.testimonials.remove-testimonial') }}',
                            method: 'DELETE',
                            data: {
                                index: index,
                                _token: $('meta[name="csrf-token"]').attr('content')
                            },
                            success: function(response) {
                                console.log('Remove testimonial success:', response);

                                if (response.success) {
                                    // Remove the testimonial item from DOM
                                    testimonialItem.fadeOut(300, function() {
                                        $(this).remove();

                                        // Check if no testimonials left
                                        if ($('.testimonial-item').length === 0) {
                                            $('#testimonialsContainer').html(`
                                        <div class="text-center py-4 text-muted">
                                            <i class="fas fa-comments fa-3x mb-3"></i>
                                            <p>No testimonials added yet. Click "Add Testimonial" to get started.</p>
                                        </div>
                                    `);
                                        }
                                    });

                                    alert('Testimonial removed successfully!');
                                } else {
                                    alert('Error: ' + (response.message ||
                                        'Failed to remove testimonial'));
                                }
                            },
                            error: function(xhr, status, error) {
                                console.error('Remove testimonial error:', xhr.responseText);

                                let errorMessage =
                                    'An error occurred while removing the testimonial.';

                                if (xhr.responseJSON && xhr.responseJSON.message) {
                                    errorMessage = xhr.responseJSON.message;
                                }

                                alert('Error: ' + errorMessage);
                            }
                        });
                    } catch (error) {
                        console.error('Remove testimonial error:', error);
                        alert('An unexpected error occurred. Please try again.');
                    }
                }
            });

            // Reset modal form when modal is hidden
            $('#addTestimonialModal').on('hidden.bs.modal', function() {
                $('#addTestimonialForm')[0].reset();
                $('#saveTestimonial').prop('disabled', false).html(
                    '<i class="fas fa-plus"></i> Add Testimonial');
            });
        });
    </script>
@endpush
