<?php
session_start();
require $_SERVER["DOCUMENT_ROOT"].'/includes/db.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: /login');
    exit;
}

$user_id = (int)$_SESSION['user_id'];

/**
 * TOKEN (HASH)
 */
$token = hash_hmac(
    'sha256',
    $user_id . '|' . time() . '|' . bin2hex(random_bytes(16)),
    'INPAY_SIGN_SECRET_2026'
);

$expiry = date('Y-m-d H:i:s', time() + 600); // 10 daqiqa

/**
 * TOKEN NI USERS JADVALIGA YOZAMIZ
 */
$stmt = $conn->prepare("
    UPDATE users 
    SET sign_token = ?, sign_token_expiry = ?
    WHERE id = ?
    LIMIT 1
");
$stmt->bind_param("ssi", $token, $expiry, $user_id);
$stmt->execute();
$stmt->close();

/**
 * REDIRECT → local control_base
 */
$host = $_SERVER['HTTP_HOST'] ?? 'inpay.avtopay.uz';
$redirectUrl = 'https://' . $host . '/control_base/identification/passport/?token=' . urlencode($token);
header("Location: $redirectUrl");
exit;
