<?php
/**
 * Session Management System
 * Handles authentication, session validation, and user management
 * Integrated with existing business-based authentication
 */

// Session configuration (must be set before session_start())
if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.cookie_httponly', 1);
    ini_set('session.cookie_secure', isset($_SERVER['HTTPS']));
    ini_set('session.use_strict_mode', 1);
    ini_set('session.cookie_samesite', 'Strict');
    
    // Start session
    session_start();
}

// Session timeout (24 hours)
define('SESSION_TIMEOUT', 24 * 60 * 60);

/**
 * Check if user is authenticated (business-based)
 */
function isAuthenticated() {
    if (!isset($_SESSION['business_id']) || !isset($_SESSION['business_name'])) {
        return false;
    }
    
    // Check if login time is set (for session timeout)
    if (isset($_SESSION['login_time'])) {
        if (time() - $_SESSION['login_time'] > SESSION_TIMEOUT) {
            destroySession();
            return false;
        }
    }
    
    // Update last activity
    $_SESSION['last_activity'] = time();
    return true;
}

/**
 * Authenticate business user and create session
 */
function authenticateBusiness($business_id, $business_name, $role = 'admin') {
    $_SESSION['business_id'] = $business_id;
    $_SESSION['business_name'] = $business_name;
    $_SESSION['role'] = $role;
    $_SESSION['login_time'] = time();
    $_SESSION['last_activity'] = time();
    $_SESSION['session_id'] = session_id();
    
    // Regenerate session ID for security
    session_regenerate_id(true);
}

/**
 * Destroy current session
 */
function destroySession() {
    // Clear all session variables
    $_SESSION = array();
    
    // Destroy session cookie
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params["path"], $params["domain"],
            $params["secure"], $params["httponly"]
        );
    }
    
    // Destroy session
    session_destroy();
}

/**
 * Get current business user information
 */
function getCurrentBusiness() {
    if (!isAuthenticated()) {
        return null;
    }
    
    return [
        'business_id' => $_SESSION['business_id'],
        'business_name' => $_SESSION['business_name'],
        'role' => $_SESSION['role'] ?? 'admin',
        'login_time' => $_SESSION['login_time'] ?? time(),
        'last_activity' => $_SESSION['last_activity'] ?? time()
    ];
}

/**
 * Require authentication - redirect to login if not authenticated
 */
function requireAuth() {
    if (!isAuthenticated()) {
        if (isApiRequest()) {
            http_response_code(401);
            header('Content-Type: application/json');
            echo json_encode([
                'status' => false,
                'message' => 'Authentication required',
                'code' => 'AUTH_REQUIRED'
            ]);
            exit;
        } else {
            // Redirect to login page
            header('Location: ' . BASE_URL . '/public/login.php');
            exit;
        }
    }
}

/**
 * Check if current request is an API request
 */
function isApiRequest() {
    $path = $_SERVER['REQUEST_URI'] ?? '';
    return strpos($path, '/src/api/') !== false || 
           (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false);
}

/**
 * Validate API token from Authorization header
 */
function validateApiToken() {
    $headers = getallheaders();
    $auth_header = $headers['Authorization'] ?? '';
    
        // Accept both "Bearer <token>" and "<token>"
       if (preg_match('/Bearer\s+(.*)$/i', $auth_header, $matches)) {
           $token = $matches[1];
       } else {
          // No Bearer prefix — assume raw token
           $token = trim($auth_header);
       }
       if (!$token) {
           return false;
       }

    
    $token = $matches[1];
    
    // Simple token validation (in production, use proper JWT)
    try {
        $payload = json_decode(base64_decode($token), true);
        if (!$payload || !isset($payload['business_id']) || !isset($payload['exp'])) {
            return false;
        }
        
        // Check if token is expired
        if ($payload['exp'] < time()) {
            return false;
        }
        
        // Set session data from token
        $_SESSION['business_id'] = (int)$payload['business_id'];
        $_SESSION['business_name'] = $payload['business_name'] ?? 'api_business';
        $_SESSION['role'] = $payload['role'] ?? 'admin';
        $_SESSION['login_time'] = $payload['iat'] ?? time();
        $_SESSION['last_activity'] = time();
        
        return $payload['business_id'];
    } catch (Exception $e) {
        return false;
    }
}

/**
 * Generate API token
 */
function generateApiToken($business_id, $business_name = 'api_business', $role = 'admin') {
    $payload = [
        'business_id' => $business_id,
        'business_name' => $business_name,
        'role' => $role,
        'exp' => time() + SESSION_TIMEOUT,
        'iat' => time()
    ];
    return base64_encode(json_encode($payload));
}

/**
 * Check if business user has required role
 */
function hasRole($required_role) {
    if (!isAuthenticated()) {
        return false;
    }
    
    $user_role = $_SESSION['role'] ?? 'admin';
    
    // Admin has access to everything
    if ($user_role === 'admin') {
        return true;
    }
    
    return $user_role === $required_role;
}

/**
 * Require specific role
 */
function requireRole($required_role) {
    requireAuth();
    
    if (!hasRole($required_role)) {
        if (isApiRequest()) {
            http_response_code(403);
            header('Content-Type: application/json');
            echo json_encode([
                'status' => false,
                'message' => 'Insufficient permissions',
                'code' => 'INSUFFICIENT_PERMISSIONS'
            ]);
            exit;
        } else {
            header('HTTP/1.1 403 Forbidden');
            echo '<h1>403 - Access Denied</h1>';
            exit;
        }
    }
}

/**
 * Log business user activity
 */
function logActivity($action, $details = '') {
    if (!isAuthenticated()) {
        return;
    }
    
    $business_id = $_SESSION['business_id'];
    $business_name = $_SESSION['business_name'];
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
    
    // In a real application, you would log this to a database
    error_log("Activity: Business $business_name ($business_id) performed $action from $ip - $details");
}

/**
 * CSRF Protection
 */
function generateCSRFToken() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function validateCSRFToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

/**
 * Rate limiting (simple implementation)
 */
function checkRateLimit($action, $limit = 60, $window = 3600) {
    $key = "rate_limit_{$action}_" . ($_SERVER['REMOTE_ADDR'] ?? 'unknown');
    
    if (!isset($_SESSION[$key])) {
        $_SESSION[$key] = ['count' => 0, 'window_start' => time()];
    }
    
    $rate_data = $_SESSION[$key];
    
    // Reset if window has passed
    if (time() - $rate_data['window_start'] > $window) {
        $_SESSION[$key] = ['count' => 1, 'window_start' => time()];
        return true;
    }
    
    // Check if limit exceeded
    if ($rate_data['count'] >= $limit) {
        return false;
    }
    
    // Increment counter
    $_SESSION[$key]['count']++;
    return true;
}

/**
 * Security headers
 */
function setSecurityHeaders() {
    header('X-Content-Type-Options: nosniff');
    header('X-Frame-Options: DENY');
    header('X-XSS-Protection: 1; mode=block');
    header('Referrer-Policy: strict-origin-when-cross-origin');
    
    if (isset($_SERVER['HTTPS'])) {
        header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
    }
}

// Set security headers for all requests
setSecurityHeaders();
?>
