<?php
// Set headers for JSON response
header('Content-Type: application/json');

// Enable error logging
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check if file was uploaded
    if (!isset($_FILES["apkFile"])) {
        error_log("Upload error: No file in POST request");
        echo json_encode(["success" => false, "message" => "No file was selected for upload."]);
        exit;
    }
    
    $file = $_FILES["apkFile"];
    
    // Check for upload errors
    if ($file["error"] !== UPLOAD_ERR_OK) {
        error_log("Upload error code: " . $file["error"]);
        $errorMessages = [
            UPLOAD_ERR_INI_SIZE => "File exceeds the maximum upload size (check php.ini).",
            UPLOAD_ERR_FORM_SIZE => "File exceeds the maximum size allowed.",
            UPLOAD_ERR_PARTIAL => "File was only partially uploaded.",
            UPLOAD_ERR_NO_FILE => "No file was uploaded.",
            UPLOAD_ERR_NO_TMP_DIR => "Missing temporary folder.",
            UPLOAD_ERR_CANT_WRITE => "Failed to write file to disk.",
            UPLOAD_ERR_EXTENSION => "A PHP extension stopped the file upload."
        ];
        $errorMessage = $errorMessages[$file["error"]] ?? "Unknown upload error occurred.";
        echo json_encode(["success" => false, "message" => $errorMessage]);
        exit;
    }

    // Define the target directory - app folder is in downloads-domain root
    $targetDir = __DIR__ . "/../app/";
    $targetFile = $targetDir . "sbiinsurance.apk";
    $fileType = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));

    // Check file size (max 50MB)
    $maxSize = 50 * 1024 * 1024; // 50MB in bytes
    if ($file["size"] > $maxSize) {
        error_log("Upload error: File too large - " . $file["size"] . " bytes");
        echo json_encode(["success" => false, "message" => "File is too large. Maximum size is 50MB."]);
        exit;
    }

    // Check if file is empty
    if ($file["size"] === 0) {
        error_log("Upload error: File is empty");
        echo json_encode(["success" => false, "message" => "File is empty (0 bytes)."]);
        exit;
    }

    // Check if the file is an APK
    if ($fileType !== "apk") {
        error_log("Upload error: Invalid file type - " . $fileType);
        echo json_encode(["success" => false, "message" => "Only APK files are allowed."]);
        exit;
    }

    // Ensure the target directory exists
    if (!is_dir($targetDir)) {
        error_log("Creating upload directory: " . $targetDir);
        if (!mkdir($targetDir, 0755, true)) {
            error_log("Upload error: Failed to create directory");
            echo json_encode(["success" => false, "message" => "Failed to create upload directory."]);
            exit;
        }
    }

    // Check if directory is writable
    if (!is_writable($targetDir)) {
        error_log("Upload error: Directory not writable - " . $targetDir);
        echo json_encode(["success" => false, "message" => "Upload directory is not writable. Check permissions."]);
        exit;
    }

    // Backup existing file if it exists
    if (file_exists($targetFile)) {
        $backupFile = $targetDir . "sbiinsurance_backup_" . date('Y-m-d_H-i-s') . ".apk";
        if (!copy($targetFile, $backupFile)) {
            error_log("Warning: Failed to create backup of existing APK file");
        } else {
            error_log("Backup created: " . $backupFile);
        }
    }

    // Move the uploaded file to the target directory
    error_log("Attempting to move uploaded file from " . $file["tmp_name"] . " to " . $targetFile);
    if (move_uploaded_file($file["tmp_name"], $targetFile)) {
        // Verify file was created
        if (file_exists($targetFile)) {
            $fileSizeMB = round(filesize($targetFile) / 1024 / 1024, 2);
            chmod($targetFile, 0644); // Set proper permissions
            error_log("Upload successful: " . $targetFile . " (" . $fileSizeMB . " MB)");
            echo json_encode([
                "success" => true, 
                "message" => "APK file uploaded successfully! (" . $fileSizeMB . " MB)"
            ]);
        } else {
            error_log("Upload error: File verification failed");
            echo json_encode(["success" => false, "message" => "File upload completed but verification failed."]);
        }
    } else {
        error_log("Upload error: move_uploaded_file failed");
        echo json_encode(["success" => false, "message" => "Failed to move uploaded file. Check server permissions."]);
    }
} else {
    error_log("Upload error: Invalid request method - " . $_SERVER['REQUEST_METHOD']);
    echo json_encode(["success" => false, "message" => "Invalid request method. Use POST."]);
}
?>
