<!DOCTYPE html>
<html lang="en">
@include('includes.head')
<body id="kt_body" class="header-fixed header-tablet-and-mobile-fixed toolbar-enabled toolbar-fixed aside-enabled aside-fixed">
    <div class="d-flex flex-column flex-root">
        <div class="page d-flex flex-row flex-column-fluid">
            @include('includes.side-nav')
            <div class="wrapper d-flex flex-column flex-row-fluid" id="kt_wrapper">
                @include('includes.header')
                <div class="content d-flex flex-column flex-column-fluid" id="kt_content">
                    <div class="toolbar" id="kt_toolbar">
                        <div id="kt_toolbar_container" class="container-fluid d-flex flex-stack">
                            <div class="page-title">
                                <h1 class="text-dark fw-bolder fs-3">Video Gallery</h1>
                            </div>
                            <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#videoModal" onclick="resetModalForm()">Add Video</button>
                        </div>
                    </div>
                    <div class="post d-flex flex-column-fluid" id="kt_post">
                        <div id="kt_content_container" class="container-xxl">
                            <div class="card">
                                @include('includes.messages')
                                <div class="card-header border-0 pt-6">
                                    <form method="GET" action="{{ route('videoGallery.list') }}" class="d-flex align-items-center">
                                        <div class="d-flex align-items-center position-relative me-5">
                                            <span class="svg-icon svg-icon-1 position-absolute ms-6">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
                                                    <rect opacity="0.5" x="17.0365" y="15.1223" width="8.15546" height="2" rx="1" transform="rotate(45 17.0365 15.1223)" fill="black" />
                                                    <path d="M11 19C6.55556 19 3 15.4444 3 11C3 6.55556 6.55556 3 11 3C15.4444 3 19 6.55556 19 11C19 15.4444 15.4444 19 11 19ZM11 5C7.53333 5 5 7.53333 5 11C5 14.4667 7.53333 17 11 17C14.4667 17 17 14.4667 17 11C17 7.53333 14.4667 5 11 5Z" fill="black" />
                                                </svg>
                                            </span>
                                            <input type="text" name="search" value="{{ request('search') }}" class="form-control form-control-solid w-250px ps-15" placeholder="Search by video ID..." />
                                        </div>
                                        <button type="submit" class="btn btn-primary me-2">Filter</button>
                                        <a href="{{ route('videoGallery.list') }}" class="btn btn-secondary">Reset</a>
                                    </form>
                                </div>
                                <div class="card-body pt-0">
                                    <div class="table-responsive">
                                        <table class="table align-middle table-row-dashed fs-6 gy-5">
                                            <thead>
                                                <tr class="text-start text-gray-400 fw-bolder fs-7 text-uppercase">
                                                    <th>ID</th>
                                                    <th>Thumbnail</th>
                                                    <th>Video ID</th>
                                                    <th>Preview</th>
                                                    <th>Status</th>
                                                    <th class="text-end">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                @foreach($videos as $video)
                                                <tr id="video-row-{{ $video->id }}">
                                                    <td>{{ $video->id }}</td>
                                                    <td>
                                                        <a href="#" class="video-preview" data-video-id="{{ $video->video_id }}">
                                                            <img src="https://img.youtube.com/vi/{{ $video->video_id }}/mqdefault.jpg" style="width: 80px; height: 60px; object-fit: cover;" class="rounded">
                                                        </a>
                                                    </td>
                                                    <td>{{ $video->video_id }}</td>
                                                    <td>
                                                        <button class="btn btn-sm btn-info play-video" data-video-id="{{ $video->video_id }}">
                                                            <i class="fab fa-youtube"></i> Play
                                                        </button>
                                                    </td>
                                                    <td>
                                                        <span class="badge {{ $video->status ? 'badge-success' : 'badge-danger' }}">
                                                            {{ $video->status ? 'Active' : 'Inactive' }}
                                                        </span>
                                                    </td>
                                                    <td class="text-end">
                                                        <button class="btn btn-sm btn-primary edit-btn" data-id="{{ $video->id }}">
                                                            <i class="fas fa-edit"></i> Edit
                                                        </button>
                                                        <button class="btn btn-sm btn-danger delete-btn" data-id="{{ $video->id }}">
                                                            <i class="fas fa-trash"></i> Delete
                                                        </button>
                                                    </td>
                                                </tr>
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                    {{ $videos->links('pagination::bootstrap-4') }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                @include('includes.footer')
            </div>
        </div>
    </div>
    @include('includes.scripts')

    <!-- Modal for Add/Edit Video -->
    <div class="modal fade" id="videoModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">Add Video</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="videoForm">
                        @csrf
                        <input type="hidden" name="id" id="videoId">
                        <div class="mb-3">
                            <label class="form-label required">YouTube Video ID</label>
                            <input type="text" name="video_id" id="video_id" class="form-control" placeholder="e.g., dQw4w9WgXcQ" required>
                            <small class="text-muted">The 11-character ID from YouTube URL (e.g., https://youtu.be/XXXXXXXXXXX)</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Status</label>
                            <select name="status" id="status" class="form-select">
                                <option value="1">Active</option>
                                <option value="0">Inactive</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label>Preview</label>
                            <div id="videoPreview" class="mt-2"></div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="saveBtn">Save</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Video Play Modal (optional) -->
    <div class="modal fade" id="playModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Watch Video</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="ratio ratio-16x9">
                        <iframe id="videoIframe" src="" frameborder="0" allowfullscreen></iframe>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        function resetModalForm() {
            $('#videoForm')[0].reset();
            $('#videoId').val('');
            $('#videoPreview').html('');
            $('#modalTitle').text('Add Video');
        }

        // Preview video when typing ID
        $('#video_id').on('keyup', function() {
            let videoId = $(this).val();
            if (videoId && videoId.length === 11) {
                $('#videoPreview').html('<iframe width="100%" height="200" src="https://www.youtube.com/embed/' + videoId + '" frameborder="0" allowfullscreen></iframe>');
            } else {
                $('#videoPreview').html('');
            }
        });

        // Save Video
        $('#saveBtn').click(function() {
            let id = $('#videoId').val();
            let url = id ? "{{ route('videoGallery.update', '') }}/" + id : "{{ route('videoGallery.store') }}";
            let formData = {
                video_id: $('#video_id').val(),
                status: $('#status').val(),
                _token: '{{ csrf_token() }}'
            };
            if (id) formData._method = 'PUT';

            $.ajax({
                url: url,
                type: 'POST',
                data: formData,
                success: function(res) {
                    if (res.success) {
                        $('#videoModal').modal('hide');
                        location.reload();
                    } else {
                        alert('Error saving video');
                    }
                },
                error: function(xhr) {
                    let errors = xhr.responseJSON.errors;
                    if (errors) alert(Object.values(errors).flat().join('\n'));
                    else alert('Something went wrong');
                }
            });
        });

        // Edit Video
        $('.edit-btn').click(function() {
            let id = $(this).data('id');
            $.get("{{ route('videoGallery.edit', '') }}/" + id, function(res) {
                if (res.success) {
                    let v = res.video;
                    $('#videoId').val(v.id);
                    $('#video_id').val(v.video_id);
                    $('#status').val(v.status);
                    if (v.video_id && v.video_id.length === 11) {
                        $('#videoPreview').html('<iframe width="100%" height="200" src="https://www.youtube.com/embed/' + v.video_id + '" frameborder="0" allowfullscreen></iframe>');
                    } else {
                        $('#videoPreview').html('');
                    }
                    $('#modalTitle').text('Edit Video');
                    $('#videoModal').modal('show');
                } else {
                    alert('Video not found');
                }
            });
        });

        // Delete Video
        $('.delete-btn').click(function() {
            if (confirm('Delete this video?')) {
                let id = $(this).data('id');
                $.ajax({
                    url: "{{ route('videoGallery.delete', '') }}/" + id,
                    type: 'DELETE',
                    data: { _token: '{{ csrf_token() }}' },
                    success: function(res) {
                        if (res.success) {
                            $('#video-row-' + id).remove();
                            if ($('tbody tr').length === 0) location.reload();
                        } else {
                            alert('Delete failed');
                        }
                    }
                });
            }
        });

        // Play video (from table preview button)
        $('.play-video').click(function() {
            let videoId = $(this).data('video-id');
            if (videoId) {
                $('#videoIframe').attr('src', 'https://www.youtube.com/embed/' + videoId + '?autoplay=1');
                $('#playModal').modal('show');
            }
        });

        // Reset iframe when modal closes
        $('#playModal').on('hidden.bs.modal', function() {
            $('#videoIframe').attr('src', '');
        });
    </script>
</body>
</html>
