grthtrhthjhtyjytjytkergtrhtrjytjerhrfh<?php
/**
 * BrightBrains Sorbit Academy - Common API Configuration & Helpers
 */

// Error Reporting Config (Disable in production if you want silent errors, but helpful for setup)
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Session start for basic lightweight session fallback if required
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// CORS headers for flexible deployment integration
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// Handle OPTIONS preflight request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

/**
 * Helper to send standardized JSON response
 */
function sendJSON($data, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode($data);
    exit();
}

/**
 * Helper to get PHP raw input stream (parsed JSON)
 */
function getInputData() {
    $rawInput = file_get_contents('php://input');
    $decoded = json_decode($rawInput, true);
    return is_array($decoded) ? $decoded : [];
}

/**
 * Secure password hashing function matching node server
 */
function hashPassword($password) {
    return hash('sha256', $password . '_secure_quiz_salt_123!');
}

/**
 * Helper to add action details to the audit log
 */
function addAuditLog($pdo, $userId, $userName, $action, $details) {
    try {
        $stmt = $pdo->prepare("INSERT INTO logs (id, timestamp, userId, userName, action, details) VALUES (:id, :timestamp, :userId, :userName, :action, :details)");
        $stmt->execute([
            ':id' => 'log-' . uniqid() . '-' . bin2hex(random_bytes(4)),
            ':timestamp' => gmdate("Y-m-d\TH:i:s.000\Z"),
            ':userId' => $userId,
            ':userName' => $userName,
            ':action' => $action,
            ':details' => $details
        ]);
    } catch (Exception $e) {
        // Silently fail log write so api continues
    }
}

/**
 * Authenticate teacher based on Bearer token
 */
function authenticateTeacher($pdo) {
    $headers = apache_request_headers();
    $authHeader = isset($headers['Authorization']) ? $headers['Authorization'] : '';
    
    if (empty($authHeader) && isset($_SERVER['HTTP_AUTHORIZATION'])) {
        $authHeader = $_SERVER['HTTP_AUTHORIZATION'];
    }

    if (preg_match('/Bearer\s+(mock-teacher-token-[a-zA-Z0-9\-]+)/', $authHeader, $matches)) {
        $token = $matches[1];
        $teacherId = str_replace('mock-teacher-token-', '', $token);
        
        $stmt = $pdo->prepare("SELECT id, email, name FROM teachers WHERE id = :id");
        $stmt->execute([':id' => $teacherId]);
        $teacher = $stmt->fetch();
        
        if ($teacher) {
            return $teacher; // Authenticated
        }
    }
    
    sendJSON(['error' => 'Access denie