<?php

if(isset($_POST['action'])){
        if ($_POST['action'] == "generate_authcode") { generate_authcode($_POST['rin']); }
        if ($_POST['action'] == "validate_authcode") { validate_authcode($_POST['authcode'],$_POST['userid']); }
    }
    
// class user_auth_cls {
//This function will accept gedcom number and combine it with current timestamp
// to generate a authcode
function generate_authcode($gedcom) {
    global $dbh;
    // $rin = 1; //for testing only
    $now = date("YmdHis");
    $uniqueCode = rand(100000,999999);
    $sql = 'UPDATE humo_persons SET pers_bapt_text = ' . $uniqueCode . ' WHERE pers_gedcomnumber = "'. $gedcom . '"';
    $result = $dbh->query($sql);
    // $authstr = $rin . ":" . $now . ":" . $uniqueCode;
    // echo base64_encode($authstr);
    echo $uniqueCode;
}

//This function will accept the auth code and gedcom number
//It will then decode the auth code and determine the gedcom number & auth time
// if auth time is older than 1 day, it will return X to suggest expiry
// if returned gedcom number doesn't match the user indicated gedcom number, it
// will return 'I' to suggest that invalid gedcom number was passed
// if both auth time & gedcom pass the validation, then it will return 'S'
// to suggest success

function validate_authcode($authcode, $userid) {
    $userid = 4;
    $now = date("YmdHis");
    $authstr = base64_decode($authcode);
    list($rin, $authts) = explode(":", $authstr);
    echo $authts->format("Y");
    $interval = date_create($authts)->diff(date_create($now));
    $ageofcode = $interval->days;
    if ($ageofcode >= 1) {
        echo 'X';
    }
    else {
        if ($userid <> $rin) {
            echo 'I';
        }
        else {
            echo 'S';
        }
    }
}

// } //End of class
?>