<?php
// Function to extract metadata, including Open Graph (Facebook)
function get_metadata($url) {
    $metadata = [];
    $context = stream_context_create(['http' => ['header' => 'User-Agent: Mozilla/5.0']]);
    $html = @file_get_contents($url, false, $context);

    if ($html === false) {
        return null;
    }

    // Load the HTML content
    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    libxml_clear_errors();

    // Extract Open Graph meta tags for Facebook posts
    $metaTags = $dom->getElementsByTagName('meta');
    foreach ($metaTags as $metaTag) {
        if ($metaTag->getAttribute('property') == 'og:title') {
            $metadata['title'] = $metaTag->getAttribute('content');
        }
        if ($metaTag->getAttribute('property') == 'og:description') {
            $metadata['description'] = $metaTag->getAttribute('content');
        }
        if ($metaTag->getAttribute('property') == 'og:image') {
            $metadata['image'] = $metaTag->getAttribute('content');
        }
    }

    return $metadata;
}

// Handle metadata fetching via AJAX
if (isset($_POST['fetch_metadata'])) {
    $link = filter_var(trim($_POST['article_link']), FILTER_VALIDATE_URL);
    if ($link) {
        $metadata = get_metadata($link);
        if ($metadata) {
            // Convert HTML entities to human-readable form and sanitize
            $title = html_entity_decode($metadata['title'], ENT_QUOTES, 'UTF-8');
            // Replace deprecated FILTER_SANITIZE_STRING with strip_tags
            $title = strip_tags($title);
            $title = trim($title);
            $markdown = "## " . $title . "\n";
            
            if (isset($metadata['description'])) {
                $description = html_entity_decode($metadata['description'], ENT_QUOTES, 'UTF-8');
                $description = strip_tags($description);
                $description = trim($description);
                $markdown .= $description . "\n\n";
            }
            if (isset($metadata['image'])) {
                $markdown .= "![](" . htmlspecialchars($metadata['image'], ENT_QUOTES, 'UTF-8') . ")\n\n";
            }

            echo json_encode(['success' => true, 'title' => $title, 'markdown' => $markdown]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Could not fetch metadata']);
        }
    } else {
        echo json_encode(['success' => false, 'error' => 'Invalid URL']);
    }
    exit();
}

// Save the markdown file after form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['fetch_metadata'])) {
    $title = $_POST['post_title'] ?? '';
    $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
    $title = strip_tags($title); // Replace deprecated FILTER_SANITIZE_STRING
    $title = trim($title);
    $title = preg_replace('/\p{C}+/u', '', $title); // Removes invisible characters
    $markdown_content = $_POST['markdown'] ?? '';
    $date = date('Y-m-d H:i:s'); // Include time in the date

    // Generate a clean, human-readable filename with the first two words of the title
    $title_words = preg_split('/\s+/', trim($title));
    $filename_part = strtolower(preg_replace('/[^a-zA-Z0-9-_]/', '', implode('_', array_slice($title_words, 0, 2))));
    $filename_date = date('Y-m-d'); // Use date without time for filename
    $filename = $filename_date . '-' . $filename_part . ".md";

    // Generate the Markdown content in the required format
    $markdown = "---\n";
    $markdown .= "title: " . htmlspecialchars($title, ENT_QUOTES, 'UTF-8') . "\n";
    $markdown .= "date: " . $date . "\n";
    $markdown .= "---\n\n";
    $markdown .= $markdown_content;

    // Save the markdown file
    $file_path = "posts/$filename";
    if (file_put_contents($file_path, $markdown) !== false) {
        echo "Markdown file saved as: $filename";
    } else {
        echo "Error saving markdown file.";
    }
    exit();
}

// Helper function to extract post date from YAML front matter
function getPostDate($filename) {
    $content = file_get_contents($filename);
    if ($content === false) {
        error_log("Failed to read file: $filename");
        return null;
    }
    $content = str_replace("\r\n", "\n", $content); // Normalize line endings

    // Extract YAML front matter
    if (preg_match('/^---\n(.*?)\n---/s', $content, $matches)) {
        $yaml_content = trim($matches[1]);
        $yaml = parseYAML($yaml_content);
        if (is_array($yaml) && isset($yaml['date'])) {
            $dateStr = $yaml['date'];

            // Try parsing the date with available formats
            $dateFormats = [
                'Y-m-d H:i:s',
                'Y-m-d H:i',
                'Y-m-d',
                'Y-m-d\TH:i:sP', // ISO 8601 format
                'Y-m-d\TH:i:s',  // ISO 8601 without timezone
                'D, d M Y H:i:s O', // RFC 2822
            ];
            foreach ($dateFormats as $format) {
                $date = DateTime::createFromFormat($format, $dateStr);
                $errors = DateTime::getLastErrors();
                if ($date && $errors && $errors['warning_count'] == 0 && $errors['error_count'] == 0) {
                    return $date; // Return valid DateTime
                }
            }
            // Try using strtotime() as a last resort
            $timestamp = strtotime($dateStr);
            if ($timestamp !== false) {
                return (new DateTime())->setTimestamp($timestamp); // Return DateTime from timestamp
            }
        }
    }
    return null;
}

// Simple YAML parser function
function parseYAML($yaml_content)
{
    $lines = explode("\n", $yaml_content);
    $data = [];
    foreach ($lines as $line) {
        $line = trim($line);
        if (preg_match('/^([^:]+):\s*(.*)$/', $line, $matches)) {
            $key = trim($matches[1]);
            $value = trim($matches[2]);

            // Remove surrounding quotes if present
            if ((substr($value, 0, 1) === '"' && substr($value, -1) === '"') ||
                (substr($value, 0, 1) === "'" && substr($value, -1) === "'")) {
                $value = substr($value, 1, -1);
            }

            $data[$key] = $value;
        }
    }
    return $data;
}

// Include header
include 'header.php';
?>

<style>
    input[type="text"], textarea {
        width: 100%;
        padding: 10px;
        margin-bottom: 10px;
        background-color: #222;
        color: #ccc;
        border-radius: 4px;
        border: 1px solid #444;
    }
    input[type="submit"], button {
        background-color: #5cb85c;
        color: white;
        padding: 10px 20px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }
    .error {
        color: red;
    }
    .article_link {
        text-align: right;
        font-size: 0.8em;
        color: #888;
    }
</style>
<script>
    function fetchMetadata() {
        const articleLink = document.getElementById('article_link').value;
        const errorMessage = document.getElementById('error_message');
        const markdownField = document.getElementById('markdown');
        const titleField = document.getElementById('post_title');

        fetch('', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                fetch_metadata: true,
                article_link: articleLink
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                markdownField.value += data.markdown;
                titleField.value = data.title;
                errorMessage.textContent = '';
            } else {
                errorMessage.textContent = data.error;
            }
        })
        .catch(err => {
            errorMessage.textContent = 'An error occurred';
        });
    }
</script>
</head>
<body>

<h1>Create a Markdown Post</h1>

<form method="POST" action="">
    <label for="post_title">Post Title:</label>
    <input type="text" name="post_title" id="post_title" required>

    <label for="article_link">Article Link:</label>
    <input type="text" name="article_link" id="article_link">

    <button type="button" onclick="fetchMetadata()">Fetch Metadata</button>

    <label for="markdown">Markdown Content:</label>
    <textarea name="markdown" id="markdown" rows="10" required></textarea>

    <p id="error_message" class="error"></p>

    <input type="submit" value="Generate Markdown">
</form>

<?php
include 'footer.php';
?>