<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');

$uploadDir = __DIR__ . '/uploads/';
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

if (empty($_FILES) || !isset($_FILES['apk_file'])) {
    echo json_encode([
        "success" => false,
        "message" => "❌ Upload failed: No file received!",
        "details" => [
            "POST" => $_POST,
            "FILES" => $_FILES,
            "upload_max_filesize" => ini_get('upload_max_filesize'),
            "post_max_size" => ini_get('post_max_size'),
            "upload_tmp_dir" => ini_get('upload_tmp_dir')
        ]
    ]);
    exit;
}

$file = $_FILES['apk_file'];

$allowedTypes = ['application/vnd.android.package-archive', 'application/octet-stream'];
$maxSize = 100 * 1024 * 1024; 

if ($file['error'] !== UPLOAD_ERR_OK) {
    echo json_encode([
        "success" => false,
        "message" => "❌ Upload error code: " . $file['error'],
        "details" => $file
    ]);
    exit;
}

if ($file['size'] > $maxSize) {
    echo json_encode([
        "success" => false,
        "message" => "❌ File too large! (" . round($file['size'] / 1024 / 1024, 2) . " MB)",
        "limit" => "100 MB"
    ]);
    exit;
}

$filename = basename($file['name']);
$targetPath = $uploadDir . $filename;

if (move_uploaded_file($file['tmp_name'], $targetPath)) {
    echo json_encode([
        "success" => true,
        "message" => "✅ Upload successful!",
        "filename" => $filename,
        "path" => "uploads/$filename",
        "size" => round($file['size'] / 1024 / 1024, 2) . " MB"
    ]);
} else {
    echo json_encode([
        "success" => false,
        "message" => "❌ Failed to move uploaded file. Check folder permission!",
        "target" => $targetPath,
        "is_writable" => is_writable($uploadDir)
    ]);
}
exit;
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>APK Upload (Debug Mode)</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body { background:#f9fafb; }
    .progress { height:25px; }
  </style>
</head>
<body class="p-5">
  <div class="container">
    <h3 class="mb-4">📱 APK Upload Debug Panel</h3>
    <input type="file" id="apkFile" class="form-control mb-3" accept=".apk">
    <div class="progress mb-3">
      <div id="progressBar" class="progress-bar progress-bar-striped bg-success" style="width:0%">0%</div>
    </div>
    <pre id="debug" class="bg-light p-3 border rounded"></pre>
  </div>

  <script>
    const fileInput = document.getElementById('apkFile');
    const progressBar = document.getElementById('progressBar');
    const debug = document.getElementById('debug');

    fileInput.addEventListener('change', () => {
      const file = fileInput.files[0];
      if (!file) return;

      const formData = new FormData();
      formData.append('apk_file', file);

      const xhr = new XMLHttpRequest();
      xhr.open('POST', 'app_upload.php', true);

      xhr.upload.addEventListener('progress', (e) => {
        if (e.lengthComputable) {
          const percent = Math.round((e.loaded / e.total) * 100);
          progressBar.style.width = percent + '%';
          progressBar.textContent = percent + '%';
        }
      });

      xhr.onload = () => {
        try {
          const res = JSON.parse(xhr.responseText);
          debug.textContent = JSON.stringify(res, null, 2);
          if (res.success) {
            alert("✅ Upload Success!");
          } else {
            alert("❌ Upload Failed!");
          }
        } catch (err) {
          debug.textContent = "⚠️ Invalid JSON response:\n" + xhr.responseText;
        }
      };

      xhr.onerror = () => {
        alert("❌ Network Error");
      };

      xhr.send(formData);
    });
  </script>
</body>
</html>