<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Video Upload with AJAX Progress</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <div class="container mt-5">
    <h2 class="mb-4">Upload Video</h2>
    <form id="uploadForm" enctype="multipart/form-data">
      <div class="mb-3">
        <label for="videoFile" class="form-label">Choose Video</label>
        <input class="form-control" type="file" id="videoFile" name="video" accept="video/*" required>
      </div>
      <button type="submit" class="btn btn-primary">Upload</button>
    </form>

    <div class="progress mt-3" style="height: 25px; display: none;">
      <div id="progressBar" class="progress-bar" role="progressbar" style="width: 0%;">0%</div>
    </div>

    <div id="status" class="mt-3"></div>
  </div>

  <script>
    $(document).ready(function() {
      $('#uploadForm').on('submit', function(e) {
        e.preventDefault();
        var fileInput = $('#videoFile')[0];
        if (fileInput.files.length === 0) return;
        var formData = new FormData(this);

        $.ajax({
          xhr: function() {
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function(e) {
              if (e.lengthComputable) {
                var percent = Math.round((e.loaded / e.total) * 100);
                $('.progress').show();
                $('#progressBar').css('width', percent + '%').text(percent + '%');
              }
            }, false);
            return xhr;
          },
          url: 'upload.php',
          type: 'POST',
          data: formData,
          contentType: false,
          processData: false,
          success: function(response) { 
            $('#status').html('<div class="alert alert-success">Upload successful! File path: ' + response.file + '</div>');
          },
          error: function(jqXHR) { console.log(jqXHR);
            var msg = 'An error occurred.';
            try {
              var err = JSON.parse(jqXHR.responseText); 
              msg = err.message || msg;
            } catch (_) {}
            $('#status').html('<div class="alert alert-danger">Upload failed: ' + msg + '</div>');
          }
        });
      });
    });
  </script>
</body>
</html>

