<?php
require("../../include/variables.php");
require("../../include/functions.php");
$pdo = sqlConnect($sqlDatabaseHost, $sqlDatabaseName, $sqlDatabaseUser, $sqlDatabasePass);

if (isset($_FILES['newPP']) && $_FILES['newPP']['error'] == 0) {
    $tempImagePath = $_FILES['newPP']['tmp_name'];
    $ImagePath = 'assets/pp/' . $_SESSION['userID'] . '.png';
    $rootImagePath = $rootFilePath . 'html/' . $ImagePath;
    $imageURL = $rootPageURL . $ImagePath;

    list($width, $height) = getimagesize($tempImagePath);

    $imageInfo = getimagesize($tempImagePath);

    if ($imageInfo[2] === IMAGETYPE_PNG || $imageInfo[2] === IMAGETYPE_JPEG) {
        $imageWidth = 128;
        $imageHeight = 128;
        $imageResized = imagecreatetruecolor($imageWidth, $imageHeight);
        $imageOriginal = imagecreatefromstring(file_get_contents($tempImagePath));

        imagecopyresampled($imageResized, $imageOriginal, 0, 0, 0, 0, $imageWidth, $imageHeight, $width, $height);
        imagealphablending($imageResized, false);
        imagesavealpha($imageResized, $rootPath);

        imagepng($imageResized, $rootImagePath);

        imagedestroy($imageOriginal);
        imagedestroy($imageResized);

        $sqlRequest = "UPDATE users SET profile_picture = :userPP WHERE ID = :userID";
        $request = $pdo->prepare($sqlRequest);
        $request->bindParam(":userPP", $imageURL);
        $request->bindParam(":userID", $_SESSION['userID']);
        if($request->execute()) {
            $status = "Photo de profil mise à jour";
        } else {
            $status = "Erreur SQL";
        }
    } else {
        $status = "Le fichier doit être au format PNG ou JPG";
    }
}

if (isset($_FILES['newBanner']) && $_FILES['newBanner']['error'] == 0) {
    $tempImagePath = $_FILES['newBanner']['tmp_name'];
    $ImagePath = 'assets/banners/' . $_SESSION['userID'] . '.png';
    $rootImagePath = $rootFilePath . 'html/' . $ImagePath;
    $imageURL = $rootPageURL . $ImagePath;

    list($width, $height) = getimagesize($tempImagePath);

    $imageInfo = getimagesize($tempImagePath);

    if ($imageInfo[2] === IMAGETYPE_PNG || $imageInfo[2] === IMAGETYPE_JPEG) {
        $imageWidth = 800;
        $imageHeight = ($height / $width) * $imageWidth;
        $imageResized = imagecreatetruecolor($imageWidth, $imageHeight);
        $imageOriginal = imagecreatefromstring(file_get_contents($tempImagePath));

        imagecopyresampled($imageResized, $imageOriginal, 0, 0, 0, 0, $imageWidth, $imageHeight, $width, $height);
        imagealphablending($imageResized, false);
        imagesavealpha($imageResized, $rootPath);

        imagepng($imageResized, $rootImagePath);

        imagedestroy($imageOriginal);
        imagedestroy($imageResized);

        $sqlRequest = "UPDATE users SET banner = :userBanner WHERE ID = :userID";
        $request = $pdo->prepare($sqlRequest);
        $request->bindParam(":userBanner", $imageURL);
        $request->bindParam(":userID", $_SESSION['userID']);
        if($request->execute()) {
            $status = "Banière mise à jour";
        } else {
            $status = "Erreur SQL";
        }
    } else {
        $status = "Le fichier doit être au format PNG ou JPG";
    }
}

if (isset($_POST['userDisplayName']) && isset($_POST['userBio'])) {
    if(preg_match('!\S!u', $_POST['userDisplayName']) && preg_match('!\S!u', $_POST['userBio'])) {
        $sqlRequest = "UPDATE users SET display_name = :userDisplayName, bio = :userBio WHERE ID = :userID";
        $request = $pdo->prepare($sqlRequest);
        $request->bindParam(":userDisplayName", htmlspecialchars($_POST['userDisplayName']));
        $request->bindParam(":userBio", htmlspecialchars($_POST['userBio']));
        $request->bindParam(":userID", $_SESSION['userID']);
        if($request->execute()) {
            $status = "Informations mises à jour";
            $_SESSION['userDisplayName'] = htmlspecialchars($_POST['userDisplayName']);
        }
    }
}

$request = $pdo->prepare("SELECT ID, username, display_name, profile_picture, banner, bio FROM users WHERE ID = :userID");
$request->bindParam(":userID", $_SESSION['userID']);
$request->execute();
$result = $request->fetchAll(PDO::FETCH_ASSOC);

if($result) {
    $userID = $result[0]['ID'];
    $userName = $result[0]['username'];
    $userDisplayName = $result[0]['display_name'];
    $userPPURL = $result[0]['profile_picture'] == NULL ? "https://abs.twimg.com/sticky/default_profile_images/default_profile_400x400.png" : $result[0]['profile_picture'];
    $userBanner = $result[0]['banner'] = NULL ? "" : $result[0]['banner'];
    $userBio = $result[0]['bio'];
} else {
    header("Location: /login?p=account");
    die("Erreur, utilisateur introuvable");
}

?>

<!DOCTYPE html>
<html lang="fr">

    <head>
        <?php fillHead($rootPageURL, $pageTitle, $darkTheme, $lightTheme);?>
        <style>
            .content {
                padding: 0;
                width: 100%;
            }

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

            .user-profile .bio-input {
                max-height: 3em;
                width:  80%;
            }

            .user-header .text-input,  .user-header textarea {
                background-color: var(--background);
            }

            .user-info .text-input label {
                width:  0;
            }

            .image-input .file-input {
                display: inline-block;
                margin-right: 1em;
            }

            .image-input button {
                display: inline-block;
            }

            .user-info form {
                margin: 1em 0;
            }
        </style>
    </head>

    <body class="body">

        <header>
            <div class="panel-content">
                <?php fillHeader($rootPageURL, $headerTitle, $headerSubtitle);?>
            </div>
        </header>

        <nav>
            <div class="panel-content">
                <?php fillNav($rootPageURL);?>
            </div>
        </nav>

        <main>
            <div class="content">
                <div class="user-profile">
                        <div class="user-banner"></div>
                        <div class="user-header">
                            <div class="user-header-content">
                                <div class="user-pp"><img src="<?=$userPPURL?>"></div>
                                <a href="/users?u=<?=$userName?>" class="button">Voir le profil publique</a>
                                <div class="status"><?=$status?></div>
                                <div class="user-info">
                                    <form action="#" method="post">
                                    <div class="names">
                                        <div class="display-name">
                                            <?php  textInput("text", "", "userDisplayName", "Nom d'affichage", $userDisplayName) ?>
                                        </div>
                                    </div>
                                    <div><textarea class="bio-input" name="userBio" placeholder="Bio..." maxlength="100"><?=$userBio?></textarea></div>
                                    <div><button type="submit">Mettre à jour</button></div>
                                    </form>
                                    <div>
                                        <form action="#" method="post" enctype="multipart/form-data">
                                            <div class="image-input">
                                            <?php fileInput("newPP")?>
                                            <input type="submit" value="Changer la PP" class="button">
                                            </div>
                                        </form>
                                    </div>
                                    <div>
                                        <form action="#" method="post" enctype="multipart/form-data">
                                            <div class="image-input">
                                            <?php fileInput("newBanner")?>
                                            <input type="submit" value="Changer la banière" class="button">
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="user-articles">
                            <div class="user-content">
                            <div><a href="/upload" class="button">Rédiger un article</a></div>
                                <?php
                                    $search = isset($_GET['search']) ? "%" . htmlspecialchars($_GET['search']) . "%" : "%%";
                                    $request = $pdo->prepare("SELECT ID, title, date, miniature, resume FROM articles WHERE (title LIKE :search OR ID LIKE :search) AND author = :userID ORDER BY date DESC");
                                    $request->bindParam(":search", $search);
                                    $request->bindParam(":userID", $userID);
                                    $request->execute();
                                    $result = $request->fetchAll(PDO::FETCH_ASSOC);
                                    echo ('<h1>Vos articles</h1>');
                                    echo ('<form action="#" method="get">');
                                    $shapePath = '<path d="M10.25 3.75c-3.59 0-6.5 2.91-6.5 6.5s2.91 6.5 6.5 6.5c1.795 0 3.419-.726 4.596-1.904 1.178-1.177 1.904-2.801 1.904-4.596 0-3.59-2.91-6.5-6.5-6.5zm-8.5 6.5c0-4.694 3.806-8.5 8.5-8.5s8.5 3.806 8.5 8.5c0 1.986-.682 3.815-1.824 5.262l4.781 4.781-1.414 1.414-4.781-4.781c-1.447 1.142-3.276 1.824-5.262 1.824-4.694 0-8.5-3.806-8.5-8.5z"></path>';
                                    textInput("text", $shapePath, "search", "Chercher", "");
                                    echo ('</form>');

                                    if ($result) {
                                        echo('<div class="articles-list">');
                                        listArticles($result, $rootPageURL);
                                        echo ('</div>');
                                    } else {
                                        echo ('Vous n\'avez publié aucun article...');
                                    }
                                ?>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </main>
        <footer>
            <div class="panel-content">
                <?php fillFooter($footerText);?>
            </div>
        </footer>
    </body>
</html>