<?php

$G_pwtoken_time_expire = 30; // 30 min
class  CMsg
{
    var $success;
    var $status;
    var $message;
    var $fields;
    var $data;

    function __construct($success,$status = null,$message = null,$fields = null,$data = null)
    {
        $this->success = $success;
        $this->status = $status;
        $this->message = $message;
        $this->fields = $fields;
        $this->data = $data;
    }

    function jsonclass()
    {
        return json_encode($this);
    }

    function jsonarray()
    {
        return json_encode([
            'success' => $this->success,
            'status' => $this->status,
            'message' => $this->message,
            'fields' => $this->fields,
            'data' => $this->data
        ]);
    }
}

class CUser
{
    var $id;
    var $qr_id;
    var $email;

    function __construct($id,$qr_id,$email)
    {
        $this->id = $id;
        $this->qr_id = $qr_id;
        $this->email = $email;
    }
    function jsonarray()
    {
        return json_encode([
            'id' => $this->id,
            'qr_id' => $this->qr_id,
            'email' => $this->email
        ]);
    }
    function phparray()
    {
        return ([
            'id' => $this->id,
            'qr_id' => $this->qr_id,
            'email' => $this->email
        ]);
    }

}

/**
 * Generate a random string, using a cryptographically secure 
 * pseudorandom number generator (random_int)
 * 
 * For PHP 7, random_int is a PHP core function
 * For PHP 5.x, depends on https://github.com/paragonie/random_compat
 * 
 * @param int $length      How many characters do we want?
 * @param string $keyspace A string of all possible characters
 *                         to select from
 * @return string
 */
function random_str(
    $length,
    $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
) 
{
    $str = '';
    $max = mb_strlen($keyspace, '8bit') - 1;
    if ($max < 1) 
    {
        throw new Exception('$keyspace must be at least two characters long');
    }
    for ($i = 0; $i < $length; ++$i) 
    {
        $str .= $keyspace[random_int(0, $max)];
    }
    return $str;
}

function getNewFilename($targetDir, $fileExt, $length)
{
    $newFname = random_str($length);

//    echo "newFname   " . $newFname . "\n";

    $maxtries = 100000; // prevent endless loop, most unlikely 
    $tries = 0;
    // echo "file_exists   " . $targetDir . '/' . $newFname . '.' . $fileExt . "\n";
    // echo "file_exists   " . file_exists($targetDir . '/' . $newFname . '.' . $fileExt) . "\n";
    while(file_exists($targetDir . '/' . $newFname . '.' . $fileExt) && $tries < $maxtries)
    {
//        echo "file_exists   " . $targetDir . '/' . $newFname . '.' . $fileExt . "\n";
        ++$tries;
        $newFname = random_str($length);
        // echo "tries   " . $tries . "\n";
        // echo "newFname   " . $newFname . "\n";
    }
    if($tries >= $maxtries)
    {
        $newFname = "";
    }
    return $newFname .".".$fileExt;
}

function getNewPwtoken($length, $conn)
{
    $newToken = random_str($length);

    $maxtries = 100000; // prevent endless loop, most unlikely 
    $tries = 0;

    do 
    {
        $stmt = $conn->prepare("SELECT id FROM `dogs` WHERE `pwtoken`=?");
        $stmt->execute([$newToken]); 

        if ($stmt->rowCount() == 0) 
        {
            break;
        }
        $newToken = random_str($length);
        echo ('newToken ' . $newToken);
        ++$tries;
    } while ($tries <= $maxtries);

    if($tries >= $maxtries)
    {
        $newToken = "";
    }
    return $newToken;
}

function getDogByQrId($qr_id, $conn, $fields = null)
{
    if(strcmp($qr_id, 'SESS') === 0)
    {
        $allHeaders = getallheaders();
        $auth = new Auth($conn, $allHeaders);
        $data = json_decode($auth->isValid());
        $user = $data->data;
        $qr_id = $user->qr_id;
    }
    $fetch_user_qr_id = 
    "SELECT id, qr_id, email, name, phone, 
    qr_width_cm, qr_height_cm, qr_fontsize, qr_visible_items, qr_item_sequence,
    qr_code, picture FROM `dogs` WHERE `qr_id`=:qr_id";
    $query_stmt = $conn->prepare($fetch_user_qr_id);
    $query_stmt->bindValue(':qr_id', $qr_id,PDO::PARAM_STR);
    $query_stmt->execute();

    // IF THE dog IS FOUNDED BY qr_id
    if($query_stmt->rowCount())
    {
        $row = $query_stmt->fetch(PDO::FETCH_ASSOC);
        $returnData = new CMsg(1,200,'get dog',$fields,$row);
    }
    else
    {
        $returnData = new CMsg(0,422,'no dog',$fields);
    }
    return $returnData;
}
function deleteDir($dir) 
{
    foreach(glob($dir . '/*') as $file) 
    {
        if(!is_dir($file))
        {
            unlink($file);
        }
    }
    return rmdir($dir);
}
?>
