<?php
require_once __DIR__.'/includes/config.php';
require_login();

$db = db();
$msg = '';
$erro = '';
$role = $_SESSION['role'] ?? 'admin';
$owner_id = (int)($_SESSION['owner_id'] ?? 0);
$username = $_SESSION['username'] ?? ($_SESSION['name'] ?? '');

function perfil_get_row($db, $role, $owner_id, $username){
    if($role === 'admin'){
        $st=$db->prepare('SELECT * FROM users WHERE username=:u LIMIT 1');
        $st->bindValue(':u',$username,SQLITE3_TEXT);
        return $st->execute()->fetchArray(SQLITE3_ASSOC) ?: null;
    }
    if($role === 'revenda'){
        $st=$db->prepare('SELECT * FROM revendas WHERE id=:id LIMIT 1');
        $st->bindValue(':id',$owner_id,SQLITE3_INTEGER);
        return $st->execute()->fetchArray(SQLITE3_ASSOC) ?: null;
    }
    if($role === 'subrevenda'){
        $st=$db->prepare('SELECT * FROM sub_revendas WHERE id=:id LIMIT 1');
        $st->bindValue(':id',$owner_id,SQLITE3_INTEGER);
        return $st->execute()->fetchArray(SQLITE3_ASSOC) ?: null;
    }
    return null;
}

if($_SERVER['REQUEST_METHOD']==='POST'){
    $atual = (string)($_POST['atual'] ?? '');
    $nova = (string)($_POST['nova'] ?? '');
    $conf = (string)($_POST['conf'] ?? '');
    $row = perfil_get_row($db, $role, $owner_id, $username);

    if(!$row){
        $erro = 'Perfil não encontrado.';
    } elseif(!password_ok($atual, $row['password'] ?? ($row['senha'] ?? ''))){
        $erro = 'Senha atual incorreta.';
    } elseif(strlen($nova) < 4){
        $erro = 'A nova senha precisa ter pelo menos 4 caracteres.';
    } elseif($nova !== $conf){
        $erro = 'A confirmação da senha não confere.';
    } else {
        $hash = password_hash($nova, PASSWORD_DEFAULT);
        if($role === 'admin'){
            $st=$db->prepare('UPDATE users SET password=:p WHERE id=:id');
            $st->bindValue(':id',(int)$row['id'],SQLITE3_INTEGER);
        } elseif($role === 'revenda'){
            $st=$db->prepare('UPDATE revendas SET senha=:p, updated_at=CURRENT_TIMESTAMP WHERE id=:id');
            $st->bindValue(':id',$owner_id,SQLITE3_INTEGER);
        } else {
            $st=$db->prepare('UPDATE sub_revendas SET senha=:p, updated_at=CURRENT_TIMESTAMP WHERE id=:id');
            $st->bindValue(':id',$owner_id,SQLITE3_INTEGER);
        }
        $st->bindValue(':p',$hash,SQLITE3_TEXT);
        $st->execute();
        $msg = 'Senha alterada com sucesso.';
    }
}

include __DIR__.'/includes/header.php';
?>
<div class="card" style="max-width:620px">
    <h2>🔑 Trocar Senha</h2>
    <p class="muted">Altere a senha do seu acesso ao painel.</p>
    <?php if($msg): ?><p class="ok"><?=h($msg)?></p><?php endif; ?>
    <?php if($erro): ?><p class="bad"><?=h($erro)?></p><?php endif; ?>
    <form method="post">
        <label>Senha atual</label>
        <input type="password" name="atual" required>
        <label>Nova senha</label>
        <input type="password" name="nova" required>
        <label>Confirmar nova senha</label>
        <input type="password" name="conf" required>
        <p><button class="btn">Salvar Senha</button> <a class="btn dark" href="logout.php">🚪 Sair</a></p>
    </form>
</div>
<?php include __DIR__.'/includes/footer.php'; ?>
