<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Initialize variables
$text = $_POST['text'] ?? $_SESSION['text'] ?? '';
$formatted = '';
$format = $_POST['format'] ?? '';
$template = $_POST['template'] ?? '';
$mode = $_POST['mode'] ?? 'html'; // HTML or Markdown mode
$fontSize = $_POST['fontSize'] ?? '16px';
$theme = $_POST['theme'] ?? 'light';

// Save text in session for persistence
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $_SESSION['text'] = $text;
}

// Enhanced templates with more options
$templates = [
    'blog-post' => [
        'title' => 'Blog Post',
        'icon' => 'fa-blog',
        'content' => <<<EOT
# [Your Engaging Title Here]

![Featured Image](https://source.unsplash.com/random/1200x600/?relevant)

## Introduction
Hook your readers with an engaging opening paragraph that introduces your topic and why it matters.

## The Problem
Describe the challenge or issue you're addressing. Use concrete examples and data when possible.

## The Solution
Present your main arguments or solutions. Break this into subsections if needed.

### Key Points
- First major point with supporting evidence
- Second major point with real-world examples
- Third major point with actionable insights

## How to Implement
1. Step-by-step instructions
2. Practical tips
3. Common pitfalls to avoid

## Case Study
Share a real example or case study that illustrates your points.

## Expert Insights
> "Add a relevant quote from an industry expert here" - Expert Name

## Conclusion
Wrap up your main points and provide a call to action.

---
*Author: [Your Name]*
*Published: [Date]*
*Tags: #topic1 #topic2 #topic3*

[Edit: Remember to replace placeholder text and add relevant images]
EOT
    ],
    'social-media' => [
        'title' => 'Social Media Pack',
        'icon' => 'fa-hashtag',
        'content' => <<<EOT
// Twitter Post (280 chars)
🚀 [Main point in one punchy sentence]

💡 Key insight
🔍 Supporting fact
🎯 Call to action

#hashtag1 #hashtag2

// LinkedIn Post
[Attention-grabbing headline]

Have you ever wondered [question that addresses pain point]?

Here's what I discovered:

👌 Key finding #1
👌 Key finding #2
👌 Key finding #3

But here's the most important part:
[Main insight or takeaway]

🔑 Action steps:
1. First step
2. Second step
3. Third step

What's your experience with this? Share in the comments!

#ProfessionalDevelopment #Industry #Trends

// Instagram Caption
✨ [Catchy opening line]

🎯 What you'll learn:
• Point 1
• Point 2
• Point 3

💫 Tag someone who needs to see this!

.
.
.
#instagram #growth #success
[Add more relevant hashtags]
EOT
    ],
    'email-campaign' => [
        'title' => 'Email Campaign',
        'icon' => 'fa-envelope',
        'content' => <<<EOT
Subject: [Compelling Subject Line]

Hi [First Name],

I hope this email finds you well!

[Personalized opening referencing previous interaction or mutual interest]

I wanted to reach out because [clear purpose/value proposition]

Here's what makes this special:

• [Benefit 1]
• [Benefit 2]
• [Benefit 3]

[Social proof or testimonial]

Ready to take the next step? Here's what to do:

1. [Clear action step]
2. [Optional additional step]
3. [Final conversion action]

[Urgency or scarcity element if applicable]

Let me know if you have any questions!

Best regards,
[Your Name]
[Your Title]
[Company Name]

P.S. [Additional incentive or reminder]

--
[Contact Information]
[Social Media Links]
[Company Address]
EOT
    ],
    'product-description' => [
        'title' => 'Product Description',
        'icon' => 'fa-tag',
        'content' => <<<EOT
[Product Name]
Starting at $[Price]

🌟 Overview
[2-3 sentences highlighting the product's main value proposition]

✨ Key Features
• [Feature 1] - [Benefit]
• [Feature 2] - [Benefit]
• [Feature 3] - [Benefit]
• [Feature 4] - [Benefit]

🎯 Perfect For
• [Ideal Customer 1]
• [Ideal Customer 2]
• [Ideal Customer 3]

📦 What's Included
• [Item 1]
• [Item 2]
• [Item 3]

⭐️ Customer Reviews
"[Featured review quote]" - [Customer Name]

💫 Specifications
• Dimensions: [X x Y x Z]
• Weight: [Weight]
• Materials: [Materials list]
• Colors: [Available colors]

🔒 Warranty
[Warranty details]

📦 Shipping
[Shipping information and timeframes]

💳 Payment Options
[Available payment methods]

[Call to Action Button Text]
EOT
    ],
    'technical-doc' => [
        'title' => 'Technical Documentation',
        'icon' => 'fa-file-code',
        'content' => <<<EOT
# [Component/Feature Name]
Version: [x.x.x]

## Overview
[Brief description of the component/feature and its purpose]

## Prerequisites
- Requirement 1
- Requirement 2
- Requirement 3

## Installation
```bash
# Installation command
npm install package-name
```

## Basic Usage
```javascript
// Example code
const component = new Component({
    option1: 'value1',
    option2: 'value2'
});
```

## API Reference

### Methods
| Method | Parameters | Return Type | Description |
|--------|------------|-------------|-------------|
| method1 | (param1: Type) | ReturnType | Description |
| method2 | (param1: Type) | ReturnType | Description |

### Events
| Event Name | Payload | Description |
|------------|---------|-------------|
| event1 | PayloadType | Description |
| event2 | PayloadType | Description |

## Configuration Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| option1 | Type | default | Description |
| option2 | Type | default | Description |

## Examples

### Basic Example
```javascript
// Code example
```

### Advanced Usage
```javascript
// Advanced code example
```

## Troubleshooting
Common issues and their solutions:

1. Problem: [Issue description]
   Solution: [Solution steps]

2. Problem: [Issue description]
   Solution: [Solution steps]

## Best Practices
- Best practice 1
- Best practice 2
- Best practice 3

## Contributing
[Contributing guidelines]

## License
[License information]
EOT
    ]
];

// Format processors
$formatProcessors = [
    'html' => [
        'h1' => fn($text) => "<h1>$text</h1>",
        'h2' => fn($text) => "<h2>$text</h2>",
        'h3' => fn($text) => "<h3>$text</h3>",
        'h4' => fn($text) => "<h4>$text</h4>",
        'bold' => fn($text) => "<strong>$text</strong>",
        'italic' => fn($text) => "<em>$text</em>",
        'underline' => fn($text) => "<u>$text</u>",
        'strike' => fn($text) => "<del>$text</del>",
        'quote' => fn($text) => "<blockquote>$text</blockquote>",
        'code' => fn($text) => "<pre><code>$text</code></pre>",
        'list' => function($text) {
            $items = array_filter(array_map('trim', explode("\n", $text)));
            return "<ul>\n" . implode("\n", array_map(fn($item) => "  <li>$item</li>", $items)) . "\n</ul>";
        },
        'numbered-list' => function($text) {
            $items = array_filter(array_map('trim', explode("\n", $text)));
            return "<ol>\n" . implode("\n", array_map(fn($item) => "  <li>$item</li>", $items)) . "\n</ol>";
        }
    ],
    'markdown' => [
        'h1' => fn($text) => "# $text",
        'h2' => fn($text) => "## $text",
        'h3' => fn($text) => "### $text",
        'h4' => fn($text) => "#### $text",
        'bold' => fn($text) => "**$text**",
        'italic' => fn($text) => "*$text*",
        'underline' => fn($text) => "_$text_",
        'strike' => fn($text) => "~~$text~~",
        'quote' => fn($text) => "> $text",
        'code' => fn($text) => "```\n$text\n```",
        'list' => fn($text) => implode("\n", array_map(fn($item) => "- $item", array_filter(array_map('trim', explode("\n", $text))))),
        'numbered-list' => function($text) {
            $items = array_filter(array_map('trim', explode("\n", $text)));
            return implode("\n", array_map(fn($i, $item) => ($i + 1) . ". $item", array_keys($items), $items));
        }
    ]
];

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($template && isset($templates[$template])) {
        $text = $templates[$template]['content'];
        $formatted = $text;
    } elseif ($format && isset($formatProcessors[$mode][$format])) {
        $formatted = $formatProcessors[$mode][$format]($text);
    } else {
        $formatted = $text;
    }
}

// Text analysis
$charCount = strlen($text);
$wordCount = str_word_count($text);
$lineCount = substr_count($text, "\n") + 1;
$readingTime = ceil($wordCount / 200); // Average reading speed of 200 words per minute
$sentenceCount = preg_match_all('/[.!?]+/', $text, $matches);
$avgWordsPerSentence = $sentenceCount > 0 ? round($wordCount / $sentenceCount, 1) : 0;
$uniqueWords = count(array_unique(str_word_count(strtolower($text), 1)));
$lexicalDensity = $wordCount > 0 ? round(($uniqueWords / $wordCount) * 100, 1) : 0;

// Get common SEO keywords (simple implementation)
function getKeywords($text, $limit = 5) {
    $words = str_word_count(strtolower($text), 1);
    $stopWords = ['the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have', 'i', 'it', 'for', 'not', 'on', 'with', 'he', 'as', 'you', 'do', 'at'];
    $words = array_diff($words, $stopWords);
    $wordCount = array_count_values($words);
    arsort($wordCount);
    return array_slice($wordCount, 0, $limit);
}
$keywords = getKeywords($text);

?>
<!DOCTYPE html>
<html lang="en" data-theme="<?php echo htmlspecialchars($theme); ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Professional Text Formatter</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.12.0/cdn/themes/light.css">
    <script type="module" src="https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.12.0/cdn/shoelace-autoloader.js"></script>
    <style>
        /* Theme Variables */
        :root {
            --primary-color: #2563eb;
            --primary-dark: #1d4ed8;
            --success-color: #059669;
            --warning-color: #d97706;
            --error-color: #dc2626;
            --gray-50: #f9fafb;
            --gray-100: #f3f4f6;
            --gray-200: #e5e7eb;
            --gray-300: #d1d5db;
            --gray-400: #9ca3af;
            --gray-500: #6b7280;
            --gray-600: #4b5563;
            --gray-700: #374151;
            --gray-800: #1f2937;
            --gray-900: #111827;
            
            --font-sans: 'Inter', system
