{# templates/container-photos.html #}
{% extends "barrier/barrier-base.html" %}
{% load static %}

{% block content %}
<div class="barrier-container">
    <h2 class="text-2xl mb-4">Container Photos - {{ container.number }}</h2>

    {% csrf_token %}  {# Added CSRF token here #}

    <div class="photo-upload-section mb-4">
        <video id="video" class="mb-4 w-full" autoplay></video>
        <canvas id="canvas" style="display:none;"></canvas>

        <div class="flex justify-between mb-4">
            <button id="capture" class="btn-primary" {% if photos_count >= 3 %}disabled{% endif %}>
                Take Photo ({{ photos_count }}/3)
            </button>
            <a href="{% url 'barrier_dashboard' %}" class="btn-secondary">Back to Dashboard</a>
        </div>
    </div>

    <div id="photos-preview" class="grid grid-cols-3 gap-4">
        {% for photo in photos %}
            <div class="photo-preview">
                <img src="{{ photo.photo.url }}" alt="Container photo" class="w-full">
            </div>
        {% endfor %}
    </div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const video = document.getElementById('video');
        const canvas = document.getElementById('canvas');
        const captureButton = document.getElementById('capture');
        let photoCount = {{ photos_count }};
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;

        navigator.mediaDevices.getUserMedia({ video: true })
            .then(stream => {
                video.srcObject = stream;
            })
            .catch(err => {
                console.error('Camera error:', err);
                alert('Could not access camera. Please check permissions.');
            });


    captureButton.addEventListener('click', () => {
        if (photoCount >= 3) return;

        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d').drawImage(video, 0, 0);

        const photo = canvas.toDataURL('image/jpeg').split(',')[1];

        fetch(`/api/damages/{{ container.pk }}/`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            },
            body: JSON.stringify({
                depot_id: {{ container.pk }},
                photo_extension: 'jpg',
                photo: photo
            })
        })
        .then(async response => {
            if (response.status === 201) {
                photoCount++;
                if (photoCount >= 3) {
                    captureButton.disabled = true;
                }
                location.reload();
            } else {
                const error = await response.json();
                throw new Error(error.error || 'Upload failed');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert(error.message);
        });
    });
    });
</script>
</div>
{% endblock %}