<?php
//  Generate and return a client id.  Expect a name (clientName) and session (session name)


require("phpVars.php");

//header("Content-Type: text/plain");
$idate =time();

  $sessName='';
  $clientName='';
  $content='';
  foreach ($_REQUEST as $vname=>$oof) {
     $avar=trim(strtoupper($vname)) ;
     $toof=trim($oof);
     if ($avar=='SESSION')  {
        $sessName=$toof;
     }
     if ($avar=='USERNAME' || $avar=='clientName' || $avar='NAME') {
         $clientName=$toof;
     }
  }      // foreach

if ($sessName=='') {
   print '- Error. No session= in call to assignClientId.php ';
   exit ;
}
if ($clientName=='') {
   print '- Error. No username= in call to assignClientId.php ';
   exit ;
}

// does this session exist?
$dafile=$sessions_dir . $sessName . '.XML' ;
$isfile=file_exists($dafile);
if (!$isfile) {
  print '- Error. No such session ' . $sessName . ' (joinSession.php) ';
  exit ;
}


// ===  connect to mysql databases
$link=mysql_connect('localhost','dsurveyAdmin','admin');
if (!$link) {
   print ' - Error. Could not connect to mysql (with username=`dsurveyAdmin` and password=`admin`): ' . mysql_error();
   exit ;
}

$mdata=$hdrMysql . $sessName ;
$qq=mysql_select_db($mdata, $link);
if (!$qq) {
   print '- Error. Unable to select mysql database ' . $mdata . ': '  . mysql_error();
   mysql_close($link);
   return 0;
}

// add this entry to clientid table

$sql="INSERT INTO assignCID (servertime,clientName)
              VALUES
     ('$idate','$clientName') ";

$qq=mysql_query($sql,$link);
if (!$qq) {
   print 'Error. Unable to add entry to ASSIGNCID  table in mysql database ' . $mdata . ': '  . mysql_error();
   return 0;
}

$cid=mysql_insert_id();         // get the clientid (auto_incremented) just assigned

print $cid.' '.$clientName ;
exit ;


/*===
  print count($otherVars) . " \n ";
$stuff="Session= $sessName \n Namecheck=$nameCheck \n clientid = $clientid \n Others  " . count($otherVars);
for ($ith=0;$ith<count($otherVars);$ith++) {
  $goose=$otherVars[$ith];
  $aline=" $goose[0]  = $goose[1]  \n " ;
  $stuff .= $aline ;
}
===*/

?>