<?php

namespace App\Services;

use Smalot\PdfParser\Parser;

class PdfExtractorService
{
    public static function extract($filePath)
    {
        try {
            $parser = new Parser();
            $pdf = $parser->parseFile($filePath);

            $pages = $pdf->getPages();
            $text = '';

            foreach ($pages as $page) {
                $pageText = $page->getText();

                // Remove page numbers (common patterns)
                $pageText = preg_replace('/^\s*\d+\s*$|^\s*-\s*\d+\s*-\s*$|^\s*Page\s+\d+\s*$/im', '', $pageText);

                // Remove headers/footers (lines with less than 10 chars at start/end)
                $lines = explode("\n", $pageText);
                $filtered = [];
                
                foreach ($lines as $line) {
                    $trimmed = trim($line);
                    // Skip very short lines that look like page markers
                    if (strlen($trimmed) > 3 && !preg_match('/^\d+$/', $trimmed)) {
                        $filtered[] = $trimmed;
                    }
                }

                $text .= implode("\n", $filtered) . "\n\n";
            }

            // Clean up excessive whitespace
            $text = preg_replace('/\n{3,}/', "\n\n", $text);
            $text = trim($text);

            // Convert to HTML paragraphs
            $paragraphs = array_filter(explode("\n\n", $text));
            $html = '';

            foreach ($paragraphs as $para) {
                $para = trim($para);
                if (!empty($para)) {
                    // Check if it looks like a heading (short line, all caps, or ends with colon)
                    if (strlen($para) < 60 && (strtoupper($para) === $para || preg_match('/:$/', $para))) {
                        $html .= "<h2>" . htmlspecialchars($para) . "</h2>\n";
                    } else {
                        $html .= "<p>" . htmlspecialchars($para) . "</p>\n";
                    }
                }
            }

            return [
                'success' => true,
                'data' => [
                    'content' => $html,
                    'pages' => count($pages),
                    'words' => str_word_count(strip_tags($text)),
                ],
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'PDF işleme hatası: ' . $e->getMessage(),
            ];
        }
    }
}
