<?php
require_once '../config.php';
require_once '../middleware.php';
require_once '../new_app_config.php';

date_default_timezone_set('Asia/Kolkata');

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

### API Blueprint: /user/transfer_user_data
# POST /user/transfer_user_data
# Description: Transfers user data from current app to another app's database.
# Headers:
#   - Device-ID: <device_id> (required)
#   - Session-Token: <session_token> (required)
# Request Body:
#   - email: string (required)
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "User data transferred successfully",
#       "data": {
#         "transferred_coins": 1000,
#         "new_app_user_id": 5
#       },
#       "new_session_token": "new_strong_session_token_64_chars"
#     }
#   - 400: Invalid user_id, User data already transferred, User not found
#   - 401: Unauthorized
#   - 429: Too many requests
#   - 500: Database connection failed, Transfer failed

$device_id = $_SERVER['HTTP_DEVICE_ID'] ?? '';
$session_token = $_SERVER['HTTP_SESSION_TOKEN'] ?? '';

$method = $_SERVER['REQUEST_METHOD'];

if ($method !== 'POST') {
    sendResponse(405, 'Method not allowed');
}

// Get the encrypted payload
$encrypted_payload = file_get_contents('php://input');
if (empty($encrypted_payload)) {
    sendResponse(400, 'Empty request body');
}

// Decrypt the payload
$data = decryptRequestPayload($encrypted_payload);
if (!$data) {
    sendResponse(400, 'Invalid request body');
}

$email = $data['email'] ?? '';

if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    sendResponse(400, 'Invalid email');
}

$conn = getDbConnection();

try {
    // Get user data from current database by email
    $stmt = $conn->prepare("SELECT id, email, device_id, coins, refercode, referred_by, created_at, is_blocked FROM users WHERE email = ?");
    if (!$stmt) {
        sendResponse(500, 'Database query preparation failed: ' . $conn->error);
    }
    
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();
    $user_data = $result->fetch_assoc();
    $stmt->close();
    
    if (!$user_data) {
        sendResponse(400, 'User not found');
    }
    
    $user_id = (int) $user_data['id'];
    
    authenticateSession($user_id, $device_id, $session_token);
    rateLimit($user_id);
    $new_session_token = generateNewSessionToken($user_id, $device_id);
    
    // Store original coins before transfer
    $original_coins = (int) $user_data['coins'];

    // If coins are already zero, assume transfer already completed (fallback response)
    if ($original_coins <= 0) {
        $conn->close();
        sendResponse(200, 'User data already transferred', [
            'transferred_coins' => 0,
            'message' => 'Your coins in this app are already 0. It appears your data has already been transferred to the new app.'
        ], $new_session_token);
    }
    
    // Connect to new app database
    $new_app_conn = getNewAppDbConnection();
    
    // Check if user already exists in new app database (by email or device_id)
    $stmt_check = $new_app_conn->prepare("SELECT id FROM users WHERE email = ? OR device_id = ?");
    if (!$stmt_check) {
        $new_app_conn->close();
        sendResponse(500, 'New app database query preparation failed: ' . $new_app_conn->error);
    }
    
    $stmt_check->bind_param("ss", $user_data['email'], $user_data['device_id']);
    $stmt_check->execute();
    $result_check = $stmt_check->get_result();
    
    if ($result_check->num_rows > 0) {
        $existing_user = $result_check->fetch_assoc();
        $stmt_check->close();
        $new_app_conn->close();
        sendResponse(400, 'User data already exists in the new app. User ID: ' . $existing_user['id'], [], $new_session_token);
    }
    $stmt_check->close();
    
    // Start transaction on both databases
    $conn->begin_transaction();
    $new_app_conn->begin_transaction();
    
    try {
        // Insert user data into new app database
        $stmt_insert = $new_app_conn->prepare("INSERT INTO users (email, device_id, coins, refercode, referred_by, created_at, is_blocked) VALUES (?, ?, ?, ?, ?, ?, ?)");
        if (!$stmt_insert) {
            throw new Exception('New app database insert preparation failed: ' . $new_app_conn->error);
        }
        
        $stmt_insert->bind_param("ssisssi", 
            $user_data['email'],
            $user_data['device_id'],
            $user_data['coins'],
            $user_data['refercode'],
            $user_data['referred_by'],
            $user_data['created_at'],
            $user_data['is_blocked']
        );
        
        $stmt_insert->execute();
        
        if ($stmt_insert->affected_rows === 0) {
            throw new Exception('Failed to insert user data into new app database');
        }
        
        $new_app_user_id = $new_app_conn->insert_id;
        $stmt_insert->close();
        
        // Update coins to 0 in current database
        $stmt_update = $conn->prepare("UPDATE users SET coins = 0 WHERE id = ?");
        if (!$stmt_update) {
            throw new Exception('Current database update preparation failed: ' . $conn->error);
        }
        
        $stmt_update->bind_param("i", $user_id);
        $stmt_update->execute();
        
        if ($stmt_update->affected_rows === 0) {
            throw new Exception('Failed to update coins in current database');
        }
        $stmt_update->close();
        
        // Commit both transactions
        $conn->commit();
        $new_app_conn->commit();
        
        // Close connections
        $new_app_conn->close();
        $conn->close();
        
        sendResponse(200, 'User data transferred successfully', [
            'transferred_coins' => $original_coins,
            'new_app_user_id' => $new_app_user_id,
            'message' => 'Your data has been successfully transferred to the new app. Your coins in this app have been reset to 0.'
        ], $new_session_token);
        
    } catch (Exception $e) {
        // Rollback both transactions on error
        $conn->rollback();
        $new_app_conn->rollback();
        $new_app_conn->close();
        $conn->close();
        sendResponse(500, 'Transfer failed: ' . $e->getMessage());
    }
    
} catch (Exception $e) {
    $conn->close();
    sendResponse(500, 'Database operation failed: ' . $e->getMessage());
}
?>

