<?php
/**
 * Session Manager
 * Handles session initialization and authentication
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

class SessionManager {
    
    public static function getUserId() {
        return $_SESSION['user_id'] ?? null;
    }
    
    public static function isAuthenticated() {
        return !empty($_SESSION['user_id']);
    }
    
    public static function setUser($userId, $token = null) {
        $_SESSION['user_id'] = $userId;
        $_SESSION['token'] = $token ?? bin2hex(random_bytes(32));
        $_SESSION['login_time'] = time();
    }
    
    public static function logout() {
        session_destroy();
        return true;
    }
    
    public static function requireAuth() {
        if (!self::isAuthenticated()) {
            http_response_code(401);
            echo json_encode(['error' => 'Unauthorized']);
            exit;
        }
    }
}

/**
 * Response Helper
 */
class ResponseHelper {
    
    public static function json($data, $statusCode = 200) {
        http_response_code($statusCode);
        header('Content-Type: application/json');
        header('Access-Control-Allow-Origin: *');
        echo json_encode($data);
        exit;
    }
    
    public static function success($message, $data = [], $statusCode = 200) {
        return self::json(array_merge([
            'success' => true,
            'message' => $message
        ], $data), $statusCode);
    }
    
    public static function error($message, $statusCode = 400) {
        return self::json([
            'success' => false,
            'error' => $message
        ], $statusCode);
    }
}

/**
 * Input Validator
 */
class InputValidator {
    
    public static function required($data, $fields) {
        foreach ((array)$fields as $field) {
            if (empty($data[$field])) {
                ResponseHelper::error("Missing required field: {$field}", 400);
            }
        }
        return true;
    }
    
    public static function email($email) {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            ResponseHelper::error("Invalid email format", 400);
        }
        return true;
    }
}
?>
