<?php
require_once('includes/application_top.php');
require_once('admin/includes/config.ebayapi.inc.php');
$env = (isset($_REQUEST['environment']) and $_REQUEST['environment'] == 'sandbox') ? 'sandbox' : 'production';
if( !isset($_SESSION['ebay_auth_session_id']) or empty($_SESSION['ebay_auth_session_id']) or ($_REQUEST['sessionid'] != $_SESSION['ebay_auth_session_id'])){
    die('<b>Fehler:</b> Unauthorisierte Session<br /><br /><a href="admin/token.php">Weiter</a>');
}
$parameters = ['user'=>$_REQUEST['username']];
$exists_query_raw = sprintf("SELECT count(*) as anzahl FROM ebay_auth WHERE environment='%s' and user=:user",
    $env
);
$exists = yes_query($exists_query_raw,$parameters,true);
if($_REQUEST['token'] != '' and isset($_REQUEST['username']) and $_REQUEST['username'] != ''){
    $parameters = [
        'token'=>$_REQUEST['token'],
        'expire'=>$_REQUEST['expire'],
        'user'=>$_REQUEST['username']
    ];
    if($exists['anzahl']>0){
        $update_sql = sprintf(
            "UPDATE ebay_auth SET ebaytkn=:token, tknexp=:expire WHERE environment='%s' and user=:user",
            $env,
        );
        yes_query($update_sql,$parameters);
    }else{
        $insert_sql = sprintf(
            "INSERT INTO ebay_auth SET ebaytkn=:token, tknexp=:expire, environment='%s',user=:user",
            $env
        );
        yes_query($insert_sql,$parameters);
    }
}else{
	die("Token konnte nicht gespeichert werden. Kontaktieren Sie das YES Team");
}
xtc_redirect('admin/token.php');
