<?php require './ZZ_logintest.php'; ?>
<?php
// Specify the directory where uploaded zip files will be saved
$uploadDir = '/home/relayup/dev/sysupdate/';

// Get admin password from POST parameter
$adminPassword = $_POST['adminPassword'] ?? '';

$response = [
    'status' => 'success',
    'message' => 'Files uploaded successfully',
    'files' => []
];

// Function to get error message
function getErrorMessage($errorCode) {
    switch ($errorCode) {
        case UPLOAD_ERR_INI_SIZE:
            return "The uploaded file exceeds the upload_max_filesize directive in php.ini";
        case UPLOAD_ERR_FORM_SIZE:
            return "The uploaded file exceeds the MAX_FILE_SIZE directive specified in the HTML form";
        case UPLOAD_ERR_PARTIAL:
            return "The uploaded file was only partially uploaded";
        case UPLOAD_ERR_NO_FILE:
            return "No file was uploaded";
        case UPLOAD_ERR_NO_TMP_DIR:
            return "Missing a temporary folder";
        case UPLOAD_ERR_CANT_WRITE:
            return "Failed to write file to disk";
        case UPLOAD_ERR_EXTENSION:
            return "A PHP extension stopped the file upload";
        default:
            return "Unknown upload error";
    }
}

if (!isset($_FILES['file1'])) {
    $response['status'] = 'error';
    $response['message'] = "Something went wrong. No file was uploaded";
    header('Content-Type: application/json');
    die(json_encode($response));
}

// Loop through the uploaded files
for ($i = 1; $i <= 4; $i++) {
    $fileKey = "file$i";
    if(isset($_FILES[$fileKey])) {
        $file = $_FILES[$fileKey];
        // echo $file;
        
        // Get file details
        $fileName = $file['name'];
        $fileTmpName = $file['tmp_name'];
        $fileSize = $file['size'];
        $fileError = $file['error'];
        
        // Check for upload errors first
        if ($fileError !== UPLOAD_ERR_OK) {
            $response['status'] = 'error';
            $response['message'] = "Error uploading file $i: " . getErrorMessage($fileError);
            break;
        }
        
        // Check if the file is a zip
        $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        if ($fileExt != 'zip') {
            $response['status'] = 'error';
            $response['message'] = "File $i is not a ZIP file";
            break;
        } else {
            // Generate a unique filename to prevent overwriting
            $fileNewName = $fileName;
            
            if (!file_exists($uploadDir)) {
                if (!mkdir($uploadDir, 0777, true)) {
                    die(json_encode(['status' => 'error', 'message' => "Failed to create upload directory: $uploadDir"]));
                }
            }
            
            // Specify the full path where the file will be saved
            $destination = $uploadDir . $fileNewName;
            // echo $destination;
            
            // Move the file from temporary location to desired destination
            if(move_uploaded_file($fileTmpName, $destination)) {
                // Verify the file was actually saved
                if (!file_exists($destination)) {
                    $response['status'] = 'error';
                    $response['message'] = "File $i was moved but not found at destination";
                    break;
                }
                
                $response['files'][] = [
                    'original_name' => $fileName,
                    'new_name' => $fileNewName,
                    'path' => $destination
                ];
            } else {
                $response['status'] = 'error';
                $response['message'] = "Failed to move uploaded file $i";
                break;
            }
        }
    }
}


// Create config file with admin password


if ($response['status'] === 'success') {
    $configContent = "01_user_password=" . $adminPassword;
    $configFile = $uploadDir . 'default.cfg';

    // Ensure the upload directory exists and write config file
    if (!file_exists($uploadDir)) {
        if (!mkdir($uploadDir, 0777, true)) {
            die(json_encode(['status' => 'error', 'message' => "Failed to create upload directory: $uploadDir"]));
        }
    }

    // Write the config file
    if (!file_put_contents($configFile, $configContent)) {
        die(json_encode(['status' => 'error', 'message' => "Failed to write configuration file"]));
    }
    http_response_code(200);
} else {
    http_response_code(400);
}

// Send JSON response
header('Content-Type: application/json');
echo json_encode($response);
?>

