<?php
session_start();

// Check admin
if (!isset($_SESSION['id']) || !$_SESSION['admin']) {
    header("Location: login.php");
    exit();
}

ini_set("display_errors", 0);
ini_set("display_startup_errors", 0);
error_reporting(32767);

$db = new SQLite3("./api/.anspanel.db");

// Load current admin row
$res = $db->query("SELECT * FROM USERS WHERE ID='1'");
$row = $res->fetchArray(SQLITE3_ASSOC);

$flashHtml = "<div class=\"alert alert-primary\" id=\"flash-msg\"><h4><i class=\"icon fa fa-check\"></i> Profile updated successfully!</h4></div>";

if (isset($_POST["submit"])) {
    $nameIn     = $db->escapeString($_POST["name"]);
    $userIn     = $db->escapeString($_POST["username"]);
    $passIn     = $db->escapeString($_POST["password"]);

    $setParts = [
        "NAME='{$nameIn}'",
        "USERNAME='{$userIn}'",
        "PASSWORD='{$passIn}'"
    ];

    // If a logo file was uploaded, move it and update LOGO column
    if (!empty($_FILES["logo"]["tmp_name"])) {

        // extension du fichier (png par défaut)
        $ext = pathinfo($_FILES["logo"]["name"], PATHINFO_EXTENSION);
        if ($ext === '') {
            $ext = 'png';
        }

        // nom unique du fichier
        $target_dir  = "img2/";
        $fileName    = "logo_" . time() . "." . $ext;
        $target_file = $target_dir . $fileName;

        // déplacement du fichier uploadé
        if (@move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file)) {
            // On enregistre le chemin dans la DB
            $setParts[] = "LOGO='" . $db->escapeString($target_file) . "'";
            // Et dans la session pour affichage immédiat
            $_SESSION["logo"] = $target_file . "?t=" . time();
        }
    }

    $setSql = implode(", ", $setParts);
    $db->exec("UPDATE USERS SET $setSql WHERE ID='1'");

    // Update session username
    $_SESSION["name"] = $userIn;

    header("Location: profile.php?m=" . urlencode($flashHtml));
    exit();
}

// Values for the form
$name = $row["NAME"];
$user = $row["USERNAME"];
$pass = $row["PASSWORD"];

// logo brut venant de la DB (ou fallback par défaut)
$rawLogo = $row["LOGO"];
if (empty($rawLogo)) {
    $rawLogo = "img2/logo.png";
}

// ce qu'on affiche : session (si on vient d'uploader) sinon DB
$logo = isset($_SESSION["logo"]) ? $_SESSION["logo"] : $rawLogo;

include "includes/header.php";
?>

<!-- ===== STYLE SPÉCIFIQUE À LA PAGE PROFIL (PANEL SOMBRE) ===== -->
<style>
    .page-shell-esso{
        padding: 20px 12px 40px;
    }

    .panel-card-esso{
        max-width: 1100px;
        margin: 0 auto;
        border-radius: 28px;
        padding: 28px 30px 34px;
        position: relative;
        background:
            radial-gradient(circle at top, rgba(15,23,42,0.98) 0, #020617 55%, #020617 100%);
        box-shadow: 0 26px 70px rgba(3,7,18,0.95);
        border: 1px solid rgba(148,163,184,0.45);
        color: #e5e7eb;
        overflow: hidden;
    }

    .panel-card-esso::before{
        content:"";
        position:absolute;
        inset:-1px;
        border-radius:inherit;
        background:
            conic-gradient(from 190deg,
                rgba(56,189,248,0.00) 0deg,
                rgba(56,189,248,0.9) 70deg,
                rgba(129,140,248,0.9) 150deg,
                rgba(16,185,129,0.9) 230deg,
                rgba(56,189,248,0.00) 320deg);
        filter: blur(14px);
        opacity:0.95;
        z-index:-1;
    }

    .panel-card-esso h1,
    .panel-card-esso label,
    .panel-card-esso p,
    .panel-card-esso small,
    .panel-card-esso strong{
        color:#e5e7eb !important;
    }

    /* Libellés bleus bien visibles */
    .panel-card-esso label.control-label strong,
    .panel-card-esso .current-logo-label strong{
        color:#22d3ee !important;
        text-shadow:0 0 10px rgba(34,211,238,0.55);
        letter-spacing:0.02em;
    }

    .panel-card-esso .form-text.text-muted{
        color:#9ca3af !important;
    }

    .panel-card-esso code{
        color:#a5b4fc;
        background:rgba(15,23,42,0.85);
        border-radius:6px;
        padding:2px 6px;
    }

    .panel-card-esso img{
        background: radial-gradient(circle at center, rgba(15,23,42,0.9), #020617);
        padding:10px;
    }
</style>

<div class="container-fluid page-shell-esso">
    <div class="panel-card-esso">
        <?php
        if (isset($_GET["m"])) {
            echo urldecode($_GET["m"]);
        }
        ?>
        <h1 class="h3 mb-3 text-gray-200">Update Login</h1>

        <form method="post" enctype="multipart/form-data">
            <div class="row">
                <div class="col-md-8">
                    <div class="form-group">
                        <label class="control-label" for="name"><strong>Name</strong></label>
                        <div class="input-group">
                            <input
                                type="text"
                                class="form-control text-primary"
                                id="name"
                                name="name"
                                value="<?= htmlspecialchars($name, ENT_QUOTES); ?>"
                                placeholder="Enter the name">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="control-label" for="username"><strong>Username</strong></label>
                        <div class="input-group">
                            <input
                                type="text"
                                class="form-control text-primary"
                                id="username"
                                name="username"
                                value="<?= htmlspecialchars($user, ENT_QUOTES); ?>"
                                placeholder="Enter the username">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="control-label" for="password"><strong>Password</strong></label>
                        <div class="input-group">
                            <input
                                type="text"
                                class="form-control text-primary"
                                id="password"
                                name="password"
                                value="<?= htmlspecialchars($pass, ENT_QUOTES); ?>"
                                placeholder="Enter the password">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="control-label" for="logo"><strong>Logo</strong></label>
                        <div class="input-group">
                            <input
                                type="file"
                                class="form-control text-primary"
                                id="logo"
                                name="logo">
                        </div>
                        <small class="form-text text-muted">
                            PNG recommended. It will be saved in <code>img2/</code>.
                        </small>
                    </div>

                    <div class="form-group">
                        <button class="btn btn-success btn-icon-split" name="submit" type="submit">
                            <span class="icon text-white-50"><i class="fas fa-check"></i></span>
                            <span class="text">Update</span>
                        </button>
                    </div>
                </div>

                <div class="col-md-4 d-flex flex-column align-items-center justify-content-center">
                    <p class="current-logo-label"><strong>Current Logo</strong></p>
                    <img src="<?= htmlspecialchars($logo, ENT_QUOTES); ?>" alt="Logo" style="max-width:120px; border-radius:12px;">
                </div>
            </div>
        </form>
    </div>
</div>

<?php
include "includes/footer.php";
require "includes/ans.php";
echo "</body>\n";
?>
