<?php
if (!isset($PathPrefix)) {
	$PathPrefix='../';
}

include($PathPrefix . 'includes/session.php');
$Title = _('New Contact');
include('includes/header.php');


$FreeURL = false;
if(isset($_GET['FreeURL']) && $_GET['FreeURL'] == '1')
{
    $FreeURL = true;
}

$message_list = array();
$url_list = array();
$sql = "SELECT id, url, label, message FROM lms_page WHERE label IS NOT NULL AND userid = '".$_SESSION['UserID']."' AND active = 1 AND approved = 1 ORDER BY label";
$result = DB_query($sql);
while($myrow = DB_fetch_array($result))
{
    $url_list[$myrow['id']] = array("url" => $myrow['url'], "label" => $myrow['label']);
    $message_list[$myrow['url']] = $myrow['message'];
}

// CONTACT CARD
// $url_list[] = array("url" => getNameCardLink($_SESSION['UserID']), "label" => "My Contact Card");

$status_list = array();
$sql = "SELECT id, label, probability FROM lms_status";
$result = DB_query($sql);
while($myrow = DB_fetch_array($result))
{
    $status_list[$myrow['id']] = array('label' => $myrow['label'], 'probability' => $myrow['probability']);
}

if(isset($_POST['save']) &&
    !empty($_POST['name']))
{
    if(isset($_SESSION['last_id']) && $_SESSION['last_id'] == $_POST['key'])
    {
        // do nothing if same id as previous indicating a form resubmit
        prnMsg('Contact ' . $_POST['name'] . ' has been processed and will not be processed again', 'warn');
    }
    else
    {
        $_SESSION['last_id'] = $_POST['key'];
        
        $name = $_POST['name'];
        $contactno = $_POST['contactno'];
        $email = $_POST['email'];
        $company = $_POST['company'];
        $location = $_POST['location'];
        $remarks = $_POST['remarks'];
        $message = stripcslashes($_POST['message']);
        $status = $_POST['status'];
        $url = $_POST['url'];
        $url_include = (isset($_POST['include_url_list']) && count($url_list) > 0); // if checkbox is selected and there is at least one url in the list

        if(!empty($url))
        {
            $url = filter_var($url, FILTER_SANITIZE_URL);
            $valid_url = filter_var($url, FILTER_VALIDATE_URL);
        }

        if ((isset($valid_url) && $valid_url) || 
            (!isset($valid_url) && $url_include))
        {
            $contactno = str_ireplace(array(' ', '-'), '', $contactno); // remove all - and space

            $sql = "INSERT INTO lms_leads (name, contactno, email, company, location, remarks, status, owner)
                    VALUES ('".$name."', '".$contactno."', '".$email."', '".$company."', '".$location."', '".$remarks."', '".$status."','".$_SESSION['UserID']."')";
            $result = DB_query($sql);
            $lead_id = $_SESSION['LastInsertId'];
            prnMsg('New Contact ' . $name . ' has been added','success');
            

            $i = 1;
            $links = '<div class="well">
                        <h3>Connect with: '.$name.'</h3>';

            if(!empty($url))
            {
                // check and add url entered against our list
                $sql = "SELECT id FROM lms_page WHERE url = '" . $url . "' and userid = '".$_SESSION['UserID']."'";
                $result = DB_query($sql);
                if (DB_num_rows($result) > 0)
                {
                    $myrow = DB_fetch_array($result);
                    $page_id = $myrow['id'];
                }
                else
                {
                    $sql = "INSERT INTO lms_page (url, userid, active, approved) VALUES ('" . $url . "', '".$_SESSION['UserID']."', 0, 1)";
                    DB_query($sql);
                    $page_id = $_SESSION['LastInsertId'];
                }

                // generate link to be shared
                $sharelink = generateLink($page_id, $lead_id);
                $share_content = empty($message) ? urlencode($sharelink) : str_replace('&amp;', '%26', $message) . ' ' . urlencode($sharelink);

                $links .= '<h4>Link to: '.$url.' <a href="'.$url.'" target="_blank"><span class="glyphicon glyphicon-share"></span></a></h4>
                            <div class="form-inline form-group">';
                if(!empty($contactno))
                {
                    $contactno = trim($contactno, '+'); // remove + prefix
                    $links .= '<a class="btn btn-success" target="_blank" data-action="share/whatsapp/share" href="https://wa.me/'.$contactno.'?text='.$share_content.'"><span class="glyphicon glyphicon glyphicon-phone"></span> WhatsApp</a>';
                }
                if(!empty($email))
                {
                    $links .= '<a class="btn btn-info" href="mailto:'.$email.'?body='.$share_content.'"><span class="glyphicon glyphicon-envelope"></span> Email</a>';
                }
                
                $links .= '<a class="btn btn-default" onclick="copyClipboard(\'copyText_'.$i.'\');">Copy URL</a>';
                $links .= '<form class="form-inline" method="post" action="lms_LeadsReportViews.php" target="_blank" style="display:inline;">
                                <input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />
                                <input type="hidden" name="lead" value="' . $lead_id . '" />
                                <button type="submit" name="view" class="btn btn-default"><span class="glyphicon glyphicon-stats"></span> View</button>
                            </form>';
                $links .= '<pre id="copyText_'.$i.'">'.$sharelink.'</pre>';
                $links .= '</div>';

                $i++;
            }
           
            
            if($url_include)
            {
                
                foreach($url_list as $id => $url)
                {
                    $sharelink = generateLink($id, $lead_id);
                    $share_content = empty($message) ? urlencode($sharelink) : str_replace('&amp;', '%26', $message) . ' ' . urlencode($sharelink);

                    $links .= '<h4>Link to: '.$url["url"].' <a href="'.$url["url"].'" target="_blank"><span class="glyphicon glyphicon-share"></span></a></h4>';
                    $links .= '<div class="form-inline form-group">';
                    if(!empty($contactno))
                    {
                        $contactno = trim($contactno, '+'); // remove + prefix
                        $links .= '<a class="btn btn-success" target="_blank" data-action="share/whatsapp/share" href="https://wa.me/'.$contactno.'?text='.$share_content.'"><span class="glyphicon glyphicon glyphicon-phone"></span> WhatsApp</a>';
                    }
                    if(!empty($email))
                    {
                        $links .= '<a class="btn btn-info" href="mailto:'.$email.'?body='.$share_content.'"><span class="glyphicon glyphicon-envelope"></span> Email</a>';
                    }
                    
                    $links .= '<a class="btn btn-default" onclick="copyClipboard(\'copyText_'.$i.'\');">Copy URL</a> <pre id="copyText_'.$i.'">'.$sharelink.'</pre>';
                    $links .= '</div>';

                    $i++;
                }
            }
        
            $links .= '</div>';

            echo $links;
            
            unset($name);
            unset($contactno);
            unset($email);
            unset($company);
            unset($location);
            unset($remarks);
            unset($message);
            unset($status);
            unset($url);
        }
        else
        {
            if(isset($valid_url) && !$valid_url)
            {
                // invalid url
                prnMsg(_('Invalid URL'),'error');
            }
            else if(!$url_include)
            {
                // no url
                prnMsg(_('No URL detected'),'error');
            }
        }
    }
}


// if(empty($message))
// {
//     $message = "Hi, kindly click or share the URL for more information: ";
// }
?>

<style>
.well a, pre {
    margin: 2px;
}
</style>
<script>
function copyClipboard(elementid)
{
    var range = document.createRange();
    range.selectNode(document.getElementById(elementid));
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
    document.execCommand("copy");
    window.getSelection().removeAllRanges();
    alert("Copied URL to clipboard!");
}

function setMessage(sel)
{
    <?php
    echo 'message_list=' . json_encode($message_list) . ';';
    ?>
    $("#message").val(message_list[sel.value]);
}

$(document).ready(function(){

    $('#additionaldetails').on('show.bs.collapse', function() {
        $("#detailstoggle").html('Less <span style="float:right;" class="glyphicon glyphicon-chevron-up"></span>');
    });

    $('#additionaldetails').on('hide.bs.collapse', function() {
        $("#detailstoggle").html('More <span style="float:right;" class="glyphicon glyphicon-chevron-down"></span>');
    });

});
</script>

<div class="row">
    <div class="col-sm-4"></div>
    <div class="col-sm-4">
        <form method="post">
        <?php
        echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
        echo '<input type="hidden" name="key" value="'.uniqid().'" />';
        ?>
            <div class="form-group">
                <label for="name">Name:</label>
                <input type="text" class="form-control" name="name" placeholder="Contact Name" value="<?php echo (isset($name) ? $name : '' ); ?>" required >
            </div>
            <div class="form-group">
                <label for="contactno">Phone No:</label>
                <input type="tel" class="form-control" name="contactno" placeholder="Contact Phone Number" value="<?php echo (isset($contactno) ? $contactno : '' ); ?>">
                <span class="help-block">(Eg: +60123456789) </span>
            </div>
            
            <div class="form-group">
                <a href="#additionaldetails" style="text-align:left;" class="btn btn-block" id="detailstoggle" data-toggle="collapse">More <span style="float:right;" class="glyphicon glyphicon-chevron-down"></span></a>
            </div>
            <div id="additionaldetails" class="collapse">
                <div class="form-group">
                    <label for="email">Email address:</label>
                    <input type="email" class="form-control" name="email" placeholder="Contact Email Address" value="<?php echo (isset($email) ? $email : '' ); ?>">
                </div>
                <div class="form-group">
                    <label for="company">Company:</label>
                    <input type="text" class="form-control" name="company" placeholder="Company of Contact" value="<?php echo (isset($company) ? $company : '' ); ?>">
                </div>
                <div class="form-group">
                    <label for="location">Location:</label>
                    <textarea class="form-control" rows="5" name="location" placeholder="Location / Address of Contact"><?php echo (isset($location) ? $location : '' ); ?></textarea>
                </div>
                <div class="form-group">
                    <label for="remarks">Remarks:</label>
                    <textarea class="form-control" rows="2" name="remarks" placeholder="Your Remarks / Comments / Notes"><?php echo (isset($remarks) ? $remarks : '' ); ?></textarea>
                </div>
            </div>
            <div class="form-group">
                <label for="url">Share URL:</label>
                
                <?php
                if($FreeURL)
                {
                ?>
                    <input list="urls" type="text" class="form-control" name="url" placeholder="URL to share with Contact" value="<?php echo (isset($url) ? $url : '' ); ?>">
                    <span class="help-block">Only complete URL is accepted<br>(Eg: http://www.google.com) </span>
                    <datalist id="urls">
                    <?php
                    foreach($url_list as $id => $url)
                    {
                        echo '<option value="'.$url["url"].'">'.$url["label"].'</option>';
                    }
                    ?>
                    </datalist>
                    <div class="checkbox">
                        <label><input name="include_url_list" type="checkbox"> include URL list</label>
                    </div>
                <?php
                }
                else
                {
                ?>
                    <select class="form-control" name="url" required onchange="setMessage(this);">
                        <option value="" disabled selected>Please select...</option>
                    <?php
                    foreach($url_list as $id => $url)
                    {
                        echo '<option value="'.$url["url"].'">'.$url["label"].'</option>';
                    }
                    ?>
                    </select>
                <?php
                }
                ?>
            </div>
            
            <div class="form-group">
                <label for="message">Message:</label>
                <textarea class="form-control" rows="2" id="message" name="message" placeholder="Message to Contact.."><?php echo (isset($message) ? $message : '' ); ?></textarea>
            </div>

            <div class="form-group">
                <label for="status">Status:</label>
                <select class="form-control" name="status">
                <?php
                foreach($status_list as $id => $desc)
                {
                    echo '<option value="'.$id.'" ' . ($status == $id ? 'selected' : '') . '>' . $desc['label'] . ' - ' . ($desc['probability'] * 100) . '%</option>';
                }
                ?>
                </select>
            </div>

            <button type="submit" name="save" class="btn btn-block btn-info">Save <span class="glyphicon glyphicon-save"></span></button>
        </form>
    </div>
    <div class="col-sm-4"></div>
</div>

<?php
include('includes/footer.php');
?>