<?php
define('FORMORE_SECRET_KEY', '9LUcqkH6:C7k&}$c%y.?my{mkR:]:@QE[ND2p?5%Az-p-J1j#`vrS`bq3(V}b9V');
define('FORMORE_TOKEN_EXPIRY', 31536000);
define('DB_HOST', 'localhost:3306');
define('DB_NAME', 'gqdcvggs_formore');
define('DB_USER', 'gqdcvggs');
define('DB_PASS', 'imaors_management.346980*#@-onlyforcpanel;forchange');

try {
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

function validateFormoreToken($token, $expires, $signature) {
    if (time() > $expires) {
        return false;
    }
    
    $expected_signature = hash_hmac('sha256', $token . $expires, FORMORE_SECRET_KEY);
    
    if (!hash_equals($expected_signature, $signature)) {
        return false;
    }
    
    $data = json_decode(base64_decode($token), true);
    
    if (!$data || !isset($data['user_id']) || !isset($data['email'])) {
        return false;
    }
    
    return $data;
}

function storeUserSession($user_data) {
    global $pdo;
    
    $stmt = $pdo->prepare("
        INSERT INTO formore_sessions (user_id, email, username, profile_picture, expires_at, created_at) 
        VALUES (?, ?, ?, ?, ?, NOW()) 
        ON DUPLICATE KEY UPDATE 
        email = VALUES(email), 
        username = VALUES(username), 
        profile_picture = VALUES(profile_picture), 
        expires_at = VALUES(expires_at), 
        updated_at = NOW()
    ");
    
    $stmt->execute([
        $user_data['user_id'],
        $user_data['email'],
        $user_data['username'],
        $user_data['profile_picture'],
        date('Y-m-d H:i:s', $user_data['expires'])
    ]);
    
    $_SESSION['formore_user_id'] = $user_data['user_id'];
    $_SESSION['formore_email'] = $user_data['email'];
    $_SESSION['formore_username'] = $user_data['username'];
    $_SESSION['formore_profile_picture'] = $user_data['profile_picture'];
    $_SESSION['formore_expires'] = $user_data['expires'];
}

function checkExistingSession() {
    global $pdo;
    
    if (!isset($_SESSION['formore_user_id']) || !isset($_SESSION['formore_expires'])) {
        return false;
    }
    
    if (time() > $_SESSION['formore_expires']) {
        unset($_SESSION['formore_user_id']);
        unset($_SESSION['formore_email']);
        unset($_SESSION['formore_username']);
        unset($_SESSION['formore_profile_picture']);
        unset($_SESSION['formore_expires']);
        return false;
    }
    
    $stmt = $pdo->prepare("SELECT * FROM formore_sessions WHERE user_id = ? AND expires_at > NOW()");
    $stmt->execute([$_SESSION['formore_user_id']]);
    
    if ($stmt->rowCount() > 0) {
        return true;
    }
    
    return false;
}

function redirectToLogin() {
    header('Location: https://idsma.imators.com/login.php?formore-connection-protocole');
    exit;
}
?>