<?php
require "../include/variables.php";
require "../include/functions.php";

if($_SESSION['role'] < 1) {
    header("Location: index.php");
    http_response_code(404);
    die();
}

$filetypes = [
    0 => "article",
    1 => "page"
];

if(isset($_GET['article']) && filter_var($_GET['article'], FILTER_VALIDATE_INT)) {
    if(file_exists($wwwroot . "/content/journal/" . $_GET['article'] . ".md")){
        $fichier = $wwwroot . "/content/journal/" . $_GET['article'] . ".md";
        $filename = $_GET['article'];
        $filetype = 0;
    }
}

if(isset($_GET['page']) && strpos($_GET['page'], "..") == false && $_SESSION['role'] >= 3) {
    if(file_exists($wwwroot . "/content/" . $_GET['page'] . ".md")){
        $fichier = $wwwroot . "/content/" . $_GET['page'] . ".md";
        $filename = $_GET['page'];
        $filetype = 1;
    }
}

if (isset($_FILES['miniature']) && $_FILES['miniature']['error'] == 0 && isset($_GET['article'])) {
    // Chemins et noms de fichiers
    $tempPath = $_FILES['miniature']['tmp_name'];
    $path = '/src/miniature/'. $_GET['article'] .'.png';
    $rootPath = $wwwroot . "/html" . $path;
    $webPath = $root . $path;

    // Redimensionnement de l'image
    list($width, $height) = getimagesize($tempPath);
    $imageInfo = getimagesize($tempPath);

    if ($imageInfo[2] === IMAGETYPE_PNG || $imageInfo[2] === IMAGETYPE_JPEG) {
    $newWidth = 600;
    $newHeight = ($height / $width) * $newWidth;
    $imageResized = imagecreatetruecolor($newWidth, $newHeight);
    imagealphablending($imageResized, false);
    imagesavealpha($imageResized, true);
    $imageOriginal = imagecreatefromstring(file_get_contents($tempPath));
    imagecopyresampled($imageResized, $imageOriginal, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

    // Enregistrement de l'image redimensionnée
    imagepng($imageResized, $rootPath);

    // Nettoyage
    imagedestroy($imageOriginal);
    imagedestroy($imageResized);

    $bdd = connect($dbhost, $dbname, $dbuser, $dbpass);
    $req = $bdd->prepare("UPDATE articles SET image = :image WHERE ID = :article AND auteur = :user_id");
    $req->bindParam(":image", $webPath);
    $req->bindParam(":article", $_GET['article']);
    $req->bindParam(":user_id", $_SESSION['userid']);
    if($req->execute()) {
        $status = "Miniature mise à jour";
    } else {
        $status = "Erreur SQL";
    }
    } else {
        $status = "Le fichier doit être un PNG ou JPG";
    }
}

$filename = isset($filename) ? $filename : "";

if(isset($fichier)) {
    if(isset($_GET['article']) && isset($_POST['deletefile']) && $_POST['deletefile'] == "Supprimer") {
        if(unlink($fichier)) {
            $bdd = connect($dbhost, $dbname, $dbuser, $dbpass);
            $upload = $bdd->prepare("DELETE FROM articles WHERE ID = :filename AND auteur = :user_id");
            $upload->bindParam(':filename', $filename);
            $upload->bindParam(':auteur', $_SESSION['userid']);
            if($upload->execute()) {
                header("Location: editpage.php");
                echo "Fichier supprimé";
                exit();
            } else {
                die("Erreur SQL");
            }
        } else {
            die("Erreur : Le fichier n'a pas pu être supprimé");
        }
    }
    if(isset($_POST['page-content'])) {
        file_put_contents($fichier, nl2br($_POST['page-content']));
    }
    if(isset($_POST['article-classification']) && isset($_POST['article-resume']) && isset($_GET['article'])) {
        $bdd = connect($dbhost, $dbname, $dbuser, $dbpass);

        $req = $bdd->prepare("UPDATE articles SET classification = :classification, titre = :titre, resume = :resume WHERE ID = :article AND auteur = :user_id");
        $req->bindParam(':classification', $_POST['article-classification']);
        $req->bindParam(':titre', htmlspecialchars($_POST['article-titre']));
        $req->bindParam(':resume', nl2br($_POST['article-resume']));
        $req->bindParam(':article', $_GET['article']);
        $req->bindParam(':user_id', $_SESSION['userid']);
        if($req->execute()) {
            $status = "Informations mises à jour";
        } else {
            $status = "Erreur SQL";
        }
    }
    $contenu = file_get_contents($fichier);
}

?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta name="robots" content="noindex">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./src/css/style.css">
    <style>
    @media (prefers-color-scheme: dark) {
        .body {
            <?=$theme_dark?>
        }
    } 
    @media (prefers-color-scheme: light) {
        .body {
            <?=$theme_light?>
            }
        }
    </style>
    <link rel="icon" href="./src/img/favicon.ico">
    <title><?=$title?></title>
    <style>
        textarea {
            width: 100%;
            min-height: 50em;
        }
    </style>
</head>
<body class="body">
    <header>
        <div class="pancontent">
            <div class="athena-container">
                <a href="<?=$root?>">
                    <img src="./src/img/athena-mono.png" class="athena">
                </a>
            </div>
            <div class="content">
                <div>
                    <div class="main-title">
                        <div class="title"><?=$header_title?></div>
                        <div class="subtitle"><?=$header_subtitle?></div>
                    </div>
                </div>
            </div>
        </div>
    </header>
    <nav>
        <div class="pancontent">
            <?php nav($nav);?>
        </div>
    </nav>
    <main>
        <div class="content">
            <div>
                <div><div class="status"><?=$status?></div>
                    <?php 
                        if(isset($contenu)) {
                            echo '<form action="?' . $filetypes[$filetype] . '=' . $filename . '" method="post">';
                            echo "<div><div class='button'><a href='editpage.php'>Retour</a></div>";
                            echo "<div><div class='button'><a href='news.php?article=" . $filename . "'>Voir l'article</a></div>";
                            if(isset($_GET['article'])) {
                                $bdd = connect($dbhost, $dbname, $dbuser, $dbpass);
                                $req = $bdd->prepare("SELECT classification, titre, image, resume FROM articles WHERE ID = :article AND auteur = :user_id");
                                $req->bindParam(":article", $_GET['article']);
                                $req->bindParam(":user_id", $_SESSION['userid']);
                                $req->execute();
                                $resultat = $req->fetchAll(PDO::FETCH_ASSOC);

                                if($resultat) {
                                    echo '<div><label for="article-classification">Classification : </label><select name="article-classification" required>';
                                    foreach($classifications as $id => $nom) { 
                                        if((int)$resultat[0]['classification'] == $id) {
                                            echo '<option value="' . $id .'" selected>' . $nom . '</option>'; 
                                        } else {
                                            echo '<option value="' . $id .'">' . $nom . '</option>'; 
                                        }
                                        
                                    }
                                    echo '</select></div>';
                                    $filetitle = $resultat[0]['titre'];

                                    echo '<div><input type="text" name="article-titre" value="' . $resultat[0]['titre'] . '"></div>';
                                    echo '<div><textarea name="article-resume" placeholder="Résumé de l\'article (200 cacactères) ..." class="article-resume-input" maxlength="200">' . str_replace("<br />", "", $resultat[0]['resume']) . '</textarea></div>';
                                }
                            }
                            echo "<div><h1>" . $filetitle . "</h1></div>";
                            echo '<div><textarea name="page-content" placeholder="Contenu de l\'article (MarkDown) ...">' . str_replace("<br />", "", $contenu) . '</textarea></div>';
                            echo '<div><input type="submit" value="Publier"></div></form>';
                            if($resultat) {
                                echo '<form action="?article=' . $_GET['article'] . '" method="post" enctype="multipart/form-data">';
                                echo '<input type="file" name="miniature">';
                                echo '<input type="submit" value="Mettre à jour la Miniature">';
                                echo '</form></div>';
                            }
                        } else {
                            if($_SESSION['role'] >= 3) {
                                echo "<div><div><h2>Pages</h2></div>";
                                echo "<div>";
                                $pages = scandir($wwwroot . "/content/");
                                foreach($pages as $page) {
                                    if($page != "." && $page != "..") {
                                        if (is_file($wwwroot . "/content/" . $page)) {
                                            echo "<a href='?page=" . pathinfo($page, PATHINFO_FILENAME) . "'><div class='button'>" . pathinfo($page, PATHINFO_FILENAME) . "</div></a>";
                                        }
                                    }
                                }
                                echo "</div></div><div>";
                            }
                            echo "<div><h2>Articles</h2></div>";
                            echo "<form action='' method='get'><input type='text' placeholder='Article' name='search'><input type='submit' value='Rechercher'></form>";

                            $bdd = connect($dbhost, $dbname, $dbuser, $dbpass);
                            $condition = "";
                            if(isset($_GET['search'])) {
                                $search = "%" . htmlspecialchars($_GET['search']) . "%";
                                $condition =  "AND (titre LIKE '" . $search . "' OR ID LIKE '" . $search . "' OR auteur LIKE '" . $search . "') ";
                            }
                            $req = $bdd->prepare("SELECT ID, titre, date, image, resume FROM articles WHERE auteur = :user_id ORDER BY date DESC LIMIT 10"); 
                            $req->bindParam(":user_id", $_SESSION['userid']);
                            $req->execute();
                            $resultat = $req->fetchAll(PDO::FETCH_ASSOC);

                            if ($resultat) {
                                foreach($resultat as $row) {
                                    $date = strtotime($row['date']);
                                    echo '<div class="article-preview">';
                                    echo '<div class="article-illustration">';
                                    echo '<a href="?article=' . $row['ID'] . '" class="article-link"><img src="' . $row['image'] . '" class="article-miniature"></a>';
                                    echo '</div>';
                                    echo '<div class="article-details">';
                                    echo '<div class="article-data">n° ' . $row['ID'] . ' | ' . date('d/m/Y', $date) . '</div>';
                                    echo '<a href="?article=' . $row['ID'] . '" class="article-link">';
                                    echo '<div class="article-titre">' . $row['titre'] . '</div>';
                                    echo '</a>';
                                    echo '<div class="article-resume">' . $row['resume'] . '</div>';
                                    echo '</div>';
                                    echo '</div>';
                                }
                            }

                            echo "</div>";
                        }
                    ?>
                </div>
                <?php 
                if(isset($contenu)) {
                    echo '<form action=?article=' . $filename . ' method="post"><div><input type="submit" name="deletefile" value="Supprimer"></div></form>';
                }
                ?>
            </div>
        </div>
    </main>
    <footer>
        <div class="content">
            <div>
                <div><?=$copyright?></div>
            </div>
        </div>
    </footer>
</body>
</html>