<?php
// ============================================
// دوال المصادقة والصلاحيات - AUTO TESTER
// المسار: /api/config/auth.php
// ============================================

function verifyToken($token, $pdo) {
    try {
        $stmt = $pdo->prepare("
            SELECT s.user_id, s.expires_at, u.id, u.full_name, u.email, u.phone, u.role, u.user_type, 
                   u.status, u.area, u.assigned_region, u.center
            FROM admin_sessions s
            JOIN users u ON s.user_id = u.id
            WHERE s.token = ? AND u.status = 'active'
        ");
        $stmt->execute([$token]);
        $user = $stmt->fetch();
        
        if ($user) {
            $expiresAt = strtotime($user['expires_at']);
            $now = time();
            
            if ($expiresAt > $now) {
                return $user;
            } else {
                $stmt = $pdo->prepare("DELETE FROM admin_sessions WHERE token = ?");
                $stmt->execute([$token]);
                return null;
            }
        }
        return null;
    } catch (Exception $e) {
        error_log('verifyToken error: ' . $e->getMessage());
        return null;
    }
}

function checkPermission($user, $requiredRole) {
    if (!$user) return false;
    if (is_array($requiredRole)) {
        return in_array($user['role'], $requiredRole) || in_array($user['user_type'], $requiredRole);
    }
    return $user['role'] === $requiredRole || $user['user_type'] === $requiredRole;
}

function checkRegionAccess($user, $targetRegion) {
    if (checkPermission($user, 'admin')) return true;
    if (checkPermission($user, 'supervisor')) {
        return $user['assigned_region'] === $targetRegion;
    }
    return false;
}

function logActivity($pdo, $userId, $action, $details = null) {
    try {
        $stmt = $pdo->prepare("
            INSERT INTO activity_log (user_id, action, details, ip_address, user_agent, created_at)
            VALUES (?, ?, ?, ?, ?, NOW())
        ");
        $stmt->execute([
            $userId, 
            $action, 
            $details, 
            $_SERVER['REMOTE_ADDR'] ?? null,
            $_SERVER['HTTP_USER_AGENT'] ?? null
        ]);
    } catch (Exception $e) {
        error_log('Failed to log activity: ' . $e->getMessage());
    }
}

function generateCsrfToken() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

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