<?php
require_once __DIR__ . '/../helpers.php';

class ArticlesController {

    private $articlesDir;
    
    public function __construct() {
        $this->articlesDir = __DIR__ . '/../../articles';
        
        // Создаем директорию для статей, если её нет
        if (!file_exists($this->articlesDir)) {
            mkdir($this->articlesDir, 0777, true);
        }
    }
    
    /**
     * Просмотр статей
     */
    public function view($params = []) {
        $slug = isset($params['slug']) ? $params['slug'] : '';
        $slug = $this->sanitizeSlug($slug);
        
        if (empty($slug)) {
			$articles = [];
			
			// Получаем все .txt файлы из директории articles
			$files = glob($this->articlesDir . '/*.txt');
			
			foreach ($files as $file) {
				$filename = basename($file, '.txt');
				
				// Читаем мета-данные из файла
				$content = file_get_contents($file);
				$metadata = $this->parseMetadata($content);
				$cleanContent = $this->stripMetadata($content);
				
				// Создаем превью (первые 200 символов без мета-данных)
				$preview = substr(strip_tags(textToHtml($cleanContent)), 0, 200) . '...';
				
				$articles[] = [
					'slug' => $metadata['slug'] ?? '',
					'date' => $metadata['date'] ?? date('Y-m-d H:i:s'),
					'title' => $metadata['title'] ?? '',
					'preview' => $preview,
					'filename' => $filename,
					'filemtime' => filemtime($file),
					'filesize' => filesize($file)
				];
			}
			
			// Сортируем по дате (сначала новые)
			usort($articles, function($a, $b) {
				return strtotime($b['date']) - strtotime($a['date']);
			});
			
			$header = ['right' => []];
			addButtonToHeaderSide($header['right'], '➕', 'Новая статья', "/articles.create");
			
			renderPage('articles/index', [
				'title' => 'Все статьи',
				'description' => 'Список всех статей на сайте',
				'articles' => $articles,
				'total' => count($articles),
				'header' => $header
			]);
            return;
        }
        
        // Ищем файл статьи (имена файлов у статей такие же, как их slug)
        $files = glob($this->articlesDir . '/' . $slug . '.txt');
        
        if (empty($files)) {
            renderPage('Файл статьи не найден (slug=' . $slug . ')');
            return;
        }
        
        $file = $files[0]; // Берем первый найденный файл
        $filename = basename($file, '.txt');
        
        // Читаем и парсим содержимое
        $content = file_get_contents($file);
        $metadata = $this->parseMetadata($content);
        $rawContent = $this->stripMetadata($content);
        
        //consolog(textToHtml($rawContent));
        
        $title = $metadata['title'] ?? '';
        
        $header = ['left' => [], 'right' => []];
		addButtonToHeaderSide($header['left'], '←', 'Все статьи', "/articles");
		addButtonToHeaderSide($header['right'], '✏️', 'Редактировать', "/articles.edit/$slug");
        
        renderPage('articles/article', [
            'title' => $title,
            'description' => 'Просмотр статьи',
            'article' => [
                'title' => $title,
                'date' => $metadata['date'] ?? date('Y-m-d H:i:s'),
                'raw_content' => $rawContent,
                'slug' => $slug,
                'filename' => $filename
            ],
            'mode' => 'view',
            'header' => $header,
            'isNew' => false
        ]);
    }
    
    /**
     * Сохранение статьи
     */
    public function save($params = []) {
        $title = $_POST['title'] ?? '';
        $content = $_POST['content'] ?? '';
        
        $slug = isset($params['slug']) ? $params['slug'] : '';
        $slug = $this->sanitizeSlug($slug);
        $date = date('Y-m-d H:i:s'); // По умолчанию - время вызова функции сохранения
        
        // Валидация
        if (empty($title) || empty($content)) {
            $_SESSION['flash_message'] = 'Заголовок и содержание обязательны';
            $_SESSION['flash_type'] = 'error';
            header('Location: /articles.edit/' . $slug);
            return;
        }
        
        if ($slug === '') {
            // Значит новая статья, создаем slug из даты и заголовка
            $slug = $this->createSlug($title, $date);
        }
        else {
            // Ищем старый файл
            $oldFilePath = null;
            $files = glob($this->articlesDir . '/' . $slug . '.txt');
            
            if (!empty($files)) {
        	    $oldFilePath = $files[0];
			    $fileContent = file_get_contents($oldFilePath);
			    // Парсим мета-данные и берем дату оттуда
                $metadata = $this->parseMetadata($fileContent);
                $date = $metadata['date'];
		    }
		}
        
        // Новый slug (может измениться, если изменился заголовок)
        $newSlug = $this->createSlug($title, $date);
        
        // Формируем новое имя файла
        $newFilename = $newSlug . '.txt';
        $newFilepath = $this->articlesDir . '/' . $newFilename;
        
        // Если имя файла изменилось, удаляем старый
        if ($oldFilePath !== $newFilepath) {
            unlink($oldFilePath);
        }
        
        // Подготавливаем содержимое с мета-данными
        $fileContent = "---\n";
        $fileContent .= "title: " . $this->yamlEscape($title) . "\n";
        $fileContent .= "date: " . $date . "\n";
        $fileContent .= "slug: " . $newSlug . "\n";
        $fileContent .= "---\n\n";
        $fileContent .= $content;
        
        // Сохраняем файл
        if (file_put_contents($newFilepath, $fileContent)) {
            $_SESSION['flash_message'] = 'Статья успешно сохранена';
            header('Location: /articles/' . $newSlug);
        } else {
            $_SESSION['flash_message'] = 'Ошибка при сохранении статьи';
            $_SESSION['flash_type'] = 'error';
            header('Location: /articles.edit/' . $slug);
        }
    }
    
    /**
     * Редактирование статьи
     */
    public function edit($params = []) {
        // Если пришли POST-данные - сохраняем
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->save();
            return;
        }
        
        $slug = !empty($params['slug']) ? $params['slug'] : '';
        $slug = $this->sanitizeSlug($slug);
        
        $isNew = empty($slug);
        
        if (!$isNew) {
            // Ищем файл статьи
            $files = glob($this->articlesDir . '/' . $slug . '.txt');
            
            if (!empty($files)) {
        	    $file = $files[0];
			    $filename = basename($file, '.txt');
			    $content = file_get_contents($file);
			    
			    // Парсим мета-данные
			    $metadata = $this->parseMetadata($content);
			    $rawContent = $this->stripMetadata($content);
		    }
		    else {
				renderPage('No article for slug ' . $slug);
				return;
			}
		}
		
		$header = ['right' => []];
		addButtonToHeaderSide($header['right'], '💾', 'Сохранить', 'submit');
		if (!$isNew) {
			addButtonToHeaderSide($header['right'], '🗑️', 'Удалить', "/articles.delete/$slug");
		}
		addButtonToHeaderSide($header['right'], '✖', 'Отмена', "/articles/$slug");
		
        renderPage('articles/article', [
            'title' => $isNew ? 'Новая статья' : 'Редактирование: ' . $metadata['title'],
            'description' => 'Редактирование статьи',
            'article' => [
                'title' => $isNew ? '' : $metadata['title'],
                'date' => $isNew ? '' : $metadata['date'],
                'raw_content' => $isNew ? '' : $rawContent,
                'slug' => $isNew ? '' : $slug
            ],
            'mode' => 'edit',
            'header' => $header,
            'isNew' => $isNew
        ]);
    }
    
    /**
     * Удаление статьи
     */
    public function delete($params = []) {
        $slug = isset($params['slug']) ? $params['slug'] : '';
        $slug = $this->sanitizeSlug($slug);
        
        if (empty($slug)) {
            renderPage('Не указана статья для удаления');
            return;
        }
        
        // Если есть подтверждение - удаляем
        if (isset($params['confirm']) && $params['confirm'] === 'yes') {
            $files = glob($this->articlesDir . '/' . $slug . '.txt');
            $deleted = false;
            
            foreach ($files as $file) {
                if (unlink($file)) {
                    $deleted = true;
                }
            }
            
            if ($deleted) {
                $_SESSION['flash_message'] = 'Статья успешно удалена';
                $_SESSION['flash_type'] = 'success';
            } else {
                $_SESSION['flash_message'] = 'Ошибка при удалении статьи';
                $_SESSION['flash_type'] = 'error';
            }
            
            header('Location: /articles');
            return;
        }
        
        // Ищем файл для отображения информации
        $files = glob($this->articlesDir . '/' . $slug . '.txt');
        $articleTitle = $slug;
        
        if (!empty($files)) {
            $content = file_get_contents($files[0]);
            $metadata = $this->parseMetadata($content);
            $articleTitle = $metadata['title'] ?? '';
        }
        
        // Переводим на страницу с подтверждением
        renderPage('confirm_delete', [
            'title' => 'Подтверждение удаления',
            'description' => 'Подтвердите удаление',
            'path' => $slug,
            'href_yes' => "/articles.delete/$slug?confirm=yes",
            'href_no' => "/articles.edit/$slug"
        ]);
    }
    
    /**
     * Парсинг YAML-метаданных из начала файла
     */
    private function parseMetadata($content) {
        $metadata = [];
        
        if (preg_match('/^---\s*\n(.*?)\n---\s*\n/s', $content, $matches)) {
            $yaml = $matches[1];
            $lines = explode("\n", $yaml);
            
            foreach ($lines as $line) {
                if (strpos($line, ':') !== false) {
                    list($key, $value) = explode(':', $line, 2);
                    $metadata[trim($key)] = trim($value);
                }
            }
        }
        
        return $metadata;
    }
    
    /**
     * Удаление метаданных из контента
     */
    private function stripMetadata($content) {
        return preg_replace('/^---\s*\n.*?\n---\s*\n/s', '', $content);
    }
    
    /**
     * Экранирование для YAML
     */
    private function yamlEscape($string) {
        // Если есть спецсимволы, заключаем в кавычки
        if (preg_match('/[:#\[\]{},&*?|>-]/', $string)) {
            return '"' . addcslashes($string, '"') . '"';
        }
        return $string;
    }
    
    /**
     * Очистка slug от опасных символов
     */
    private function sanitizeSlug($slug) {
        // Удаляем всё, кроме букв, цифр и дефисов
        $slug = preg_replace('/[^a-zA-Z0-9\-]/', '', $slug);
        return $slug;
    }
    
    private function utf8_strtolower($string) {
		$converter = [
			'А' => 'а', 'Б' => 'б', 'В' => 'в', 'Г' => 'г', 'Д' => 'д',
			'Е' => 'е', 'Ё' => 'ё', 'Ж' => 'ж', 'З' => 'з', 'И' => 'и',
			'Й' => 'й', 'К' => 'к', 'Л' => 'л', 'М' => 'м', 'Н' => 'н',
			'О' => 'о', 'П' => 'п', 'Р' => 'р', 'С' => 'с', 'Т' => 'т',
			'У' => 'у', 'Ф' => 'ф', 'Х' => 'х', 'Ц' => 'ц', 'Ч' => 'ч',
			'Ш' => 'ш', 'Щ' => 'щ', 'Ъ' => 'ъ', 'Ы' => 'ы', 'Ь' => 'ь',
			'Э' => 'э', 'Ю' => 'ю', 'Я' => 'я',
			'A' => 'a', 'B' => 'b', 'C' => 'c', 'D' => 'd', 'E' => 'e',
			'F' => 'f', 'G' => 'g', 'H' => 'h', 'I' => 'i', 'J' => 'j',
			'K' => 'k', 'L' => 'l', 'M' => 'm', 'N' => 'n', 'O' => 'o',
			'P' => 'p', 'Q' => 'q', 'R' => 'r', 'S' => 's', 'T' => 't',
			'U' => 'u', 'V' => 'v', 'W' => 'w', 'X' => 'x', 'Y' => 'y',
			'Z' => 'z'
		];
		
		return strtr($string, $converter);
	}
	
	private function transliterate($string) {
        // Транслитерация (полная таблица)
        $converter = [
            'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd',
            'е' => 'e', 'ё' => 'e', 'ж' => 'zh', 'з' => 'z', 'и' => 'i',
            'й' => 'y', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n',
            'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't',
            'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'ts', 'ч' => 'ch',
            'ш' => 'sh', 'щ' => 'sch', 'ъ' => '', 'ы' => 'y', 'ь' => '',
            'э' => 'e', 'ю' => 'yu', 'я' => 'ya',
            'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D',
            'Е' => 'E', 'Ё' => 'E', 'Ж' => 'Zh', 'З' => 'Z', 'И' => 'I',
            'Й' => 'Y', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N',
            'О' => 'O', 'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T',
            'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'Ts', 'Ч' => 'Ch',
            'Ш' => 'Sh', 'Щ' => 'Sch', 'Ъ' => '', 'Ы' => 'Y', 'Ь' => '',
            'Э' => 'E', 'Ю' => 'Yu', 'Я' => 'Ya'
        ];
        
        return strtr($string, $converter);
    }
    
    /**
     * Создание slug из заголовка
     */
    private function createSlug($title, $date) {
        $dateForFile = str_replace([' ', ':'], '-', $date);
        // Приводим к нижнему регистру
        $title = $this->utf8_strtolower($title);
        // Транслитерируем
        $title = $this->transliterate($title);
        // Заменяем всё, кроме букв, цифр и дефисов, на дефисы
        $title = preg_replace('/[^a-z0-9]+/', '-', $title);
        // Убираем дефисы в начале и конце
        $title = trim($title, '-');
        // Ограничиваем длину
        $title = substr($title, 0, 100);
        return $title . '-' . $dateForFile;
    }
        
    /**
     * Конвертация HTML обратно в текст с разметкой
     */
    private function htmlToText($html) {
		return $html;
        // Заменяем HTML-теги обратно на markdown-подобную разметку
        $text = $html;
        
        // Заголовки
        $text = preg_replace('/<h1>(.*?)<\/h1>/', "# $1\n\n", $text);
        $text = preg_replace('/<h2>(.*?)<\/h2>/', "## $1\n\n", $text);
        $text = preg_replace('/<h3>(.*?)<\/h3>/', "### $1\n\n", $text);
        $text = preg_replace('/<h4>(.*?)<\/h4>/', "#### $1\n\n", $text);
        $text = preg_replace('/<h5>(.*?)<\/h5>/', "##### $1\n\n", $text);
        $text = preg_replace('/<h6>(.*?)<\/h6>/', "###### $1\n\n", $text);
        
        // Жирный и курсив
        $text = preg_replace('/<strong><em>(.*?)<\/em><\/strong>/', '***$1***', $text);
        $text = preg_replace('/<strong>(.*?)<\/strong>/', '**$1**', $text);
        $text = preg_replace('/<em>(.*?)<\/em>/', '*$1*', $text);
        
        // Списки
        $text = preg_replace('/<ul>(.*?)<\/ul>/s', "$1\n", $text);
        $text = preg_replace('/<ol>(.*?)<\/ol>/s', "$1\n", $text);
        $text = preg_replace_callback('/<li>(.*?)<\/li>/', function($matches) {
            // Определяем тип списка по контексту (упрощенно)
            return "- " . $matches[1] . "\n";
        }, $text);
        
        // Ссылки
        $text = preg_replace('/<a href="([^"]+)">(.*?)<\/a>/', '[$2]($1)', $text);
        
        // Изображения
        $text = preg_replace('/<img src="([^"]+)" alt="([^"]*)">/', '![$2]($1)', $text);
        
        // Цитаты
        $text = preg_replace('/<blockquote>(.*?)<\/blockquote>/', '> $1', $text);
        
        // Код
        $text = preg_replace('/<pre><code>(.*?)<\/code><\/pre>/s', "```\n$1\n```", $text);
        $text = preg_replace('/<code>(.*?)<\/code>/', '`$1`', $text);
        
        // Параграфы
        $text = preg_replace('/<p>(.*?)<\/p>/', "$1\n\n", $text);
        $text = preg_replace('/<p>&nbsp;<\/p>/', "\n", $text);
        
        // Горизонтальная линия
        $text = preg_replace('/<hr>/', "---\n", $text);
        
        // Убираем остальные теги
        $text = strip_tags($text);
        
        // Очищаем лишние переносы строк
        $text = preg_replace("/\n{3,}/", "\n\n", $text);
        
        return trim($text);
    }
}
