<?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 PASSWORD ONLY
// =======================
if (isset($_POST['submit'])) {

    $newPassword = $_POST['password'];

    if (empty($newPassword)) {
        echo "<script>alert('Ingrese una contraseña'); window.history.back();</script>";
        exit;
    }

    if (strlen($newPassword) < 3) {
        echo "<script>alert('Password muy corta'); window.history.back();</script>";
        exit;
    }

    $updateData = [
        'password' => $newPassword
    ];

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

    echo "<script>alert('Contraseña actualizada correctamente'); 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> Menu 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>Usuario</label>
                        <input type="text" class="form-control" 
                               value="<?= htmlspecialchars($user['username']) ?>" readonly>
                    </div>

                    <div class="form-group">
                        <label>Nueva Contraseña</label>
                        <input type="password" name="password" class="form-control" 
                               placeholder="Ingrese nueva contraseña" required>

                        <small class="text-muted">
                        Solo puede cambiar la contraseña.
                        </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> GUARDAR
                        </button>
                    </div>

                </form>
            </div>
        </div>
    </div>
</div>

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