<?hh // strict

namespace App\Services;

class AccessibilityService
{
    /**
     * Check if HTML content meets Section 508/WCAG 2.1 AA compliance
     */
    public function validateHtmlAccessibility(string $html): array
    {
        $errors = [];
        
        // Check for proper heading hierarchy
        $headings = [];
        preg_match_all('/<h([1-6])[^>]*>.*?<\/h[1-6]>/i', $html, $matches);
        if (!empty($matches[0])) {
            foreach ($matches[0] as $index => $heading) {
                $level = (int)$matches[1][$index];
                $headings[] = $level;
            }
            
            // Ensure heading levels don't skip (e.g., h1 to h3 without h2)
            for ($i = 1; $i < count($headings); $i++) {
                if ($headings[$i] > $headings[$i-1] + 1) {
                    $errors[] = "Heading level skipped from h{$headings[$i-1]} to h{$headings[$i]}";
                }
            }
        }
        
        // Check for alt attributes on images
        preg_match_all('/<img[^>]*>/i', $html, $imgMatches);
        foreach ($imgMatches[0] as $img) {
            if (strpos($img, 'alt=') === false) {
                $errors[] = "Image without alt attribute: {$img}";
            } else {
                // Check if alt is empty
                if (preg_match('/alt=["\']["\']/', $img)) {
                    $errors[] = "Image with empty alt attribute: {$img}";
                }
            }
        }
        
        // Check for form labels
        preg_match_all('/<input[^>]*name=["\']([^"\']*)["\'][^>]*>/i', $html, $inputMatches);
        foreach ($inputMatches[1] as $inputName) {
            if (strpos($html, 'label') !== false) {
                if (!preg_match('/<label[^>]*for=["\']' . preg_quote($inputName, '/') . '["\'][^>]*>.*?<\/label>/i', $html) &&
                    !preg_match('/<label[^>]*>.*?<input[^>]*name=["\']' . preg_quote($inputName, '/') . '["\'][^>]*>.*?<\/label>/i', $html)) {
                    $errors[] = "Input field with name '{$inputName}' missing associated label";
                }
            }
        }
        
        // Check for sufficient color contrast (simplified check)
        preg_match_all('/style=["\'].*?color:\s*([^;]*);.*?background-color:\s*([^;]*);/i', $html, $styleMatches);
        foreach ($styleMatches[0] as $index => $style) {
            $textColor = $styleMatches[1][$index];
            $bgColor = $styleMatches[2][$index];
            if (!$this->hasSufficientContrast($textColor, $bgColor)) {
                $errors[] = "Insufficient color contrast between text '{$textColor}' and background '{$bgColor}'";
            }
        }
        
        return $errors;
    }
    
    /**
     * Generate accessible HTML from basic content
     */
    public function generateAccessibleHtml(array $content): string
    {
        $html = '<div class="accessible-content">';
        
        if (isset($content['title'])) {
            $html .= '<h1>' . htmlspecialchars($content['title']) . '</h1>';
        }
        
        if (isset($content['description'])) {
            $html .= '<p>' . htmlspecialchars($content['description']) . '</p>';
        }
        
        if (isset($content['items']) && is_array($content['items'])) {
            $html .= '<ul aria-label="Content items">';
            foreach ($content['items'] as $item) {
                $html .= '<li>' . htmlspecialchars($item) . '</li>';
            }
            $html .= '</ul>';
        }
        
        $html .= '</div>';
        
        return $html;
    }
    
    /**
     * Check if two colors have sufficient contrast for accessibility
     */
    private function hasSufficientContrast(string $color1, string $color2): bool
    {
        // Simplified contrast check - in a real app, you'd implement the full WCAG algorithm
        return true; // Placeholder implementation
    }
    
    /**
     * Generate accessibility statement
     */
    public function generateAccessibilityStatement(): string
    {
        return "
        <h2>Accessibility Statement</h2>
        <p>MerchantsOfHope.org is committed to ensuring digital accessibility for people with disabilities.</p>
        <p>We are continually improving the user experience for everyone and applying the relevant accessibility standards.</p>
        <h3>Conformance</h3>
        <p>The Web Content Accessibility Guidelines (WCAG) defines requirements for designers and developers to improve accessibility for people with disabilities.</p>
        <p>We are conforming to level AA of WCAG 2.1.</p>
        <h3>Feedback</h3>
        <p>We welcome your feedback on the accessibility of this website. Please contact us if you encounter accessibility barriers.</p>
        ";
    }
}