<?php
// Enable error reporting (for development purposes)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start the session at the very top of the script
session_start();

// Initialize variables to prevent undefined errors
$optimizedContent = '';
$originalContent = '';

// Function to clean content by removing '*' and '#' characters
function cleanContent($content) {
    // Remove '*' and '#' characters
    return str_replace(['*', '#'], '', $content);
}

// Function to apply heading tags (H1, H2, H3, H4) to structure the article
function applyHeadingTags($content) {
    $lines = explode("\n", $content);
    foreach ($lines as &$line) {
        $trimmedLine = trim($line);

        // Apply H1 tag if line starts with 'Title:'
        if (stripos($trimmedLine, 'Title:') === 0) {
            $line = '<h1>' . htmlspecialchars($trimmedLine) . '</h1>';
        }
        // Apply H2 tag for common subheading markers
        elseif (preg_match('/^(Introduction|Conclusion|What’s|Step \d+|FAQ|Keywords Used|Sample Prompt)/i', $trimmedLine)) {
            $line = '<h2>' . htmlspecialchars($trimmedLine) . '</h2>';
        }
        // Apply H3 tag for subheadings and questions
        elseif (preg_match('/^(Subheading:|Q\d+:)/i', $trimmedLine)) {
            $line = '<h3>' . htmlspecialchars($trimmedLine) . '</h3>';
        }
    }
    return implode("\n", $lines);
}

// Function to wrap text at a specified number of words per line for better readability
function wrapText($content, $wordsPerLine = 15) {
    $paragraphs = explode("\n", $content);
    $wrappedParagraphs = [];

    foreach ($paragraphs as $paragraph) {
        if (trim($paragraph) == '') {
            $wrappedParagraphs[] = '';
            continue;
        }

        $words = explode(' ', $paragraph);
        $wrappedContent = '';
        $wordCount = 0;

        foreach ($words as $word) {
            $wrappedContent .= $word . ' ';
            $wordCount++;

            if ($wordCount >= $wordsPerLine) {
                $wrappedContent = rtrim($wrappedContent) . "\n";
                $wordCount = 0;
            }
        }

        $wrappedParagraphs[] = trim($wrappedContent);
    }

    return implode("\n", $wrappedParagraphs);
}

// Handle form submission for optimizing content
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] == 'optimize') {
        if (isset($_POST['content']) && !empty(trim($_POST['content']))) {
            $originalContent = $_POST['content'];

            // Step 1: Clean the content
            $cleanedContent = cleanContent($originalContent);

            // Step 2: Apply heading tags
            $structuredContent = applyHeadingTags($cleanedContent);

            // Step 3: Wrap text at 15 words per line
            $wrappedContent = wrapText($structuredContent, 15);

            // Store the optimized content and original content in session variables
            $_SESSION['optimizedContent'] = $wrappedContent;
            $_SESSION['originalContent'] = $originalContent;

            // Redirect to the same page to prevent form resubmission
            header("Location: " . $_SERVER['PHP_SELF']);
            exit();
        } else {
            // Display an error message if no content is provided
            $optimizedContent = "Please provide some content to optimize.";
        }
    } elseif ($_POST['action'] == 'reset') {
        // Handle reset action by clearing session variables
        unset($_SESSION['optimizedContent']);
        unset($_SESSION['originalContent']);
        
        // Redirect to the same page to refresh the form
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    }
}

// Retrieve the optimized content from the session after redirection
if (isset($_SESSION['optimizedContent'])) {
    $optimizedContent = $_SESSION['optimizedContent'];
    $originalContent = $_SESSION['originalContent'];

    // Clear the session variables to reset the tool on page refresh
    unset($_SESSION['optimizedContent']);
    unset($_SESSION['originalContent']);
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>SEO Content Optimization Tool</title>
    <style>
        /* Basic styling */
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        textarea {
            width: 100%;
            height: 200px;
        }
        .optimized-content {
            margin-top: 20px;
            background-color: #f9f9f9;
            padding: 15px;
            border: 1px solid #ddd;
        }
        h1, h2, h3, h4 {
            color: #2c3e50;
        }
        h1 {
            font-size: 2em;
            text-align: center;
            margin-bottom: 0.2em;
        }
        h3 {
            font-size: 1.2em;
            color: #34495e;
            text-align: center;
            margin-top: 0;
            margin-bottom: 1em;
        }
        p {
            text-align: justify;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <!-- Headline and Subheadline -->
    <h1>SEO Content Optimization Tool</h1>
    <h3>Enhance your article's structure and readability for better SEO</h3>

    <!-- Your Form -->
    <form method="POST" action="">
        <textarea name="content" placeholder="Paste your blog content here"><?php echo isset($originalContent) ? htmlspecialchars($originalContent) : ''; ?></textarea>
        <br><br>
        <button type="submit" name="action" value="optimize">Optimize Text</button>
        <button type="submit" name="action" value="reset">Reset</button>
    </form>

    <!-- Display Optimized Content -->
    <?php if (!empty($optimizedContent)): ?>
        <div class="optimized-content">
            <h2>Optimized Content:</h2>
            <div>
                <?php
                // Display the content with allowed HTML tags
                echo nl2br(strip_tags($optimizedContent, '<h1><h2><h3><h4><p><br>'));
                ?>
            </div>
        </div>
    <?php endif; ?>
</body>
</html>
