<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Image 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 Image</h2>
    <form id="uploadForm" enctype="multipart/form-data">
      <div class="mb-3">
        <label for="imageFile" class="form-label">Choose Image</label>
        <input class="form-control" type="file" id="imageFile" name="image" accept=".png,.jpg,.jpeg" 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 id="preview" class="mt-3"></div>
  </div>

  <script>
    $(document).ready(function() {
      const maxSize = 20 * 1024 * 1024; // 20MB
      const validTypes = ['image/png', 'image/jpeg', 'image/jpg'];

      $('#imageFile').on('change', function() {
        $('#status').html('');
        $('#preview').html('');
        $('.progress').hide();
        $('#progressBar').css('width', '0%').text('0%');
      });

      $('#uploadForm').on('submit', function(e) {
        e.preventDefault();
        const fileInput = $('#imageFile')[0];
        if (fileInput.files.length === 0) return;

        const file = fileInput.files[0];
        if (validTypes.indexOf(file.type) < 0) {
          $('#status').html('<div class="alert alert-danger">Invalid file type. Only PNG, JPG, JPEG allowed.</div>');
          return;
        }
        if (file.size > maxSize) {
          $('#status').html('<div class="alert alert-danger">File too large. Maximum size is 20MB.</div>');
          return;
        }

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