<?php
// Simple Cloud Save System for NEONJA
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit;
}

$action = isset($_GET['action']) ? $_GET['action'] : '';
$email = isset($_GET['email']) ? strtolower(trim($_GET['email'])) : '';

if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid or missing email"]);
    exit;
}

$emailHash = hash('sha256', $email);
$saveDir = __DIR__ . '/saves';
$saveFile = $saveDir . '/' . $emailHash . '.json';

// Ensure saves directory exists
if (!is_dir($saveDir)) {
    @mkdir($saveDir, 0755, true);
}

if ($action === 'save') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(["error" => "Method Not Allowed. Use POST for saving."]);
        exit;
    }
    
    $jsonData = file_get_contents('php://input');
    // Validate that it's valid JSON
    $decoded = json_decode($jsonData, true);
    if ($decoded === null) {
        http_response_code(400);
        echo json_encode(["error" => "Invalid JSON data"]);
        exit;
    }
    
    // Write data securely
    $success = @file_put_contents($saveFile, $jsonData);
    if ($success === false) {
        http_response_code(500);
        echo json_encode(["error" => "Failed to write save file on server"]);
    } else {
        echo json_encode(["success" => true, "message" => "Profile saved successfully"]);
    }
} elseif ($action === 'load') {
    if (!file_exists($saveFile)) {
        http_response_code(404);
        echo json_encode(["error" => "Save file not found", "new_user" => true]);
        exit;
    }
    
    $data = @file_get_contents($saveFile);
    if ($data === false) {
        http_response_code(500);
        echo json_encode(["error" => "Failed to read save file"]);
    } else {
        echo $data;
    }
} else {
    http_response_code(400);
    echo json_encode(["error" => "Invalid action"]);
}
