<?php

$reports["_LINKEDIN_TOTAL_FOLLOWERS"] = Array(
    "ClassName" => "LinkedinTotalFollowers",
    "Category" => "_LINKEDIN",
    "icon" => "",
    "Options" => "displaymode",
    "Filename" => "linkedin_total_followers",
    "Distribution" => "Premium",
    "Order" => 4,
    "ReportVersion" => 1.0,
    "MinimumVersion" => 3.0,
    "EmailAlerts" => false,
    "Update" => false
);

class LinkedinTotalFollowers extends Report {
    function Settings() {
        $this->DisplayModes = "table,linechart";
        $this->DefaultDisplay = "linechart";
        if(empty($this->displaymode)){
          $this->displaymode = $this->DefaultDisplay;
        }
        $this->columnDefinitions[] = Array("Label" => "_DATE");
        $this->columnDefinitions[] = Array("Label" => "Followers");
        

        $this->help =  _DEFINITIONS_FOR_THIS_REPORT.':<ul>
        <li>'._TOTAL_FOLLOWERS_DESC.'</li></ul>';

        if(empty($this->companyID) || $this->companyID == 'null'){
            $this->companyID = $this->profile->GetOtherSettings('linkedincid','');
        }  else {
            $this->profile->SetOtherSettings('linkedincid',$this->companyID);
        }
    }

    function DisplayCustomForm() {
        $id = "O" . md5(time()) . rand(0,1000);
        echo "<div id='{$id}' class='form-group'>
            <label for='author'>CompanyID:</label>
            <select  name='companyID' class='form-control'></select>
        </div>";
        ?> 
        <script type="text/javascript">
        function linkedInCallback_<?php echo $id; ?>(result){
            if(result.Status == undefined){
                console.log("Error in response: ",result);
                return false;
            }

            if(result.Status == "Error"){
                $("#<?php echo $id; ?>").html(result.Result);
                rurl = window.location.href + "&label=<?php echo $this->labels; ?>";
                var u = $("#<?php echo $id; ?> .auth-button").attr("href") + "?profile=<?php echo $this->profile->profilename; ?>&return_url=" + php_urlencode(rurl);
                $("#<?php echo $id; ?> .auth-button").attr("href" , u);
            } else {
                var select = $('#<?php echo $id; ?> [name="companyID"]');
                $.each(result.Result.values, function(k, v){
                  var option = document.createElement("option");
                  option.text = v.name;
                  option.value = v.id;
                  select.append(option);
                });
            }
        }
        </script>
        <script src="https://software.logaholic.com/linkedin/Linkedin.php?action=list&rid=<?php echo $id . '&profile='.$this->profile->profilename; ?>"></script>
        <?php
    }

    function DisplayReport() {
        $this->reportHeader();
        
        $months = [];
        for ($i=1; $i <= 12; $i++) { 
            $months[$i] = LogaDate(array("F"), mktime(0,0,0,$i,1,2016) );
        }

        $id = "LI" . md5(time()) . rand(0,1000);

        if(empty($this->companyID)){              
            echoWarning($this->SettingsButton(). _AUTHORIZE_ACCOUNT_IN_SETTINGS);
            return false;
        } else {
            echo "<div id='warn_$id'>";
            echoWarning($this->SettingsButton(). _AUTHORIZE_ACCOUNT_IN_SETTINGS,"display:none");
            echo "</div>";
        }

        if($this->displaymode == 'table'){
          echo "<table id='{$id}' class='report_table'></table>";
        } else {
          echo "<div id='$id' class='linechart' data-ticks='' data-chartoptions='".json_encode($this->chartoptions)."' data-chart='' data-limit='' data-coldefs='".json_encode($this->columnDefinitions)."'></div>";
        }

        ?>
        <script type="text/javascript">
        function linkedInCallback_<?php echo $id; ?>(result){
            if(result.Status == "Error"){
                if (result.Result == "not authorized") {
                    $("#<?php echo 'warn_'.$id; ?> .alert-danger").show();

                }
            }
            <?php if($this->displaymode == 'table'){
                  echo "LiTable_{$id}(result);";
                } else {
                  echo "LiGraph_{$id}(result);";
            } ?>
        }
          
        function LiTable_<?php echo $id; ?>(result) {
            var dataset = [];

            if(result.Result.errorCode != undefined) {
                console.log(result.Result);
                $("#<?php echo 'warn_'.$id; ?> .alert-danger").show();
                return false;
            }
            
            result = result.Result.followStatistics.countsByMonth.values;

            result.reverse();

            var months = <?php echo json_encode($months); ?>;

            $.each(result, function(k,v){
                var d = months[v.date.month] + " " + v.date.year;
                dataset.push([d,v.totalCount]);
            });

            $("#<?php echo $id; ?>").DataTable( {
              "aaSorting": [],
              "iDisplayLength" : dataset.length,
              data : dataset,
              sDom : 't',
              columns : [
                { title: "<?php echo _DATE;?>" },
                { title: "<?php echo _TOTAL_FOLLOWERS;?>" }
              ]
            });
          }


          function LiGraph_<?php echo $id; ?>(result) {

            var dataset = [
                {
                    key : '<?php echo _TOTAL_FOLLOWERS;?>',
                    disabled : false,
                    area : true,
                    values : []
                }
            ];

            if(result.Result.errorCode != undefined) {
                console.log(result.Result);
                $("#<?php echo 'warn_'.$id; ?> .alert-danger").show();
                return false;
            }

            // shorten data to the set we need
            result = result.Result.followStatistics.countsByMonth.values;

            // reverse the dataset
            result.reverse();

            var xticks = [];

            var i = 0;
            
            var months = <?php echo json_encode($months); ?>;

            $.each(result, function(k,v){            
                xticks.push(months[v.date.month] + " " + v.date.year);
                dataset[0].values.push([i, v.totalCount]);
                i++;
              });

              $("#<?php echo $id; ?>").attr("data-ticks", JSON.stringify(xticks) );
              $("#<?php echo $id; ?>").attr("data-chart",JSON.stringify(dataset) );
              lg.LineChart("<?php echo $id; ?>");
          }

          
        </script>
        <script src="https://software.logaholic.com/linkedin/Linkedin.php?action=stats&cid=<?php echo $this->companyID; ?>&rid=<?php echo $id; ?>&profile=<?php echo $this->profile->profilename; ?>"></script>

        <?php
    }
}
