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

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

$message_list = array();
$sql = "SELECT url, 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))
{
    $message_list[$myrow['url']] = $myrow['message'];
}

$FreeURL = false;
if(isset($_POST['generate_link']) && empty($_POST['url']))
{
    $FreeURL = true;
    $_POST['view'] = true;
}

$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']);
}
?>

<style>
.well input, button, 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]);
}
</script>

<div class="row">
    <div class="col-sm-12">
        <button type="button" class="btn btn-danger" onclick="window.close();">
            Close <span class="glyphicon glyphicon-remove"></span>
        </button>
    </div>
</div>

<br>

<?php
if(isset($_POST['generate_link']) && !empty($_POST['lead']) && !empty($_POST['url']))
{
    $lead_id = $_POST['lead'];
    $url = htmlspecialchars_decode($_POST['url']);
    $contactno = $_POST['contactno'];
    $email = $_POST['email'];
    $message = stripcslashes($_POST['message']);

    $url = filter_var($url, FILTER_SANITIZE_URL);
    if (filter_var($url, FILTER_VALIDATE_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 = '<div class="well">
                    <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\');">Copy URL</a> <pre><div id="copyText">'.$sharelink.'</div></pre>';
        $links .= '</div></div>';

        echo $links;

        unset($url);
        unset($contactno);
        unset($email);
    }
    else
    {
        // invalid url
        prnMsg(_('Invalid url'),'error');
    }

    $_POST['view'] = true;
}
else if(isset($_POST['update_status']) && !empty($_POST['lead']))
{
    $lead_id = $_POST['lead'];

    $sql = "SELECT remarks, status
            FROM lms_leads
            WHERE id = '".$lead_id."'";

    $result = DB_query($sql);
    while($myrow = DB_fetch_array($result))
    {
        $remarks = stripcslashes($myrow['remarks']);
        $status = $myrow['status'];
    }

    if(isset($_POST['includetimestamp']))
    {
        $remarks = "";
        if($status != $_POST['status'])
        {
            $remarks .= '[' . date('jS M Y H:i') . '] ' . $status_list[$status]['label'] . '\r\n';
            $status = $_POST['status'];
            $update_fields .= "status='".$status."', ";
        }
        if(!empty(trim($_POST['addremark'])))
        {
            $remarks .= '[' . date('jS M Y H:i') . '] ' . $_POST['addremark'] . '\r\n';
        }

        if($remarks != "")
        {
            $update_fields .= "remarks=CONCAT('".$remarks."', remarks), ";
        }
    }
    else
    {
        if($status != $_POST['status'])
        {
            $status = $_POST['status'];
            $update_fields .= "status='".$status."', ";
        }
        if(!empty(trim($_POST['addremark'])))
        {
            $remarks = "";
            $remarks .= $_POST['addremark'] . '\r\n';
            $update_fields .= "remarks=CONCAT('".$remarks."', remarks), ";
        }
        
    }

   

    if(!empty($update_fields))
    {
        $update_fields .= "lastupdated=CURRENT_TIMESTAMP";

        $sql = "UPDATE lms_leads SET ".$update_fields."                                        
                WHERE id='".$lead_id."'";
        $result = DB_query($sql);
        prnMsg('Status has been updated','success');
    }

    $_POST['view'] = true;
}
else if(isset($_POST['email']) && !empty($_POST['lead']))
{
    $lead_id = $_POST['lead'];
    $watch = isset($_POST['watchlist']) ? 1 : 0;

    $sql = "UPDATE lms_leads SET watch = ".$watch." WHERE id='".$lead_id."'";
    $result = DB_query($sql);

    $_POST['view'] = true;
}

if(isset($_POST['view']) && !empty($_POST['lead']))
{
    $lead_id = $_POST['lead'];
    
    $sql = "SELECT name, contactno, email, company, location, remarks, lastupdated, owner, lastappointment, status, watch
            FROM lms_leads
            WHERE id = '".$lead_id."'";
    $result = DB_query($sql);
    while($myrow = DB_fetch_array($result))
    {
        $info['Name'] = $myrow['name'];
        $info['Contact No'] = $myrow['contactno'];
        $info['Email'] = $myrow['email'];
        $info['Company'] = $myrow['company'];
        $info['Location'] = $myrow['location'];
        $info['Last Updated'] = $myrow['lastupdated'];

        $info['Remarks'] = $myrow['remarks'];
        $info['Status'] = $myrow['status'];
        $info['Last Appointment'] = ((is_null($myrow['lastappointment']) || (date('Y-m-d', strtotime($myrow['lastappointment'])) < date('Y-m-d'))) ? '' : date('Y-m-d g:ia', strtotime($myrow['lastappointment'])));

        $userid = $myrow['owner'];
        $watch = $myrow['watch'];

        $contactno = $info['Contact No'];
        $email = $info['Email'];
    }

    $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" => $myrow['message']);
    }
    
    // CONTACT CARD
    // $url_list[] = array("url" => getNameCardLink($_SESSION['UserID']), "label" => "My Contact Card");

    $sql = "SELECT lms_viewstat.page, lms_viewstat.view, lms_page.label
            FROM lms_viewstat
            LEFT JOIN lms_page
            ON lms_viewstat.page = lms_page.url AND lms_page.userid = '".$userid."'
            WHERE lead_id = '".$lead_id."'
            ORDER BY view DESC";

    
    $result = DB_query($sql);
    while($myrow = DB_fetch_array($result))
    {
        $page = ($myrow['label']==''? $myrow['page'] : $myrow['label']);
        $stats[] = array("page" => $page, "view" => date('Y-m-d H:i:s', strtotime($myrow['view'])), "viewdate" => date('Y-m-d', strtotime($myrow['view'])));
        $statsummary[$page]['views'] += 1;
        $statsummary[$page]['url'] = $myrow['page'];
    }

    // if(empty($message))
    // {
    //     $message = "Hi, kindly click or share the URL for more information: ";
    // }
    
?>
<div class="row">
    <div class="col-sm-12">
        <form class="form-inline" method="post" action="lms_LeadEdit.php" target="_blank">
            <div class="form-group">
                <h3>Contact Info</h3>
            </div>
            <div class="form-group">
                <input type="hidden" name="FormID" value="<?php echo $_SESSION['FormID']; ?>" />
                <input type="hidden" name="lead" value="<?php echo $lead_id; ?>" />
                <button type="submit" name="edit" class="btn btn-info"><span class="glyphicon glyphicon-edit"></span></button>
                <button type="submit" name="setappointment" class="btn btn-info" formaction="lms_LeadAppointment.php" name="edit" class="btn btn-link"><span class="glyphicon glyphicon-calendar"></span></button>
            </div>
        </form>
        <div class="well well-sm">
            <form class="form-horizontal" method="post">
            <?php
                echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
                echo '<input type="hidden" name="lead" value="' . $lead_id . '" />';
                echo '<input type="hidden" name="email" value="' . $email . '" />';
                echo '<input type="hidden" name="contactno" value="' . $contactno . '" />';

                foreach($info as $label => $data)
                {
                    if(!empty($data))
                    {
                        if($label == "Location" || $label == "Remarks")
                        {
                            echo '<div class="form-group">
                                    <label class="control-label col-sm-2" for="'.$label.'">'.$label.' :</label>
                                    <div class="col-sm-10">
                                        <pre class="form-control-static">'.$data.'</pre>
                                        '. ($label == "Location" ? '<p>[<a href="https://www.google.com/maps/search/?api=1&query=' . $data . '" target="_blank">View</a>]</p>' : '') .'
                                    </div>
                                </div>';
                        }
                        else if($label == "Company")
                        {
                            echo '<div class="form-group">
                                    <label class="control-label col-sm-2" for="'.$label.'">'.$label.' :</label>
                                    <div class="col-sm-10">
                                        <p class="form-control-static">'.$data.' [<a href="https://www.google.com/maps/search/?api=1&query=' . $data . '" target="_blank">View Location</a>]</p>
                                    </div>
                                </div>';
                        }
                        // else if($label == "Remarks")
                        // {
                        //     echo '<div class="form-group">
                        //             <label class="control-label col-sm-2" for="name">'.$label.' :</label>
                        //             <div class="col-sm-10">
                        //                 <textarea class="form-control" rows="2" name="remarks">'.$data.'</textarea>
                        //             </div>
                        //         </div>';
                        // }
                        else if($label == "Status")
                        {
                            echo '<div class="form-group">
                                    <label class="control-label col-sm-2" for="name">Add Remark :</label>
                                    <div class="col-sm-10">
                                        <textarea class="form-control" rows="2" name="addremark" placeholder="Remark / Comment to add"></textarea>
                                        <div class="checkbox">
                                            <label><input type="checkbox" name="includetimestamp" value="Y" checked>include timestamp</label>
                                        </div>
                                    </div>
                                </div>';

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

                            echo '</select>
                                            <div class="input-group-btn">
                                                <button type="submit" name="update_status" class="btn btn-default" style="margin:0px;" formnovalidate>
                                                    Update Status <span class="glyphicon glyphicon-check"></span>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>';
                        }
                        else
                        {
                            $actionlink = "";
                            if($label == "Contact No")
                            {
                                $contactno = trim($data, '+'); // remove + prefix
                                $actionlink .= '<li><a class="small" href="https://wa.me/'.$contactno.'?" target="_blank">WhatsApp <span class="glyphicon glyphicon-share"></span></a></li>';
                                $data = '<a href="tel:'.$data.'">' . $data . '</a>';
                            }
                            else if($label == "Email")
                            {
                                $actionlink .= '<li><a class="small" href="mailto:'.$email.'?">Send Email <span class="glyphicon glyphicon-share"></span></a></li>';
                            }

                            echo '<div class="form-group">
                                    <label class="control-label col-sm-2" for="'.$label.'">'.$label.' :</label>
                                    <div class="col-sm-10">
                                        <ul class="list-inline form-control-static"><li>'.$data.'</li>'.$actionlink.'</ul>
                                    </div>
                                </div>';
                        }
                    }
                }

                echo  '<div class="form-group">
                            <label class="control-label col-sm-2" for="name">Watch list :</label>
                            <div class="col-sm-10">
                                <div class="checkbox">
                                    <label><input type="checkbox" name="watchlist" value="Y" onChange="this.form.submit()" ' . (($watch == 1) ? 'checked' : '') . '></label>
                                </div>
                            </div>
                        </div>';
            ?>

                <hr>

                <div class="form-group">
                    <label class="control-label col-sm-2" for="url">Share URL :</label>
                    <div class="col-sm-10">

                    <?php
                    if($FreeURL)
                    {
                    ?>
                        <div class="input-group">
                            <input list="urls" type="text" class="form-control" name="url" placeholder="http://www.google.com" value="<?php echo (isset($url) ? $url : '' ); ?>" required>
                            <div class="input-group-btn">
                                <button type="submit" name="generate_link" class="btn btn-default">
                                    Generate Link <span class="glyphicon glyphicon-link"></span>
                                </button>
                            </div>
                        </div>
                        <datalist id="urls">
                        <?php
                        foreach($url_list as $url)
                        {
                            echo '<option value="'.$url["url"].'">'.$url["label"].'</option>';
                        }
                        ?>
                        </datalist>

                    <?php
                    }
                    else
                    {
                    ?>
                        <div class="input-group">
                            <select class="form-control" name="url" required onchange="setMessage(this);">
                                <option value="" disabled selected>Please select...</option>
                            <?php
                            foreach($url_list as $url)
                            {
                                echo '<option value="'.$url["url"].'">'.$url["label"].'</option>';
                            }
                            ?>
                            </select>
                            <div class="input-group-btn">
                                <button type="submit" name="generate_link" class="btn btn-default" style="margin:0px;">
                                    Generate Link <span class="glyphicon glyphicon-link"></span>
                                </button>
                            </div>
                        </div>
                    <?php
                    }
                    ?>
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-2" for="url">Message :</label>
                    <div class="col-sm-10">
                        <textarea class="form-control" rows="2" id="message" name="message" placeholder="Message to Contact.."><?php echo (isset($message) ? $message : '' ); ?></textarea>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<?php
    if(count($stats) > 0) // only show summary when there is data
    {
?>
<div class="panel panel-default">
    <div class="panel-heading">Summary</div>
    <div class="panel-body">
    <button class="btn btn-info" onclick="drawSummaryBarChart();" >Fit Chart to Screen <span class="glyphicon glyphicon-resize-full"></span></button>

<?php
$chart_json_header[] = "Date";
// $chart_summary_json[] = array('Page', 'View(s)');
$chart_summary_json_header[] = "Views(s)";
$chart_summary_json_data[] = "";
$link_summary = '<div class="table-responsive">
                    <table class="table-condensed" style="width:100%;">
                        <tr>
                            <th>Link</th>
                            <th>Views</th>
                        </tr>';
foreach ($statsummary as $page => $page_data)
{
    // $link_summary .= '<form class="form-horizontal" method="post">
    //                     <input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />
    //                     <input type="hidden" name="lead" value="' . $lead_id . '" />
    //                     <input type="hidden" name="email" value="' . $email . '" />
    //                     <input type="hidden" name="contactno" value="' . $contactno . '" />
    //                     <input type="hidden" name="url" value="' . $page_data['url'] . '" />
                        
    //                     <ul class="list-inline form-control-static">
    //                         <li>
    //                             <button type="submit" name="generate_link" class="btn btn-sm btn-default">
    //                                 Generate Link <span class="glyphicon glyphicon-link"></span>
    //                             </button>
    //                         </li>
    //                         <li>
    //                             <a href="'.$page_data['url'].'" target="_blank">'.$page.' <span class="badge">'.$page_data['views'].'</span></a>
    //                         </li>
    //                     </ul>
    //                 </form>';

    $link_summary .= '<form class="form-horizontal" method="post">
                        <input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />
                        <input type="hidden" name="lead" value="' . $lead_id . '" />
                        <input type="hidden" name="email" value="' . $email . '" />
                        <input type="hidden" name="contactno" value="' . $contactno . '" />
                        <input type="hidden" name="url" value="' . $page_data['url'] . '" />
                      
                        <tr>
                            <td>
                                <button type="submit" name="generate_link" class="btn btn-sm btn-default">
                                    Generate Link <span class="glyphicon glyphicon-link"></span>
                                </button>
                                <a href="'.$page_data['url'].'" target="_blank">'.$page.'</a>
                            </td>
                            <td>
                                <span class="badge">'.$page_data['views'].'</span>
                            </td>
                        </tr>
                    </form>';
    

    $chart_summary_json_data[] = $page_data['views'];

    $chart_json_header[] = $page;
    $chart_summary_json_header[] = $page;
}
$link_summary .= '</table></div>';

$chart_summary_json[] = $chart_summary_json_header;
$chart_summary_json[] = $chart_summary_json_data;
    
?>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
    google.charts.load('current', {packages: ['corechart', 'bar']});
    google.charts.setOnLoadCallback(drawSummaryBarChart);

    function drawSummaryBarChart() {

        var data = google.visualization.arrayToDataTable(
            <?php
            echo json_encode($chart_summary_json);
            ?>
        );

        var options = {
            title: 'Page View Statistics',
            chartArea: {
                width: '80%'
            },
            hAxis: {
                title: 'View(s)',
                minValue: 0
            },
            vAxis: {
                textPosition: 'in'
            },
            dataOpacity: '0.7',
            legend: {
                position: 'none'
            }
        };

        var chart = new google.visualization.BarChart(document.getElementById('summary_chart_div'));

        chart.draw(data, options);
    }
    
</script>

        <div id="summary_chart_div"></div>
        <?php echo $link_summary ?>
    </div>
</div>
<div class="row">
    <div class="col-sm-12">
        <div class="table-responsive">
            <table class="table table-condensed table-hover table-striped">
                <thead>
                    <tr>
                        <th class="ascending">#</th>
                        <th class="ascending"><span class="glyphicon glyphicon-sort"></span> View</th>
                        <th class="ascending"><span class="glyphicon glyphicon-sort"></span> Page</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $recordno = 0;
                    foreach ($stats as $stat)
                    {
                        $recordno += 1;
                        echo '<tr>
                                <td class="number">'.$recordno.'</td>
                                <td>'.$stat["view"].'</td>
                                <td>'.$stat["page"].'</td>
                            </tr>';
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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