<?php
include('includes/header.php');

// =======================
// SECURITY
// =======================
if (!isset($_SESSION['loggedin']) || !isset($_SESSION['name'])) {
    echo "<script>window.location.href='index.php';</script>";
    exit;
}

$username = $_SESSION['name'];
$role = $_SESSION['role'] ?? 'reseller';
$targetTable = ($role === 'master') ? 'user' : 'menualuser';

// =======================
// LOAD USER DATA
// =======================
$userData = $db->select(
    $targetTable,
    '*',
    'username = :u',
    '',
    [':u' => $username]
);

if (!$userData) {
    die("Access denied or user not found.");
}

$user = $userData[0];

// =======================
// UPDATE LOGIC
// =======================
if (isset($_POST['submit'])) {
    $newUsername = trim(sanitize($_POST['username']));
    $newPassword = $_POST['password'];

    // Prevent Usuário Collision
    if ($newUsername !== $username) {
        $check = $db->select($targetTable, 'username', 'username = :u', '', [':u' => $newUsername]);
        if (!empty($check)) {
            echo "<script>alert('Error: Usuário already taken.'); window.history.back();</script>";
            exit;
        }
    }

    $updateData = ['username' => $newUsername];

    // UPDATED: No more password hashing. Matches your login script.
    if (!empty($newPassword)) {
        if (strlen($newPassword) < 3) { // Reduced min length for your preference
            echo "<script>alert('Password too short'); window.history.back();</script>";
            exit;
        }
        $updateData['password'] = $newPassword; 
    }

    $db->update(
        $targetTable,
        $updateData,
        'username = :u',
        [':u' => $username]
    );

    // Update Session so you stay logged in with the new name
    $_SESSION['name'] = $newUsername;

    echo "<script>alert('Profile updated successfully! Use your new credentials next time.'); window.location.href='user.php';</script>";
    exit;
}
?>

<div class="col-md-6 mx-auto">
    <div class="card-body">
        <div class="card text-white ctluser-main" style="background: rgba(0,0,0,0.5); border: 1px solid rgba(255,255,255,0.1);">
            <div class="card-header ctheading text-center">
                <h2><i class="fa fa-user-cog"></i> Meu Perfil</h2>
                <span class="badge badge-info"><?= role_label_ptbr($role) ?></span>
            </div>

            <div class="card-body">
                <form method="post">
                    <div class="form-group">
                        <label>Usuário</label>
                        <input type="text" name="username" class="form-control" 
                               value="<?= htmlspecialchars($user['username']) ?>" required>
                    </div>

                    <div class="form-group">
                        <label>Nova Senha</label>
                        <input type="text" name="password" class="form-control" 
                               placeholder="Leave blank to keep current password">
                        <small class="text-muted">Digite uma nova senha somente se quiser alterá-la.</small>
                    </div>

                    <div class="text-center mt-4">
                        <button type="submit" name="submit" class="btn btn-info px-5">
                            <i class="fa fa-save"></i> Salvar Alterações
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include('includes/footer.php'); ?>