<?php
/**
 * helpers.php - লগইন চেক ও ইউজারের Key নেয়া
 */
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/encryption.php';

function requireLogin() {
    session_name(SESSION_NAME);
    if (session_status() === PHP_SESSION_NONE) session_start();
    if (empty($_SESSION['user_id'])) {
        header('Location: index.php');
        exit;
    }
    return (int) $_SESSION['user_id'];
}

function getUserId() {
    session_name(SESSION_NAME);
    if (session_status() === PHP_SESSION_NONE) session_start();
    return isset($_SESSION['user_id']) ? (int) $_SESSION['user_id'] : null;
}

function getUserKeys($userId) {
    global $pdo;
    $st = $pdo->prepare('SELECT api_key_encrypted, secret_key_encrypted FROM user_keys WHERE user_id = ?');
    $st->execute([$userId]);
    $row = $st->fetch(PDO::FETCH_ASSOC);
    if (!$row) return null;
    $api = decryptKey($row['api_key_encrypted']);
    $secret = decryptKey($row['secret_key_encrypted']);
    if (!$api || !$secret) return null;
    return ['apiKey' => $api, 'secretKey' => $secret];
}
?>
