@extends('admin.layouts.master')
@section('title', __('importer'))
@section('content')

<section class="oftions">
    <div class="container-fluid">
        <div class="row">
            <div class="col col-md-12">
                <div class="header-top d-flex justify-content-between align-items-center">
                    <h3 class="section-title">{{ __('tmdb_importer') }}</h3>

                </div>
                <div class="row justify-content-center">
                    <div class="col-lg-8">
                        <div class="bg-white redious-border rounded-20 p-20 p-sm-30">
                            <h4> {{ __('import_movies/tv_show_from_tmdb') }} </h4>
                            <hr>
                            <div class="row g-2">
                                <div class="col-12">
                                    <div class="position-relative">
                                        <select class="form-select form-select-lg with_search w-100 pe-4" name="language"
                                            id="language" aria-describedby="error-language language-help">
                                            <option value="" selected disabled> {{ __('select_movie_language') }} </option>
                                            @foreach ($movie_languages as $language)
                                            <option value="{{ $language->slug }}"
                                                {{ $language->slug == get_config('tmdb_default_language') ? 'selected' : '' }}>
                                                {{ $language->name }}
                                            </option>
                                            @endforeach
                                        </select>
                                        <span class="position-absolute top-50 end-0 translate-middle-y me-3" style="z-index: 5;">
                                            <i class="bx bx-info-circle text-muted" style="font-size: 1.15rem;" title="{{ __('tmdb_language_help') }}" data-bs-toggle="tooltip" data-bs-placement="top" aria-label="{{ __('tmdb_language_help') }}"></i>
                                        </span>
                                    </div>
                                    <div class="invalid-feedback d-block small text-danger" id="error-language" role="alert"></div>
                                    <p class="form-text text-muted small mt-1 mb-0" id="language-help">{{ __('tmdb_language_help') }}</p>
                                </div>
                                <div class="col-12">
                                    <select class="form-select form-select-lg with_search w-100" name="type"
                                        id="type" aria-describedby="error-type">
                                        <option value="movies_by_title">{{ __('movies_by_title') }}</option>
                                        <option value="popular_movies">{{ __('popular_movies') }}</option>
                                        <option value="top_rated_movies">{{ __('top_rated_movies') }}</option>
                                        <option value="upcoming_movies">{{ __('upcoming_movies') }}</option>
                                        <option value="movies_by_year">{{ __('movies_by_year') }}</option>
                                        <option value="movies_by_genre">{{ __('movies_by_genre') }}</option>
                                        <option value="movies_by_keyword">{{ __('movies_by_keyword') }}</option>
                                        <option value="movies_by_people">{{ __('movies_by_people') }}</option>
                                        <option value="tvshows_by_title">{{ __('tvshows_by_title') }}</option>
                                        <option value="popular_tvshows">{{ __('popular_tvshows') }}</option>
                                        <option value="top_rated_tvshows">{{ __('top_rated_tvshows') }}</option>
                                        <option value="on_air_tvshows">{{ __('on_air_tvshows') }}</option>
                                        <option value="tvshows_by_year">{{ __('tvshows_by_year') }}</option>
                                        <option value="tvshows_latest">{{ __('tvshows_latest') }}</option>
                                        <option value="tvshows_by_people">{{ __('tvshows_by_people') }}</option>
                                    </select>
                                    <div class="invalid-feedback d-block small text-danger" id="error-type" role="alert"></div>
                                </div>
                                <div class="col-12" id="wrap-title">
                                    <input type="text" class="form-control placeholder-font " id="title" name="title"
                                        placeholder="{{ __('enter_movie/tv_show_title,_keywords_here') }}"
                                        aria-describedby="error-title">
                                    <div class="invalid-feedback d-block small text-danger" id="error-title" role="alert"></div>
                                </div>
                                <div class="col-12 d-none" id="wrap-genre">
                                    <select class="form-select w-100" name="genre_id" id="genre-select"
                                        aria-describedby="error-genre">
                                        <option value="">{{ __('select_genre') }}</option>
                                        @foreach ($tmdb_genres ?? [] as $genre)
                                        <option value="{{ $genre['id'] }}">{{ $genre['name'] }}</option>
                                        @endforeach
                                    </select>
                                    <div class="invalid-feedback d-block small text-danger" id="error-genre" role="alert"></div>
                                </div>
                                <div class="col-12 d-none" id="wrap-year">
                                    <input type="number" class="form-control form-control-lg" name="year"
                                        id="year" placeholder="{{ __('Ex:2025') }}" value="{{ date('Y') }}">
                                </div>
                                <div class="col-12 d-none">
                                    <input type="text" class="form-control placeholder-font" name="tmdb_id"
                                        id="tmdb-id" placeholder="{{ __('Enter ID Here') }}">
                                </div>
                                <div class="col-12">
                                    <input type="number" class="form-control placeholder-font input-page-no" name="page"
                                        min="1" id="page" placeholder="{{ __('Page no.Ex:5(optional)') }}" value="1">
                                </div>
                                @can('admin.fetch.movies')
                                <div class="col-12">
                                    <button type="button" class="btn sg-btn-primary" id="fetchButton">{{ __('fetch') }}</button>
                                </div>
                                @endcan
                            </div>
                        </div>
                        <div class="mt-3 bg-white redious-border rounded-20 p-20 p-sm-30" id="fetch-data"
                            data-movie-tmdb-ids='@json($movie_tmdb_ids ?? [])'
                            data-tv-tmdb-ids='@json($tv_show_tmdb_ids ?? [])'>
                            {{ __('list_will_be_show_here') }}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
@endsection
@push('js')
<script>
    "use strict";
    var movie_tmdb_ids = JSON.parse(document.getElementById('fetch-data').getAttribute('data-movie-tmdb-ids') || '[]');
    var tv_show_tmdb_ids = JSON.parse(document.getElementById('fetch-data').getAttribute('data-tv-tmdb-ids') || '[]');
    var currentPage = 1;
    var totalPages = 1;

    function typesRequiringTitle() {
        return ['movies_by_title', 'tvshows_by_title', 'movies_by_keyword', 'movies_by_people', 'tvshows_by_people'];
    }

    function clearFieldErrors() {
        $('#language, #type, #title, #genre-select, #year').removeClass('is-invalid');
        $('#error-language, #error-type, #error-title, #error-genre').text('').attr('aria-live', 'off');
    }

    function showFieldError(fieldId, errorElId, message) {
        $(fieldId).addClass('is-invalid');
        $(errorElId).text(message).attr('aria-live', 'polite');
        $(fieldId).focus();
    }

    function getSearchFieldMessage(type) {
        var messages = {
            movies_by_title: '{{ __("enter_movie_title_to_search") }}',
            tvshows_by_title: '{{ __("enter_tv_show_title_to_search") }}',
            movies_by_keyword: '{{ __("enter_keywords_to_search_movies") }}',
            movies_by_people: '{{ __("enter_person_name_for_movies") }}',
            tvshows_by_people: '{{ __("enter_person_name_for_tv_shows") }}'
        };
        return messages[type] || '{{ __("title_is_required") }}';
    }

    var fieldToErrorId = { language: 'error-language', type: 'error-type', title: 'error-title', genre_select: 'error-genre', year: 'error-year' };
    $('#language, #type, #title, #genre-select, #year').on('input change', function() {
        var key = this.id.replace(/-/g, '_');
        $(this).removeClass('is-invalid');
        $('#' + (fieldToErrorId[key] || ('error-' + this.id))).text('');
    });

    $('#type').on('change', function() {
        var selected = $(this).val();
        var needYear = (selected === 'movies_by_year' || selected === 'tvshows_by_year');
        var needGenre = (selected === 'movies_by_genre');
        var needTitle = typesRequiringTitle().indexOf(selected) !== -1;

        $('#wrap-year').toggleClass('d-none', !needYear);
        $('#year').toggleClass('d-none', !needYear);
        $('#wrap-genre').toggleClass('d-none', !needGenre);
        $('#genre-select').toggleClass('d-none', !needGenre);
        $('#tmdb-id').toggleClass('d-none', true);
        $('#wrap-title').toggleClass('d-none', !needTitle);
        $('#title').toggleClass('d-none', !needTitle);
        clearFieldErrors();
    });

    $(document).ready(function() {
        var t = $('#type').val();
        var needTitle = typesRequiringTitle().indexOf(t) !== -1;
        var needGenre = (t === 'movies_by_genre');
        var needYear = (t === 'movies_by_year' || t === 'tvshows_by_year');
        $('#wrap-title, #title').toggleClass('d-none', !needTitle);
        $('#wrap-genre, #genre-select').toggleClass('d-none', !needGenre);
        $('#wrap-year, #year').toggleClass('d-none', !needYear);
    });

    $(document).ready(function() {
        $("#fetchButton").click(function() {
            var $btn = $(this);
            var language = $("#language").val();
            var type = $("#type").val();
            var title = $("#title").val().trim();
            var year = $("#year").val();
            var tmdb_id = ($("#type").val() === 'movies_by_genre') ? $("#genre-select").val() : $("#tmdb-id").val();
            var page = parseInt($("#page").val(), 10) || 1;

            clearFieldErrors();
            if (!language) {
                showFieldError('#language', '#error-language', '{{ __("please_select_language") }}');
                return;
            }
            if (!type) {
                showFieldError('#type', '#error-type', '{{ __("please_select_search_type") }}');
                return;
            }
            if (typesRequiringTitle().indexOf(type) !== -1 && !title) {
                showFieldError('#title', '#error-title', getSearchFieldMessage(type));
                return;
            }
            if (type === 'movies_by_genre' && !tmdb_id) {
                showFieldError('#genre-select', '#error-genre', '{{ __("please_select_a_genre") }}');
                return;
            }

            $btn.prop('disabled', true);
            $("#fetch-data").html('<div class="text-center py-5"><span class="spinner-border text-primary" role="status"></span><p class="mt-2">{{ __("importer_loading") }}</p></div>');

            $.ajax({
                url: "{{ route('admin.fetch.movies') }}",
                type: "GET",
                data: { language: language, type: type, title: title, year: year, tmdb_id: tmdb_id, page: page },
                success: function(response) {
                    if (response.error) {
                        $("#fetch-data").html('<p class="text-danger">' + (response.error || '{{ __("error_fetching_data_please_try_again") }}') + '</p>');
                        return;
                    }
                    currentPage = response.page || 1;
                    totalPages = response.total_pages || 1;

                    if (response.results && response.results.length > 0) {
                        var html = '';
                        if (totalPages > 1) {
                            html += '<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">';
                            html += '<span>{{ __("page") }} ' + currentPage + ' {{ __("of") }} ' + totalPages + '</span>';
                            html += '<div class="btn-group">';
                            if (currentPage > 1) {
                                html += '<button type="button" class="btn btn-sm btn-outline-primary page-prev" data-page="' + (currentPage - 1) + '">&larr; {{ __("previous") }}</button>';
                            }
                            if (currentPage < totalPages) {
                                html += '<button type="button" class="btn btn-sm btn-outline-primary page-next" data-page="' + (currentPage + 1) + '">{{ __("next") }} &rarr;</button>';
                            }
                            html += '</div></div>';
                        }
                        response.results.forEach(function(movie) {
                            var selectedType = $('#type').val();
                            var lang = $('#language').val();
                            var movieId = movie.id;
                            var rawImportUrl = "{{ route('admin.import.db', ['language' => '__LANG__', 'type' => '__TYPE__', 'id' => '__ID__']) }}";
                            var importUrl = rawImportUrl.replace('__LANG__', encodeURIComponent(lang)).replace('__TYPE__', selectedType).replace('__ID__', encodeURIComponent(movieId));
                            var isMovie = ['movies_by_title', 'popular_movies', 'top_rated_movies', 'upcoming_movies', 'movies_by_year', 'movies_by_genre', 'movies_by_keyword', 'movies_by_people'].indexOf(selectedType) !== -1;
                            var isExisting = isMovie ? movie_tmdb_ids.indexOf(movieId) !== -1 : tv_show_tmdb_ids.indexOf(movieId) !== -1;
                            var posterSrc = (movie.poster_path) ? ('https://image.tmdb.org/t/p/w200' + movie.poster_path) : 'https://placehold.co/200x300?text=No+Poster';
                            var titleText = (movie.title || movie.name || '');
                            var dateText = (movie.release_date || movie.first_air_date || '');
                            var importBtn = isExisting
                                ? '<button class="px-3 py-1 mt-2 btn sg-btn-primary rounded border-0 text-muted" disabled><i class="bx bx-check"></i> {{ __("imported") }}</button>'
                                : '<a href="javascript:void(0)" data-url="' + importUrl + '" data-id="' + movieId + '" data-is-movie="' + (isMovie ? '1' : '0') + '" class="px-3 py-1 mt-2 btn sg-btn-primary rounded border-0 import-db" title="Import"><i class="bx bx-import"></i> {{ __("import") }}</a>';
                            html += '<div class="movie-item"><div class="d-flex align-items-center gap-3">';
                            html += '<img src="' + posterSrc + '" width="100" class="rounded" alt="' + titleText + '">';
                            html += '<div><h5>' + titleText + (dateText ? ' (' + dateText + ')' : '') + '</h5>';
                            html += '<p>{{ __("rating") }}: ' + (movie.vote_average || '-') + '</p>';
                            html += '<p>{{ __("description") }}: ' + (movie.overview || 'N/A') + '</p>' + importBtn + '</div></div></div><hr>';
                        });
                        $("#fetch-data").html(html);
                    } else {
                        $("#fetch-data").html("<p>{{ __('no_results_found') }}</p>");
                    }
                },
                error: function() {
                    $("#fetch-data").html("<p>{{ __('error_fetching_data_please_try_again') }}</p>");
                },
                complete: function() {
                    $btn.prop('disabled', false);
                }
            });
        });

        $(document).on('click', '.page-prev, .page-next', function() {
            var p = $(this).data('page');
            $("#page").val(p);
            $("#fetchButton").click();
        });
    });

    $(document).on("click", ".import-db", function() {
        var el = this;
        var $el = $(el);
        var url = $el.data('url');
        var id = $el.data('id');
        var isMovie = $el.data('is-movie') === 1;
        $el.prop('disabled', true).html('<i class="bx bx-loader-alt bx-spin"></i> {{ __("importing") }}');
        $.ajax({
            dataType: "json",
            type: "GET",
            url: url,
            success: function(response) {
                if (response.status === 'success') {
                    if (isMovie) { movie_tmdb_ids.push(id); } else { tv_show_tmdb_ids.push(id); }
                    $el.replaceWith('<button class="px-3 py-1 mt-2 btn sg-btn-primary rounded border-0 text-muted" disabled><i class="bx bx-check"></i> {{ __("imported") }}</button>');
                    toastr['success'](response.message);
                } else if (response.status === 'info') {
                    toastr['info'](response.message);
                    if (isMovie) { movie_tmdb_ids.push(id); } else { tv_show_tmdb_ids.push(id); }
                    $el.replaceWith('<button class="px-3 py-1 mt-2 btn sg-btn-primary rounded border-0 text-muted" disabled><i class="bx bx-check"></i> {{ __("imported") }}</button>');
                } else {
                    toastr['error'](response.message || '{{ __("Something went wrong. Please try again.") }}');
                    $el.html('<i class="bx bx-import"></i> {{ __("import") }}').prop('disabled', false);
                }
            },
            error: function() {
                toastr['error']('{{ __("error_fetching_data_please_try_again") }}');
                $el.html('<i class="bx bx-import"></i> {{ __("import") }}').prop('disabled', false);
            }
        });
    });
</script>
@endpush