<?php
require_once 'token_encryption.php';

define('DB_HOST', 'localhost');
define('DB_USER', 'snaplimit_quiz4');
define('DB_PASS', 'snaplimit_quiz4');
define('DB_NAME', 'snaplimit_quiz4');

function getDbConnection() {
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        die(json_encode(['status' => 500, 'message' => 'Database connection failed']));
    }

    // ✅ Ensure proper emoji support
    $conn->set_charset("utf8mb4");

    return $conn;
}

function sendResponse($status, $message, $data = [], $new_session_token = null) {
    $response = [
        'status' => $status,
        'message' => $message
    ];
    if (!empty($data)) {
        $response['data'] = $data;
    }
    if ($new_session_token) {
        $response['new_session_token'] = $new_session_token;
    }
    
    // Convert response to JSON string
    $json_response = json_encode($response, JSON_UNESCAPED_UNICODE); // ✅ keep emojis
    
    // Encrypt the complete response body
    $encrypted_response = encryptToken($json_response);
    
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8'); // ✅ utf-8 header
    echo $encrypted_response;
    exit;
}

function validateInput($data, $required_fields) {
    foreach ($required_fields as $field) {
        if (!isset($data[$field]) || empty($data[$field])) {
            sendResponse(400, "Missing or empty field: $field");
        }
    }
}

// Function to decrypt request payload
function decryptRequestPayload($encrypted_payload) {
    try {
        $decrypted = decryptToken($encrypted_payload);
        $data = json_decode($decrypted, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            sendResponse(400, 'Invalid JSON in decrypted payload');
        }
        
        return $data;
    } catch (Exception $e) {
        sendResponse(400, 'Failed to decrypt request payload');
    }
}
?>