<?php
require_once 'db_functions.php';

function article_ids_by_newest()
{
    $conn = get_connection();
    $results = $conn->query('SELECT article_id FROM article ORDER BY published_at DESC');
    $ids = [];

    while ($row = $results->fetch_assoc())
        $ids[] = $row['article_id'];

    return $ids;
}

function article_ids_by_oldest()
{
    $conn = get_connection();
    $results = $conn->query('SELECT article_id FROM article ORDER BY published_at ASC');
    $ids = [];

    while ($row = $results->fetch_assoc())
        $ids[] = $row['article_id'];

    return $ids;
}

function articles_ids_by_author($author_id)
{
    $results = exec_stmt('SELECT article_id FROM article WHERE author_id = ? ORDER BY published_at DESC', 'i', $author_id);
    $ids = [];

    while ($row = $results->fetch_assoc())
        $ids[] = $row['article_id'];

    return $ids;
}

function article_tags()
{
    $conn = get_connection();
    $results = $conn->query('SELECT * FROM tags');
    $tags = [];

    while ($row = $results->fetch_assoc())
        $tags[] = $row;

    return $tags;
}

function article_ids_by_tag($tag)
{
    $results = exec_stmt('SELECT article_id FROM article WHERE article.article_id IN ( SELECT article_tags.article_id FROM article_tags INNER JOIN tags ON article_tags.tag_id = tags.tag_id WHERE tag = ?) ORDER BY published_at DESC', 's', $tag);
    $ids = [];

    while ($row = $results->fetch_assoc())
        $ids[] = $row['article_id'];

    return $ids;
}

/*
 * Reads the markdown file for a given article and generates the HTML for it.
 */
function article_page_from_markdown($article_id)
{
    $article = exec_stmt('SELECT * FROM article WHERE article_id = ?', 'i', $article_id)->fetch_assoc();
    $author = exec_stmt('SELECT user_id, username, profile_picture FROM user WHERE user_id = ?', 'i', $article['author_id'])->fetch_assoc();
    $markdown = read_file_one_string($_ENV['ARTICLES_FQ_PATH'] . $article_id . '/article.md');

    $parsedown = new Parsedown();
    $parsedown->setSafeMode(true);
    $article_content = $parsedown->text($markdown);

    $html = '
        <div class="article">
            
            <div class="row">
                <h1>' . $article['title'] . '</h1>
                ' . (isset($_COOKIE['user_id']) && $_COOKIE['user_id'] == $article['author_id'] ? '<a href="compose.php?article_id=' . $article_id . '"><i class="nf nf-fa-edit"></i></a>' : '') . '
            </div>
            <div class="row">
                <div class="col_right">
                    <h5>Written by <a href="user.php?action=view&user_id=' . $author['user_id'] . '">' . $author['username'] . '</a></h5>
                    <p>Published on ' . $article['published_at'] . '<br>
                    Lasted edited on ' . $article['updated_at'] . '</p>
                </div>
                <div class="card_pic_box">
                    <img src="' . $_ENV['PROFILE_IMAGES_PQ_PATH'] . $author['profile_picture'] . '" class="card_profile_picture" />
                </div>
            </div>
            <div class="line" style="margin-bottom: 15px;"></div>
                <div class="article_content">
                    ' . $article_content . '
                </div>
        </div>
    ';

    return $html;
}

function article_filters()
{
    $filters = '
        <form method="get">
            <label for="recency_desc"><i class="nf nf-md-sort_clock_ascending_outline"></i>
                <input id="recency_desc" type="radio" name="sort" value="oldest" onclick="this.form.submit()">
            </label>

            <label for="recency_asc"><i class="nf nf-md-sort_clock_descending_outline"></i>
                <input id="recency_asc" type="radio" name="sort" value="newest" onclick="this.form.submit()">
            </label>
        </form>
    ';

    return $filters;
}

/*
 * Generates cards for a given article.
 */
function article_card($article_id)
{
    $article = exec_stmt('SELECT * FROM article WHERE article_id = ?', 'i', $article_id)->fetch_assoc();

    $tags_results = exec_stmt('SELECT tag FROM article_tags INNER JOIN tags ON article_tags.tag_id = tags.tag_id WHERE article_id = ?', 'i', $article_id);

    $tags_html = '';
    if ($tags_results != null) {
        $tags_html .= '<div class="tag_row">';

        while ($row = $tags_results->fetch_assoc())
            $tags_html .= '<a href="/articles.php?tag=' . $row['tag'] . '" class="tag">#' . $row['tag'] . '</a>';

        $tags_html .= '</div>';
    }

    $author = exec_stmt('SELECT user_id, username, profile_picture FROM user WHERE user_id = ?', 'i', $article['author_id'])->fetch_assoc();

    $card = '
        <div class="article_card">
            <div class="row">
                <h4>' . $article['title'] . '</h4>
                <div class="card_info_box">
                    <div class="col-right">
                        <a href="user.php?action=view&user_id=' . $author['user_id'] . '">Written by: ' . $author['username'] . '</a>
                        <small>Published: ' . $article['published_at'] . '</small>
                        <small>Updated: ' . $article['updated_at'] . '</small>
                    </div>
                    <div class="card_pic_box">
                        <img src="' . $_ENV['PROFILE_IMAGES_PQ_PATH'] . $author['profile_picture'] . '" class="card_profile_picture">
                    </div>
                </div>
            </div>
            <div class="line"></div>
            <p>' . $article['excerpt'] . '</p>
            <div class="row">
                <a href="/articles.php?article_id=' . $article['article_id'] . '" class="button">Read More</a>
                <div class="tag_box">' . $tags_html . '</div>
            </div>
        </div>
    ';

    return $card;
}

function create_article($author_id, $title, $excerpt, $tags, $markdown_file_contents)
{
    $id = exec_stmt('INSERT INTO article (author_id, title, excerpt, published_at) VALUES (?, ?, ?, CURRENT_TIMESTAMP)', 'iss', $author_id, $title, $excerpt);

    $path = $_ENV['ARTICLES_FQ_PATH'] . $id . '/';
    mkdir($path);

    $fs = fopen($path . 'article.md', 'a');
    fwrite($fs, $markdown_file_contents);
    fclose($fs);

    if (count($tags) > 0) {
        $tag_insert_stmt = 'INSERT INTO article_tags (article_id, tag_id) VALUES ';
        $types = '';
        for ($i = 0; $i < count($tags); $i++) {
            $tag_insert_stmt .= '(' . $id . ', ?)';

            if ($i < count($tags) - 1)
                $tag_insert_stmt .= ', ';

            $types .= 'i';
        }

        exec_stmt($tag_insert_stmt, $types, ...$tags);
    }

    return $id;
}

function update_article($article_id, $title, $excerpt, $tags, $markdown_file_contents)
{
    exec_stmt('UPDATE article SET title = ?, excerpt = ?, updated_at = CURRENT_TIMESTAMP WHERE article_id = ?', 'ssi', $title, $excerpt, $article_id);

    $path = $_ENV['ARTICLES_FQ_PATH'] . $article_id . '/';
    $fs = fopen($path . 'article.md', 'w');
    fwrite($fs, $markdown_file_contents);
    fclose($fs);

    exec_stmt('DELETE from article_tags WHERE article_id = ?', 'i', $article_id);

    if (count($tags) > 0) {
        $tag_insert_stmt = 'INSERT INTO article_tags (article_id, tag_id) VALUES ';
        $types = '';
        for ($i = 0; $i < count($tags); $i++) {
            $tag_insert_stmt .= '(' . $article_id . ', ?)';

            if ($i < count($tags) - 1)
                $tag_insert_stmt .= ', ';

            $types .= 'i';
        }

        exec_stmt($tag_insert_stmt, $types, ...$tags);
    }
}

function delete_article($article_id)
{
    exec_stmt('DELETE FROM article_tags WHERE article_id = ?', 'i', $article_id);
    exec_stmt('DELETE FROM article WHERE article_id = ?', 'i', $article_id);

    delete_dir($_ENV['ARTICLES_FQ_PATH'] . $article_id . '/');
}

function delete_articles_by_author($author_id)
{
    exec_stmt('DELETE FROM article WHERE author_id = ?', 'i', $author_id);
}

function increment_read_counter($article_id)
{
    exec_stmt('UPDATE article SET read_count = read_count + 1 WHERE article_id = ?', 'i', $article_id);
}
