<?php

if (!function_exists('com_create_guid')) {
  function com_create_guid() {
    return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
        mt_rand( 0, 0xffff ),
        mt_rand( 0, 0x0fff ) | 0x4000,
        mt_rand( 0, 0x3fff ) | 0x8000,
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
    );
  }
}

include('config_local.php');

if (! ($db = new PDO("mysql:host=$mysql_host;port=$mysql_port;dbname=$mysql_schema",$mysql_user,$mysql_pwd,array( PDO::ATTR_PERSISTENT => false)))) {
  die($err);
}  

$db -> exec('SET CHARACTER SET utf8');

$auth_token = $_COOKIE["auth-token"];

$timestamp = 0;

if ($auth_token) {

  $sql = "
    SELECT UNIX_TIMESTAMP(MAX(expires)) timestamp FROM tokens WHERE str=:s and expires>now()
  ";
  
  $q = $db -> prepare( $sql );
  $q -> bindParam(':s',$auth_token,PDO::PARAM_INT);
  $q -> execute();

  $res = [];

  $row = $q -> fetch(PDO::FETCH_ASSOC);
  $timestamp = $row['timestamp'];

} 

if ($timestamp) {
  setcookie("auth-token",$auth_token,$timestamp);
} else {
  $auth_token = com_create_guid();
  $timestamp = time()+86400*365;
  setcookie("auth-token",$auth_token,$timestamp);
  $sql = "
    INSERT INTO tokens(str,description,expires) VALUES (:token,:descr,FROM_UNIXTIME(:expires)) 
  ";
  $q = $db -> prepare( $sql );
  $q -> bindParam(':token',$auth_token,PDO::PARAM_STR);
  $descr = $_SERVER["PHP_AUTH_USER"]." from ".$_SERVER["REMOTE_ADDR"]." at ".date('m/d/Y h:i:s a', time());
  $q -> bindParam(':descr',$descr,PDO::PARAM_STR);
  $q -> bindParam(':expires',$timestamp,PDO::PARAM_INT);
  $db -> beginTransaction();
  $q -> execute();
  $db -> commit();
  
}

print $auth_token;

?>