{% extends 'layout.twig' %}

{% block body %}
    {% include 'nav.twig' %}

    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-12 col-lg-8">
                <div class="card">
                    <div class="card-body">
                        {% if canmodify %}
                            <div class="mb-4">
                                <h5>Upload New Practice Track</h5>
                                <form id="uploadForm" enctype="multipart/form-data" method="post" class="form-inline">
                                    <input type="hidden" name="MAX_FILE_SIZE" value="500">
                                    <div class="form-group mr-2">
                                        <label for="video_name" class="sr-only">Video Name</label>
                                        <input type="text" class="form-control" id="video_name" placeholder="Video Name" required name="video_name">
                                    </div>
                                    <div class="form-group mr-2">
                                        <label for="file" class="sr-only">File</label>
                                        <input type="file" class="form-control-file" id="file" name="file" required>
                                    </div>
                                    <div class="form-check form-check-inline mr-2">
                                        <input type="checkbox" class="form-check-input" id="replace" name="replace">
                                        <label class="form-check-label" for="replace">Replace</label>
                                    </div>
                                    <button type="button" id="uploadButton" class="btn btn-primary">Upload</button>

                                    <!-- Progress Bar -->
                                    <div class="container mt-5">
                                        <div id="progressBarContainer" "class="progress w-100" style="display: none">
                                            <div id="progressBar" class="progress-bar bg-success progress-bar-striped progress-bar-animated"
                                                 role="progressbar"
                                                 aria-valuenow="0"
                                                 aria-valuemin="0"
                                                 aria-valuemax="100"
                                                 style="width: 0%; color: black; font-weight: bold; padding-left: 8px;">
                                                50%
                                            </div>
                                        </div>
                                    </div>
                                    <div id="uploadStatus" class="mt-2"></div>
                                </form>
                            </div>
                        {% endif %}
                        {% for video in videos %}
                            <div class="video-item mb-5">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        {% if videos|length == 1 %}
                                            <h5 class="mb-0">{{ video.video_name }}</h5>
                                        {% else %}
                                            <a href="Instruction_Videos.php?video_name={{ video.video_id }}" class="btn btn-link">{{ video.video_name }}</a>
                                        {% endif %}
                                    </div>
                                    {% if canmodify %}
                                        <div class="d-flex align-items-center">
                                            <a href="#" class="btn btn-danger btn-sm mr-3" onclick="deletePracticeVideo('{{ video.video_name }}')">Delete</a>
                                            <form enctype="multipart/form-data" method="post" action="" class="d-flex align-items-center mb-0">
                                                <input type="hidden" name="video_id" value="{{ video.video_id }}">
                                                <label for="priority_{{ video.video_id }}" class="sr-only">Priority</label>
                                                <input type="number" class="form-control form-control-sm mr-2" id="priority_{{ video.video_id }}" name="priority" value="{{ video.video_order }}" style="width: 80px;">
                                                <button type="submit" class="btn btn-secondary btn-sm">Update</button>
                                            </form>
                                        </div>
                                    {% endif %}
                                </div>
                                {% if videos|length == 1 %}
                                    <video class="mt-3 w-100" controlsList="nodownload" onplay="stat('play {{ video.video_name }}')" onpause="stat('pause {{ video.video_name }}')" onended="stat('ended {{ video.video_name }}')" src="fileserver.php?folder=practice_video&file={{ video.file_name }}" controls></video>
                                {% endif %}
                            </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="js/upload.js"></script>

{% endblock %}

{% block script %}
<script>
    function stat(stat) {
                fetch("api.php?method=add_stat", {
                    method: "POST",
                    headers: { "Content-Type": "application/x-www-form-urlencoded" },
                    body: `stat=${encodeURIComponent(stat)}`
                }).catch(error => console.error("Error logging stat:", error));
            }
    document.getElementById('uploadButton').addEventListener('click', async function () {
        const videoName = document.getElementById('video_name').value.trim();
        const fileInput = document.getElementById('file');
        const file = fileInput.files[0];
        const replaceFlag = document.getElementById('replace').checked;
        const uploadStatus = document.getElementById('uploadStatus');

        const progressBar = document.getElementById('progressBar');
        const progressContainer = document.getElementById('progressBarContainer');

        if (!videoName || !file) {
            alert("Please provide a video name and select a file to upload.");
            return;
        }

        progressBar.style.width = '0%';
        progressBar.setAttribute('aria-valuenow', 0);
        progressBar.innerText = '0%';
        progressContainer.style.display = 'block';
        uploadStatus.innerHTML = `<p>Checking and registering video...</p>`;
        try {
            // Step 1: Register video and get assigned file name
            const initResponse = await fetch('api.php?method=init_video', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    video_name: videoName,
                    original_file_name: file.name,
                    replace: replaceFlag ? 'true' : ''
                })
            });

            const initResult = await initResponse.json();
            if (initResult.status !== 200) {
                throw new Error(initResult.message || "Failed to initialize video.");
            }

            const finalFileName = initResult.file_name;

            uploadStatus.innerHTML = `<p>Uploading ${file.name}...</p>`;
            await uploadFile(file, 'upload_video', finalFileName, (progressPercentage) => {
                progressBar.style.width = `${progressPercentage}%`;
                progressBar.setAttribute('aria-valuenow', progressPercentage);
                progressBar.innerText = `${progressPercentage}%`;
                progressBar.offsetWidth; // force reflow

            });

            uploadStatus.innerHTML = `<p class="text-success">Upload complete! <strong>Refresh the page</strong> to see your video.</p>`;
        } catch (error) {
            uploadStatus.innerHTML = `<p class="text-danger">Upload failed: ${error.message}</p>`;
        }

    });
    function deletePracticeVideo(videoName, fileName, buttonElement) {
        if (!confirm(`Are you sure you want to delete "${videoName}"?`)) return;

        fetch('api.php?method=delete_video', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                video_name: videoName,
                file_name: fileName
            })
        })
        .then(response => response.json())
        .then(result => {
            if (result.status === 200) {
                alert("Video deleted successfully.");
                window.location.reload();  // ✅ Full page reload
            } else {
                alert("Failed to delete: " + result.message);
            }
        })
        .catch(err => {
            console.error("Delete error:", err);
            alert("Something went wrong.");
        });
    }

</script>
{% endblock %}

