<?php
if(isset($_POST['get_appointment']))
{
    $lastappointment = $_POST['date'] . ' ' . $_POST['hh'] . ':' . $_POST['mm'];

    $ical = "BEGIN:VCALENDAR
VERSION:2.0
PRODID:
BEGIN:VEVENT
UID:".sha1($lastappointment . $_POST['lead'])."
DTSTAMP:".date('Ymd', strtotime($lastappointment))."T".date('His', strtotime($lastappointment))."
DTSTART:".date('Ymd', strtotime($lastappointment))."T".date('His', strtotime($lastappointment))."
DTEND:".date('Ymd',(strtotime ( '1 hour' , strtotime ( $lastappointment ) ) ))."T".date('His',(strtotime ( '1 hour' , strtotime ( $lastappointment ) ) ))."
SUMMARY:".$_POST['name']."
LOCATION:
DESCRIPTION:
BEGIN:VALARM
ACTION:DISPLAY
DESCRIPTION:".$_POST['name']."
TRIGGER:-PT1H
END:VALARM
END:VEVENT
END:VCALENDAR";
        
    header( 'Content-Type: text/calendar' );
    header( 'Content-Disposition: attachment; filename="appointment.ics";' );

    // clean output buffer
    ob_end_clean();

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

    fclose($handle);

    // flush buffer
    ob_flush();

    exit();
}

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

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

if(isset($_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);

    if($result)
    {
        if($watch == 1)
        {
            prnMsg('Added to watchlist','success');
        }
        else
        {
            prnMsg('Removed from watchlist','info');   
        }
    }
}

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

$MinView = false;
if(isset($_GET['MinView']) && $_GET['MinView'] == '1')
{
    $MinView = true;
    
    $switch_btn = '<a class="btn btn-default" href="'.$_SERVER['PHP_SELF'].'"><span class="glyphicon glyphicon-phone"></span></a>';
}
else
{
    $switch_btn = '<a class="btn btn-default" href="'.$_SERVER['PHP_SELF'].'?MinView=1"><span class="glyphicon glyphicon-tasks"></span></a>';
}

$is_search = false;
$where = 'WHERE lms_leads.id > 0 ';
if(isset($_POST['search']))
{
    $is_search = true;
    if(!empty($_POST['name']))
    {
        $name = $_POST['name'];
        $where .= 'AND lms_leads.name LIKE "%'.$name.'%" ';
    }

    if(!empty($_POST['contactno']))
    {
        $contactno = $_POST['contactno'];
        $where .= 'AND lms_leads.contactno LIKE "%'.$contactno.'%" ';
    }

    if(!empty($_POST['email']))
    {
        $email = $_POST['email'];
        $where .= 'AND lms_leads.email LIKE "%'.$email.'%" ';
    }

    if(!empty($_POST['status']))
    {
        $status = $_POST['status'];
        $where .= 'AND lms_leads.status = "' . $status . '" ';
    }
}
else
{
    $where .= "AND lms_status.probability > 0 ";
}

if(!$ViewAll)
{
    $where .= 'AND lms_leads.owner = "'.$_SESSION['UserID'].'"';
}

if($MinView)
{
    $sort = "ORDER BY lms_leads.name";
}
else
{
    $sort = "ORDER BY lms_leads.lastupdated DESC";
}


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

?>

<script>
$(document).ready(function(){
  $("#QuickSearch").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#LeadDataTable tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });

  $('[data-toggle="tooltip"]').tooltip(); 
  $('[data-toggle="popover"]').popover();
});
</script>

<div class="row">
    <div class="col-sm-12">
        <button class="btn btn-info" data-toggle="collapse" data-target="#search">Find <span class="glyphicon glyphicon-search"></span></button>
        <a class="btn btn-info" href="lms_Leads.php">Add Contact <span class="glyphicon glyphicon-plus"></span></a>
        <?php echo $switch_btn; ?>
        <button class="btn btn-default" onClick="window.location.reload();"><span class="glyphicon glyphicon-refresh"></span></button>
        <div id="search" class="collapse<?php echo (($is_search) ? ' in' : ''); ?>">
            <br>
            <form class="form-inline" method="post">
                <div class="form-group form-group-sm">
                    <label for="name">Name:</label>
                    <input type="text" class="form-control" placeholder="Name" name="name" value="<?php echo (isset($name) ? $name : '' ); ?>">
                </div>
                <div class="form-group form-group-sm">
                    <label for="contactno">Contact No:</label>
                    <input type="text" class="form-control" placeholder="Contact No" name="contactno" value="<?php echo (isset($contactno) ? $contactno : '' ); ?>">
                </div>
                
                <!-- <div class="form-group form-group-sm">
                    <label for="email">Email:</label>
                    <input type="text" class="form-control" placeholder="Email" name="email" value="<?php echo (isset($email) ? $email : '' ); ?>">
                </div> -->

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

                <div class="form-group form-group-sm">
                    <input type="hidden" name="FormID" value="<?php echo $_SESSION['FormID']; ?>" />
                    <button type="submit" name="search" class="btn btn-default">Go</button>
                    <button type="submit" name="reset" class="btn btn-default">Reset</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-sm-12">
        <h2>Contacts</h2>
        <input class="form-control" id="QuickSearch" type="text" placeholder="Search..">
    </div>
</div>

<br>

<div class="row">
    <div class="col-sm-12">

<?php
if(!$MinView)
{
?>
    <div class="table-responsive">
            <table class="table table-condensed table-hover table-striped">
            <thead>
                <tr>
                    <th class="ascending"><span class="glyphicon glyphicon-sort"></span> Last Update</th>
                    <th class="ascending"><span class="glyphicon glyphicon-sort"></span> Status</th>
                    <th class="ascending"><span class="glyphicon glyphicon-sort"></span> Name</th>
                    <th>Contact</th>
                    <th style="min-width:100px;" class="ascending"><span class="glyphicon glyphicon-sort"></span> Last View</th>
                    <th style="min-width:70px;" class="ascending"><span class="glyphicon glyphicon-sort"></span> Views</th>
                    <th></th>
                    <th>Remarks</th>
                    <?php
                    if($ViewAll)
                    {
                    ?>
                    <th style="min-width:75px;" class="ascending"><span class="glyphicon glyphicon-sort"></span> Owner</th>
                    <?php
                    }
                    ?>
                    <th class="ascending"><span class="glyphicon glyphicon-sort"></span>Watch</th>
                    <th style="text-align:right; min-width:170px;">Action</th>
                </tr>
            </thead>
<?php
}
else
{
?>
        <table class="table table-condensed table-hover table-striped">
            <thead>
                <tr>
                    <th class="ascending"><span class="glyphicon glyphicon-sort"></span> Name</th>
                    <th style="min-width:70px;" class="ascending"><span class="glyphicon glyphicon-sort"></span> Views</th>
                    <?php
                    if($ViewAll)
                    {
                    ?>
                    <th class="ascending"><span class="glyphicon glyphicon-sort"></span> Owner</th>
                    <?php
                    }
                    ?>
                    <th></th>
                    <th style="text-align:right; min-width:120px;">Action</th>
                </tr>
            </thead>
<?php
}
?>
                <tbody id="LeadDataTable">
                    <?php
                    $sql = "SELECT lms_leads.id,
                                    lms_leads.name,
                                    lms_leads.contactno,
                                    lms_leads.email,
                                    lms_leads.remarks,
                                    lms_leads.status,
                                    lms_leads.lastupdated,
                                    lms_leads.lastappointment,
                                    lms_leads.location,
                                    lms_leads.company,
                                    COUNT(lms_viewstat.view) AS views,
                                    MAX(lms_viewstat.view) AS last_view,
                                    lms_leads.owner,
                                    lms_leads.watch
                            FROM lms_leads
                            LEFT JOIN lms_viewstat
                            ON lms_leads.id = lms_viewstat.lead_id
                            LEFT JOIN lms_status
                            ON lms_status.id = lms_leads.status
                            ".$where."
                            GROUP BY lms_leads.id
                            " . $sort;

                    $result = DB_query($sql);
                    while($myrow = DB_fetch_array($result))
                    {
                        $last_updated = empty($myrow['lastupdated']) ? '-' : date('Y-m-d H:i:s', strtotime($myrow['lastupdated']));
                        $last_view = empty($myrow['last_view']) ? '-' : date('Y-m-d', strtotime($myrow['last_view']));


                        if(strlen($myrow['remarks']) > 30)
                        {
                            $trimmed_text = substr($myrow['remarks'], 0, 30);
                            // $myrow['remarks'] = '<a data-toggle="tooltip" title="'.$myrow['remarks'].'">' . $trimmed_text . '...</a>';
                            $myrow['remarks'] = '<a data-toggle="popover" data-placement="auto top" data-html="true" data-content="'.nl2br($myrow['remarks']).'">' . $trimmed_text . '...</a>';
                        }
                        
                        if(!$MinView)
                        {
                            echo '<tr>
                                    <td>'.$last_updated.'</td>
                                    <td>'.$status_list[$myrow['status']]['label'].'</td>
                                    <td>'.$myrow['name'].'</td>
                                    <td>'.$myrow['contactno'].'</td>
                                    <td>'.$last_view.'</td>
                                    <td class="number">'.$myrow['views'].'</td>
                                    <td>
                                        <form class="form-inline" method="post" action="lms_LeadsReportViews.php" target="_blank">
                                            <input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />
                                            <input type="hidden" name="lead" value="' . $myrow['id'] . '" />
                                            <button type="submit" name="view" class="btn btn-default">View <span class="glyphicon glyphicon-stats"></span></button>
                                        </form>
                                    </td>
                                    <td>'.$myrow['remarks'].'</td>
                                    '.($ViewAll ? '<td>'.$myrow['owner'].'</td>' : '').'

                                    <td>' . ($myrow['watch'] == 1 ? '<span class="glyphicon glyphicon-heart"></span>' : '<span class="glyphicon glyphicon-heart-empty"></span>') . '</td>
                                    <td style="text-align:right;">
                                        <span style="display:none;">'.$myrow['location'].'</span>
                                        <form class="form-inline" method="post" target="_blank">
                                            <input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />
                                            <input type="hidden" name="lead" value="' . $myrow['id'] . '" />
                                            <input type="hidden" name="name" value="' . $myrow['name'] . '" />
                                            <div class="btn-group">
                                                <button type="button" class="btn btn-default " data-toggle="modal" data-target="#'.sha1($myrow['id']).'"><span class="glyphicon glyphicon-info-sign"></span></button>
                                            </div>
                                            <button type="submit" formaction="lms_LeadEdit.php" name="edit" class="btn btn-default">Edit <span class="glyphicon glyphicon-edit"></span></button>
                                        </form>
                                    </td>
                                </tr>';
                        }
                        else
                        {
                            echo '<tr>
                                    <td>'.$myrow['name'].'<span style="display:none;">'.$myrow['contactno'].'</span></td>
                                    <td class="number">'.$myrow['views'].'</td>
                                    '.($ViewAll ? '<td>'.$myrow['owner'].'</td>' : '').'
                                    
                                    <td>' . ($myrow['watch'] == 1 ? '<span class="glyphicon glyphicon-heart"></span>' : '') . '</td>
                                    <td style="text-align:right;">
                                        <form class="form-inline" method="post" target="_blank">
                                            <input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />
                                            <input type="hidden" name="lead" value="' . $myrow['id'] . '" />
                                            <input type="hidden" name="name" value="' . $myrow['name'] . '" />
                                            <input type="hidden" name="date" value="' . date('Y-m-d', strtotime($myrow['lastappointment'])) . '" />
                                            <input type="hidden" name="hh" value="' . date('H', strtotime($myrow['lastappointment'])) . '" />
                                            <input type="hidden" name="mm" value="' . date('i', strtotime($myrow['lastappointment'])) . '" />

                                            <div class="btn-group">
                                                <button type="submit" formaction="lms_LeadsReportViews.php" name="view" class="btn btn-sm btn-default"><span class="glyphicon glyphicon-stats"></span></button>
                                                <button type="button" class="btn btn-sm btn-default " data-toggle="modal" data-target="#'.sha1($myrow['id']).'"><span class="glyphicon glyphicon-info-sign"></span></button>
                                            </div>
                                            <button type="submit" formaction="lms_LeadEdit.php" name="edit" class="btn btn-sm btn-default"><span class="glyphicon glyphicon-edit"></span></button>
                                        </form>
                                    </td>
                                </tr>';
                        }

                        echo '<div id="'.sha1($myrow['id']).'" class="modal fade" role="dialog">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                                            <h4 class="modal-title"><span class="glyphicon glyphicon-user"></span> '.$myrow['name'].'</h4>
                                        </div>
                                        <div class="modal-body">
                                            
                                            '. (!empty($myrow['contactno']) ? '
                                            <div class="form-group">
                                                <label for="contactno"><span class="glyphicon glyphicon-earphone"></span> Contact No :</label>
                                                <ul class="list-inline form-control-static"><li><a href="tel:'.$myrow['contactno'].'">'.$myrow['contactno'].'</a></li><li><a class="small" href="https://wa.me/'.trim($myrow['contactno'], '+').'?" target="_blank">WhatsApp <span class="glyphicon glyphicon-share"></span></a></li></ul>
                                            </div>' : '') .'

                                            '. (!empty($myrow['company']) ? '
                                            <div class="form-group">
                                                <label for="company"><span class="glyphicon glyphicon-tag"></span> Company (<a href="https://www.google.com/maps/search/?api=1&query=' . $myrow['company'] . '" target="_blank">View Location</a>):</label>
                                                <p class="form-control-static">'.$myrow['company'].'</p>
                                            </div>' : '') .'

                                            '. (!empty($myrow['location']) ? '
                                            <div class="form-group">
                                                <label for="location"><span class="glyphicon glyphicon-map-marker"></span> Location (<a href="https://www.google.com/maps/search/?api=1&query=' . $myrow['location'] . '" target="_blank">View</a>):</label>
                                                <pre class="form-control-static">'.$myrow['location'].'</pre>
                                            </div>' : '') .'

                                            ' . ((is_null($myrow['lastappointment']) || (date('Y-m-d', strtotime($myrow['lastappointment'])) < date('Y-m-d'))) ? '' :
                                            '<div class="form-group">
                                                <label for="appointment"><span class="glyphicon glyphicon-calendar"></span> Appointment :</label>
                                                <form class="form-inline" method="post" target="_blank">
                                                    <input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />
                                                    <input type="hidden" name="date" value="' . date('Y-m-d', strtotime($myrow['lastappointment'])) . '" />
                                                    <input type="hidden" name="hh" value="' . date('H', strtotime($myrow['lastappointment'])) . '" />
                                                    <input type="hidden" name="mm" value="' . date('i', strtotime($myrow['lastappointment'])) . '" />
                                                    <input type="hidden" name="lead" value="' . $myrow['id'] . '" />
                                                    <input type="hidden" name="name" value="' . $myrow['name'] . '" />
                                                    <button type="submit" name="get_appointment" class="btn btn-link">'.date('Y-m-d g:ia', strtotime($myrow['lastappointment'])).'</button>
                                                </form>
                                            </div>') .'

                                            <div class="form-group">
                                                <form class="form-inline" method="post">
                                                    <input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />
                                                    <input type="hidden" name="lead" value="' . $myrow['id'] . '" />
                                                    <label for="contactno"><span class="glyphicon glyphicon-heart"></span> Watch list </label>
                                                    <label><input type="checkbox" name="watchlist" value="Y" onChange="this.form.submit()" ' . (($myrow['watch'] == 1) ? 'checked' : '') . '></label>
                                                </form>
                                            </div>
                                        </div>
                                        <div class="modal-footer">
                                            <form class="form-inline" method="post" target="_blank">
                                                <input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />
                                                <input type="hidden" name="lead" value="' . $myrow['id'] . '" />
                                                <button type="submit" formaction="lms_LeadAppointment.php" name="edit" class="btn btn-primary">Set Appointment</button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>';
                    }
                    ?>
                </tbody>
            </table>
        
        <?php
        if(!$MinView)
        {
            echo '</div>'; // close table-responsive
        }

        if(DB_num_rows($result) == 0) {
            if($is_search)
            {
                echo '<div class="jumbotron text-center">
                        <h2>No Result(s) Found!</h2>
                        <h3>Try changing the search criteria</h3>
                    </div>';
            }
            else
            {
                echo '<div class="jumbotron text-center">
                        <h2>You do not have any contacts yet!</h2>
                        <h2><a class="btn btn-lg btn-info" href="lms_Leads.php">Add Contact</a> to begin</h2>
                    </div>';
            }
        }
        ?>
    </div>
</div>    
<?php
include('includes/footer.php');
?>
