<?php
$_HASH_SECRET_KEY = "SigmaLMS"; // this is to be kept secret and not to be exposed!

$http =  (!empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on') ? "https://" : "http://";
$dir = (dirname($_SERVER['PHP_SELF']) == '/') ? '' : dirname($_SERVER['PHP_SELF']);
$_LANDINGPAGE = $http . $_SERVER['SERVER_NAME'] . $dir . "/views";
$_CONTACTCARDPAGE = $http . $_SERVER['SERVER_NAME'] . $dir . "/views/contact";

function generateLink($page_id, $lead_id)
{
    global $_HASH_SECRET_KEY, $_LANDINGPAGE;
    $hash = sha1($_HASH_SECRET_KEY . $page_id . $lead_id);

    return $_LANDINGPAGE . "/" . $page_id . "/" . $lead_id . "/" . $hash;
}

function generateUserNamecardKey($userid)
{
    global $_HASH_SECRET_KEY;
    return sha1($_HASH_SECRET_KEY . $userid);
}

function getNameCardLink($userid)
{
    global $_CONTACTCARDPAGE;

    $contactcard_url = $_CONTACTCARDPAGE . '/' . generateUserNamecardKey($userid);
    
    // check and add url entered against our list
    $sql = "SELECT id FROM lms_page WHERE url = '" . $contactcard_url . "' AND userid = '".$userid."'";
    $result = DB_query($sql);
    if (DB_num_rows($result) > 0)
    {
        $myrow = DB_fetch_array($result);
        $page_id = $myrow['id'];
    }
    else
    {
        $message = 'Hi, kindly click on the link for my contact information:';
        $sql = "INSERT INTO lms_page (url, label, message, userid, active, approved) VALUES ('" . $contactcard_url . "', 'My Contact Card', '"."$message"."', '".$userid."', 1, 1)";
        DB_query($sql);
        $page_id = $_SESSION['LastInsertId'];
    }

    return $contactcard_url;
}

function create_vcard($name, $email, $tel, $title, $organization)
{
    return utf8_encode('BEGIN:VCARD
VERSION:3.0
N:'.$name.'
FN:'.$name.'
TEL;TYPE=cell:'.$tel.'
EMAIL;TYPE=work:'.$email.'
TITLE:'.$title.'
ORG:'.$organization.'
REV:'.date('Ymd').'
END:VCARD');
}

function CaptureRedirect($page_id, $lead_id, $hash_key)
{
    global $_HASH_SECRET_KEY;
    $userid = "";

    // validate hash key is alphanumeric and length 20
    if (!ctype_alnum($hash_key) && strlen($hash_key) == 20) {
        // echo("$hashid is not valid");
        die();
    }

    // validate page id
    if (!filter_var($page_id, FILTER_VALIDATE_INT)) {
        // echo("$page_id is not an integer");
        die();
    }
    
    // validate lead id
    if (!filter_var($lead_id, FILTER_VALIDATE_INT)) {
        // echo("$lead_id is not an integer");
        die();
    }
    
    // validate hash alogorithm matching to ensure request is from a known source
    if(sha1($_HASH_SECRET_KEY . $page_id . $lead_id) != $hash_key)
    {
        // echo("invalid request detected");
        die();
    }
    
    // check lead id exists
    $sql = "SELECT id, owner FROM lms_leads WHERE id = '" . $lead_id . "'";
    $result = DB_query($sql);
    while($myrow = DB_fetch_array($result))
    {
        $userid = $myrow['owner'];
        $lead_id = $myrow['id'];
    }

    // check page id exists
    if(!empty($userid))
    {
        $sql = "SELECT url FROM lms_page WHERE id = '" . $page_id . "' AND userid = '" . $userid . "'";
        $result = DB_query($sql);
        while($myrow = DB_fetch_array($result))
        {
            $url = htmlspecialchars_decode($myrow['url']);
        }
    }

    if(isset($url) && isset($lead_id))
    {
        $sql = "INSERT INTO lms_viewstat (lead_id, page) VALUES (" . $lead_id . ", '" . $url . "')";
        $result = DB_query($sql);

        if($result)
        {
            header("Location:" . $url); // Redirect browser
            return;
        }
    }
    else
    {
        die();
    }
}

function GetContact($id)
{
    $userid_hash = $id;

    $sql = "SELECT userid, realname, phone, email
            FROM www_users
            WHERE blocked=0";

    $result = DB_query($sql);
    while($myrow = DB_fetch_array($result))
    {
        if(generateUserNamecardKey($myrow['userid']) == $userid_hash)
        {
            $userid = $myrow['userid'];
            $name = $myrow['realname'];
            $email = $myrow['email'];
            $phone = $myrow['phone'];
            $title = "";
            $organization = "";

            $sql = "SELECT title, organization FROM lms_users WHERE userid = '".$userid."'";
            $result_user = DB_query($sql);
            while($row_user = DB_fetch_array($result_user))
            {
                $title = $row_user['title'];
                $organization = $row_user['organization'];
            }

            $vcard = create_vcard($name, $email, $phone, $title, $organization);

            break;
        }
    }


    if(isset($name))
    {
        header( 'Content-Type: text/x-vcard' );
        header( 'Content-Disposition: attachment; filename="contact.vcf";' );

        // clean output buffer
        ob_end_clean();

        $handle = fopen( 'php://output', 'w' );
        
        fwrite($handle, $vcard);

        fclose($handle);

        // flush buffer
        ob_flush();

        // use exit to get rid of unexpected output afterward
        exit();
    }
}

function DisplayContact($id)
{
    global $http;
    $dir = (dirname($_SERVER['PHP_SELF'], 2) == "/" ? '' : dirname($_SERVER['PHP_SELF'], 2));
    $userid_hash = $id;

    $sql = "SELECT userid, realname, phone, email
            FROM www_users
            WHERE blocked=0";

    $result = DB_query($sql);
    while($myrow = DB_fetch_array($result))
    {
        if(generateUserNamecardKey($myrow['userid']) == $userid_hash)
        {
            $userid = $myrow['userid'];
            $name = $myrow['realname'];
            $email = $myrow['email'];
            $phone = $myrow['phone'];
            $title = "";
            $organization = "";

            $sql = "SELECT title, organization FROM lms_users WHERE userid = '".$userid."'";
            $result_user = DB_query($sql);
            while($row_user = DB_fetch_array($result_user))
            {
                $title = $row_user['title'];
                $organization = $row_user['organization'];
            }

            $vcard = create_vcard($name, $email, $phone, $title, $organization);

            break;
        }
    }

    if(isset($name))
    {
        
        $has_email = false;
        $has_phone = false;

        if(!empty($email))
        {
            $has_email = true;
        }

        if(!empty($phone))
        {
            $has_phone = true;
        }

        $RootPath = "../../";

        $profile_img = 'css/profile.png';

        $upload_dir = 'uploads/' . $userid;
        $SupportedImgExt = array('png','jpg','jpeg');
        foreach ($SupportedImgExt as $ext) {
            $file = $upload_dir . '/profile.' . $ext;
            if (file_exists ('../' . $file) ) {
                $profile_img = $file;
                break;
            }
        }
    ?>

    <!DOCTYPE html>

    <head>
        <meta http-equiv="Content-Type" content="application/html; charset=utf-8; cache-control: no-cache, no-store, must-revalidate; Pragma: no-cache" />
        <title>Contact Info: <?php echo $name ?></title>
        <link rel="icon" href="<?php echo $RootPath; ?>favicon.ico" />
        <link rel="stylesheet" href="<?php echo $RootPath; ?>bootstrap/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="bootstrap/js/bootstrap.min.js"></script>
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <meta name="title" content="Contact Info: <?php echo $name; ?>" />
        <meta property="og:title" content="Contact Info: <?php echo $name; ?>" />
        <meta property="og:type" content="website" />
        <meta property="og:url" content="<?php echo  $http . $_SERVER['SERVER_NAME'] . $dir . '/' . $profile_img; ?>" />
        <meta property="og:image" content="<?php echo $http . $_SERVER['SERVER_NAME'] . $dir . '/' . $profile_img; ?>" />

        <style>
            .btn-round{
                border-radius: 50%;
                margin: 5px;
            }
        </style>
    </head>

    <body>
        <div class="container">

            <br>
            <br>
            <div class="row text-center">
                <div class="col-sm-4"></div>
                <div class="col-sm-4">
                    <img src="<?php echo $RootPath . $profile_img . '?' . filemtime($profile_img); ?>" class="img-circle" alt="">
                </div>
                <div class="col-sm-4"></div>
            </div>

            <div class="row">
                <div class="col-sm-12">
                    <h1 class="text-center"><?php echo $name; ?></h1>
                    <?php
                    if(!empty($title))
                    {
                        echo '<h2 style="margin:0px;" class="text-center"><small>'.$title.'</small></h2>';
                    }
                    if(!empty($organization))
                    {
                        echo '<h2 style="margin-top:0px;" class="text-center"><small>'.$organization.'</small></h2>';
                    }
                    ?>
                </div>
            </div>

            <div class="row text-center" style="margin-top:20px;">
                <div class="col-sm-4"></div>
                <div class="col-sm-4">
                    <form class="form-inline" method="post">
                        <a href="tel:<?php echo $phone; ?>" class="btn btn-primary btn-lg btn-round <?php if(!$has_phone) { echo 'disabled'; } ?>"><span class="glyphicon glyphicon-earphone"></span></a>
                        <a href="mailto:'<?php echo $email; ?>'?"class="btn btn-primary btn-lg btn-round <?php if(!$has_email) { echo 'disabled'; } ?>"><span class="glyphicon glyphicon-envelope"></span></a>
                        <a href="https://wa.me/<?php echo trim($phone, '+'); ?>?" target="_blank" class="btn btn-primary btn-lg btn-round <?php if(!$has_phone) { echo 'disabled'; } ?>"><span class="glyphicon glyphicon-phone"></span></a>
                        
                        <button type="submit" value="vcard" name="vcard" class="btn btn-primary btn-lg btn-round"><span class="glyphicon glyphicon-floppy-save"></span></button></div>
                    </form>
                <div class="col-sm-4"></div>
            </div>

            <div class="row">
                <div class="col-sm-4"></div>
                <div class="col-sm-4 lead">
                    
                    <?php
                    if($has_phone)
                    {
                    ?>
                    <hr>
                    <div class="form-group">
                        <label for="email">Contact No:</label>
                        <p class="form-control-static"><a href="tel:<?php echo $phone; ?>"><?php echo $phone; ?></a></p>
                    </div>
                    <?php
                    }
                    
                    if($has_email)
                    {
                    ?>
                    <hr>
                    <div class="form-group">
                        <label for="email">Email:</label>
                        <p class="form-control-static"><a href="mailto:'<?php echo $email; ?>'?"><?php echo $email; ?></a></p>
                    </div>
                    <?php
                    }
                    ?>

                    <hr>
                    <div class="text-center">
                        <br>
                        <h2>Scan Me</h2>
                        <img src="https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=<?php echo urlencode($vcard); ?>" >
                    </div>
                    
                </div>
                <div class="col-sm-4"></div>
            </div>
        </div>
    </body>
    <?php
    }
}
?>