<?php
// Usage:
//   php set-admin-password.php "sua_senha"

$pass = $argv[1] ?? '';
if ($pass === '') {
    fwrite(STDERR, "Uso: php set-admin-password.php \"sua_senha\"\n");
    exit(1);
}

try {
    $dbPath = __DIR__ . '/admin.db';
    $pdo = new PDO('sqlite:' . $dbPath);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $pdo->exec("CREATE TABLE IF NOT EXISTS settings (
        key TEXT PRIMARY KEY,
        value TEXT NOT NULL,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    $hash = password_hash($pass, PASSWORD_DEFAULT);

    $stmt = $pdo->prepare(
        'INSERT INTO settings (key, value, updated_at) VALUES (:k, :v, CURRENT_TIMESTAMP)
         ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP'
    );

    $stmt->execute([
        ':k' => 'admin_password_hash',
        ':v' => $hash
    ]);

    echo "OK\n";
} catch (Exception $e) {
    fwrite(STDERR, "Erro: " . $e->getMessage() . "\n");
    exit(1);
}
