<?php
// Utility functions
date_default_timezone_set('UTC');

function debugLog($message) {
    $logFile = __DIR__ . '/../debug_auth.txt';
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}

function generateUUID() {
    $data = random_bytes(16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10

    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

function createSession($userId) {
    global $pdo;
    
    $sessionId = generateUUID();
    $sessionToken = bin2hex(random_bytes(32));
    $expiresAt = date('Y-m-d H:i:s', strtotime('+24 hours'));
    
    try {
        $stmt = $pdo->prepare("INSERT INTO sessions (id, user_id, session_token, expires_at) VALUES (?, ?, ?, ?)");
        $stmt->execute([$sessionId, $userId, $sessionToken, $expiresAt]);
        return $sessionToken;
    } catch (Exception $e) {
        debugLog("Session creation failed: " . $e->getMessage());
        throw $e;
    }
}

function jsonResponse($data, $statusCode = 200) {
    http_response_code($statusCode);
    header('Content-Type: application/json');
    echo json_encode($data);
    exit();
}

function getJsonInput() {
    return json_decode(file_get_contents('php://input'), true);
}

function errorResponse($message, $statusCode = 500) {
    http_response_code($statusCode);
    header('Content-Type: application/json');
    echo json_encode(['error' => $message]);
    exit();
}

function validateApiKey($apiKey) {
    // In a real implementation, you would validate the API key against the database
    // For now, we'll just check if it's not empty
    return !empty($apiKey);
}

function validateInput($data, $requiredFields, $statusCode = 400) {
    if (!$data || !is_array($data)) {
        errorResponse('Invalid request payload', $statusCode);
    }
    $missing = [];
    foreach ($requiredFields as $field) {
        if (!isset($data[$field]) || (is_string($data[$field]) && trim($data[$field]) === '')) {
            $missing[] = $field;
        }
    }
    
    if (!empty($missing)) {
        errorResponse('Missing required fields: ' . implode(', ', $missing), $statusCode);
    }
}

/**
 * Centralized email helper
 */
function sendEmail($to, $subject, $body, $headers = []) {
    if (function_exists('sendRobustEmail')) {
        $res = sendRobustEmail($to, $subject, $body);
        return $res['success'];
    } else {
        // Enforce the standard: Do not allow fallback to basic mail() in production-ready code
        error_log("CRITICAL ERROR: sendRobustEmail not found. Core email logic missing.");
        return false;
    }
}

function getUserFromToken($token) {
    global $pdo;
    
    try {
        $stmt = $pdo->prepare("
            SELECT u.*, r.name as role, p.role_id 
            FROM sessions s
            JOIN users u ON s.user_id = u.id
            LEFT JOIN profiles p ON u.id = p.user_id
            LEFT JOIN user_roles r ON p.role_id = r.id
            WHERE s.session_token = ? AND s.expires_at > datetime('now')
            LIMIT 1
        ");
        $stmt->execute([$token]);
        $user = $stmt->fetch();
        
        return $user;
    } catch (Exception $e) {
        debugLog("getUserFromToken exception: " . $e->getMessage());
        return null;
    }
}

function isAdmin($userId) {
    global $pdo;
    
    try {
        $stmt = $pdo->prepare("
            SELECT r.name 
            FROM profiles p 
            JOIN user_roles r ON p.role_id = r.id 
            WHERE p.user_id = ?
        ");
        $stmt->execute([$userId]);
        $role = $stmt->fetch();
        return $role && strtolower($role['name']) === 'admin';
    } catch (Exception $e) {
        return false;
    }
}

function generateLicenseKey() {
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $result = '';
    
    for ($i = 1; $i <= 20; $i++) {
        $result .= $chars[rand(0, strlen($chars) - 1)];
        if ($i % 4 == 0 && $i < 20) {
            $result .= '-';
        }
    }
    
    return $result;
}

function getAuthToken() {
    $headers = getallheaders();
    $authHeader = isset($headers['Authorization']) ? $headers['Authorization'] : '';
    
    if (empty($authHeader)) {
        foreach ($headers as $key => $value) {
            if (strtolower($key) === 'authorization') {
                $authHeader = $value;
                break;
            }
        }
    }
    
    return str_replace('Bearer ', '', $authHeader);
}
?>