<!-- templates/movie_request.html -->
{% extends 'base.html' %}
{% block title %}Request a Movie - BlickBox{% endblock %}
{% block content %}
<div class="content-box">
    <div class="movie-request-container">
        <h2>Request a Movie</h2>
        <div class="form-group">
            <label for="title">Movie Title</label>
            <input type="text" id="title" placeholder="Enter movie or series title">
        </div>
        <div class="form-group">
            <label for="email">Your Email</label>
            <input type="email" id="email" placeholder="Enter your email">
        </div>
        <button id="submit-button">OK</button>
        <p class="error" id="error-message" style="display: none;"></p>
    </div>
</div>
{% endblock %}
{% block scripts %}
<script>
    // Redirect to login if not authenticated
    if (!localStorage.getItem('access_token')) {
        window.location.href = '/login/';
    }

   
    async function refreshToken() {
        const refreshToken = localStorage.getItem('refresh_token');
        if (!refreshToken) {
            localStorage.removeItem('access_token');
            window.location.href = '/login/';
            throw new Error('No refresh token available. Please log in.');
        }

        const response = await fetch('/api/token/refresh/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ refresh: refreshToken }),
        });

        if (!response.ok) {
            localStorage.removeItem('access_token');
            localStorage.removeItem('refresh_token');
            window.location.href = '/login/';
            throw new Error('Failed to refresh token. Please log in again.');
        }

        const data = await response.json();
        localStorage.setItem('access_token', data.access);
        if (data.refresh) {
            localStorage.setItem('refresh_token', data.refresh);
        }
        return data.access;
    }

    async function fetchWithAuth(url, options = {}) {
        let token = localStorage.getItem('access_token');
        if (!token) {
            throw new Error('Please log in to view content');
        }

        options.headers = {
            ...options.headers,
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
        };

        let response = await fetch(url, options);
        if (response.status === 401) {
            token = await refreshToken();
            options.headers['Authorization'] = `Bearer ${token}`;
            response = await fetch(url, options);
        }

        if (!response.ok) {
            const errorData = await response.json().catch(() => ({}));
            throw new Error(errorData.error || `Failed to fetch data from ${url}`);
        }

        return response.json();
    }
    async function submitRequest() {
        const title = document.getElementById('title').value;
        const email = document.getElementById('email').value;
        const errorMessage = document.getElementById('error-message');

        if (!title || !email) {
            errorMessage.textContent = 'Please fill in all fields';
            errorMessage.style.display = 'block';
            return;
        }

        document.getElementById('submit-button').disabled = true;
        errorMessage.style.display = 'none';

        try {
            const response = await fetch('/api/movie-request/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    title: title,
                    user_email: email
                })
            });

            if (response.ok) {
                alert('Request submitted successfully!');
                document.getElementById('title').value = '';
                document.getElementById('email').value = '';
            } else {
                const errorData = await response.json();
                errorMessage.textContent = errorData.error || 'Failed to submit request';
                errorMessage.style.display = 'block';
            }
        } catch (err) {
            errorMessage.textContent = 'Error: ' + err.message;
            errorMessage.style.display = 'block';
        } finally {
            document.getElementById('submit-button').disabled = false;
        }
    }

    document.addEventListener('DOMContentLoaded', () => {
        document.getElementById('submit-button').addEventListener('click', submitRequest);
    });
</script>
{% endblock %}

