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

if (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] == 0) {
    // Chemins et noms de fichiers
    $tempPath = $_FILES['profile_picture']['tmp_name'];
    $path = '/src/pp/'. $_SESSION['userid'] .'.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 = 128;
        $newHeight = 128;
        $imageResized = imagecreatetruecolor($newWidth, $newHeight);
        $imageOriginal = imagecreatefromstring(file_get_contents($tempPath));
        imagecopyresampled($imageResized, $imageOriginal, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
        imagealphablending($imageResized, false);
        imagesavealpha($imageResized, true);

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

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

        $bdd = connect($dbhost, $dbname, $dbuser, $dbpass);
        $req = $bdd->prepare("UPDATE users SET profile_picture = :user_pp WHERE ID = :user_id");
        $req->bindParam(":user_pp", $webPath);
        $req->bindParam(":user_id", $_SESSION['userid']);
        if($req->execute()) {
            $status = "PP mise à jour";
        } else {
            $status = "Erreur SQL";
        }
    } else {
        $status = "Le fichier doit être au format PNG ou JPG";
    }
}

if (isset($_FILES['banner']) && $_FILES['banner']['error'] == 0) {
    // Chemins et noms de fichiers
    $tempPath = $_FILES['banner']['tmp_name'];
    $path = '/src/banner/'. $_SESSION['userid'] .'.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 = 800;
    $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 users SET banner = :user_banner WHERE ID = :user_id");
    $req->bindParam(":user_banner", $webPath);
    $req->bindParam(":user_id", $_SESSION['userid']);
    if($req->execute()) {
        $status = "Banière mise à jour";
    } else {
        $status = "Erreur SQL";
    }
    } else {
        $status = "Le fichier doit être un PNG ou JPG";
    }
}

if(isset($_POST['user_display_name']) && isset($_POST['user_name']) && isset($_POST['user_bio'])) {
    $bdd = connect($dbhost, $dbname, $dbuser, $dbpass);
    $req = $bdd->prepare("SELECT ID FROM users WHERE username = :user_name AND NOT ID = :user_id");
    $req->bindParam(":user_name", htmlspecialchars($_POST['user_name']));
    $req->bindParam(":user_id", $_SESSION['userid'], PDO::PARAM_INT);
    $req->execute();
    $resultat = $req->fetchAll(PDO::FETCH_ASSOC);
    if($resultat) {
        $status = "Erreur, le nom d'utilisateur existe déjà.";
    } else {
        $bdd = connect($dbhost, $dbname, $dbuser, $dbpass);
        $req = $bdd->prepare("UPDATE users SET username = :user_name, display_name = :user_display_name, bio = :user_bio WHERE ID = :user_id");
        $req->bindParam(":user_name", htmlspecialchars($_POST['user_name']));
        $req->bindParam(":user_display_name", htmlspecialchars($_POST['user_display_name']));
        $req->bindParam(":user_bio", htmlspecialchars($_POST['user_bio']));
        $req->bindParam(":user_id", $_SESSION['userid']);
        if($req->execute()) {
            $status = "Informations mises à jour";
            $_SESSION['username'] = htmlspecialchars($_POST['user_name']);
            $_SESSION['display_name'] = htmlspecialchars($_POST['user_display_name']);
        } else {
            $status = "Erreur, les informations n'ont pas pu être mises à jour.";
        }
    }
}

$bdd = connect($dbhost, $dbname, $dbuser, $dbpass);
$req = $bdd->prepare("SELECT ID, username, creation_date, display_name, role, profile_picture, banner, bio FROM users WHERE ID = :user_id");
$req->bindParam(":user_id", $_SESSION['userid']);
$req->execute();
$resultat = $req->fetchAll(PDO::FETCH_ASSOC);

if($resultat) {
    $user_id = $resultat[0]['ID'];
    $user_name = $resultat[0]['username'];
    $user_creation_date = $resultat[0]['creation_date'];
    $user_display_name = $resultat[0]['display_name'];
    $user_role = $resultat[0]['role'];
    $user_pp = $resultat[0]['profile_picture'] == NULL ? "https://abs.twimg.com/sticky/default_profile_images/default_profile_400x400.png" : $resultat[0]['profile_picture'];
    $user_pp_url = $resultat[0]['profile_picture'];
    $user_banner = $resultat[0]['banner'] = NULL ? "./src/img/empty.jpg" : $resultat[0]['banner'];
    $user_bio = $resultat[0]['bio'];
} else {
    die("Erreur, utilisateur introuvable");
}
?>
<!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?>
            }
            <?php 
            for ($i = 0; $i < count($themes_dark); $i++) {
                echo "#palette" . $i . " { ";
                echo $themes_dark[$i];
                echo " } ";
            }
            ?>
        } 
        @media (prefers-color-scheme: light) {
            .body {
                <?=$theme_light?>
                }
            <?php 
            for ($i = 0; $i < count($themes_light); $i++) {
                echo "#palette" . $i . " { ";
                echo $themes_light[$i];
                echo " } ";
            }
            ?>
        }

        .content {
            padding: 0;
            width: 100%;
        }

        .user-banner {
            <?php
            if (empty($user_banner)) {
                echo "background-color: black";
            } else {
                echo "background-image: url('" . $user_banner . "');";
            }
            ?>
        }

        .certification {
            fill: <?php echo $user_role > 0 ? $certif_colors[$user_role] : "#000000"?>;
        }
    </style>
    <link rel="icon" href="./src/img/favicon.ico">
    <title><?=$title?></title>
</head>
<body class="body">
    <header>
        <div class="pancontent">
            <div class="athena-container">
                <a href="<?=$root?>" class="athena-link">
                    <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 class="user-main-profile">
                    <form action="#" method="post">
                        <div class="user-banner"></div>
                        <div class="user-header">
                            <div class="user-content">
                                <div class="user-pp"><img src="<?=$user_pp?>" class="user-pp-image"></div>
                                <div><a href="user.php?user=<?=$user_name?>" class="button">Voir le profil publique</a></div>
                                <div class="status"><?=$status?></div>
                                <div class="user-info">
                                    <div class="names">
                                        <div class="display-name"><input type="text" name="user_display_name" value="<?=$user_display_name?>" required/></div>
                                        <div class="username"><input type="text" name="user_name" value="<?=$user_name?>" required/></div>
                                    </div>
                                    <div><textarea class="bio-input" name="user_bio" placeholder="Bio..." maxlength="100"><?=$user_bio?></textarea></div>
                                    <div><input type="submit" value="Mettre à jour les informations"></div>
                                    </form>
                                    <div>
                                        <form action="#" method="post" enctype="multipart/form-data">
                                            <input type="file" name="profile_picture">
                                            <input type="submit" value="Mettre à jour la PP">
                                        </form>
                                    </div>
                                    <div>
                                        <form action="#" method="post" enctype="multipart/form-data">
                                            <input type="file" name="banner">
                                            <input type="submit" value="Mettre à jour la banière">
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="user-articles">
                            <div class="user-content">
                            <div><a href="upload.php" class="button">Publier un article</a></div>
                            <?php
                                $bdd = connect($dbhost, $dbname, $dbuser, $dbpass);
                                $search = isset($_GET['search']) ? "%" . htmlspecialchars($_GET['search']) . "%" : "%%";
                                $req = $bdd->prepare("SELECT ID, titre, date, image, resume FROM articles WHERE (titre LIKE :search OR ID LIKE :search OR auteur LIKE :search) AND classification <= :accreditation AND auteur = :user_id ORDER BY date DESC");
                                $req->bindParam(":search", $search);
                                $req->bindParam(":accreditation", $_SESSION['accreditation']);
                                $req->bindParam(":user_id", $user_id);
                                $req->execute();
                                $resultat = $req->fetchAll(PDO::FETCH_ASSOC);
                                echo "<h1>Editer un article</h1>";
                                echo "<form action='' method='get'><input type='text' placeholder='Article' name='search'><input type='submit' value='Rechercher'></form>";

                                if ($resultat) {
                                    foreach($resultat as $row) {
                                        $date = strtotime($row['date']);
                                        echo '<div class="article-preview">';
                                        echo '<div class="article-illustration">';
                                        echo '<a href="editpage.php?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="editpage.php?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> ';
                                    }
                                } else {
                                    echo "Vous n'avez publié aucun article...";
                                }
                            ?>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </main>
    <footer>
        <div class="content">
            <div>
                <div><?=$copyright?></div>
            </div>
        </div>
    </footer>
</body>
</html>