<?php

/**
 * Constant that is checked in included files to prevent direct access.
 * define() is used in the installation folder rather than "const" to not error for PHP 5.2 and lower
 */
define('_JEXEC', 1);
define('PHOTOS_DIR',  'https://suntendervaluations.com/media/com_jobs/task/'); 
date_default_timezone_set("America/Los_Angeles");
if (file_exists(__DIR__ . '/defines.php'))
{
	include_once __DIR__ . '/defines.php';
}

if (!defined('_JDEFINES'))
{
	define('JPATH_BASE', __DIR__);
	require_once JPATH_BASE . '/includes/defines.php';
}

require_once JPATH_BASE . '/includes/framework.php';

// Set profiler start time and memory usage and mark afterLoad in the profiler.
JDEBUG ? JProfiler::getInstance('Application')->setStart($startTime, $startMem)->mark('afterLoad') : null;

$countyfee = file_get_contents(JPATH_ROOT.'/logs/averagetime.txt'); 

$countyfee = json_decode($countyfee,true);

// Instantiate the application.
$app = JFactory::getApplication('site'); 
$db = jfactory::getdbo();
if($_GET['averagetime'] == 1){
    ?>    
    <link href="https://mottie.github.io/tablesorter/docs/css/jq.css" rel="stylesheet">
      <link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
    <!--<script src="https://code.jquery.com/jquery-3.6.0.js"></script>-->
      <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/css/theme.default.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/jquery.tablesorter.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/jquery.tablesorter.widgets.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/extras/jquery.tablesorter.pager.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <style>  
    .divwap{width:100%; height:100%; position: fixed; z-index:9999;  background-color:rgba(0,30,10,0.5);top: 0px;left: auto;} 
    .contentview{width:760px; height:500px; position: relative; margin: 100px auto 30px auto; padding:20px; background-color: #fff;} 
    .hidetooltip{    
        float: right;
        font-size: 20px;
        font-weight: bold;
    }
    .setcontentview
    {
        height: 470px;
        overflow-x: auto;
    }
    .showtooltip{
        color:blue; 
        text-decoration: none;
    }
    </style>
    <script>
        $( document ).ready(function() {
            $(".showtooltip").on("click", function(event) {
                event.preventDefault();
                var id = $(this).attr('href');
                console.log('id='+id);
                $('.setcontentview').html($(id).html());
                $('.divwap').show();
            });
            $(".hidetooltip").on("click", function() {
                $('.divwap').hide();
            });
        });
        <?php 
        if(1 == 0){
            ?>
            $(function(){
                $('#maintabvl').tablesorter({
                    theme: 'blackice',
                    widthFixed: false,
                    showProcessing: false,
                    headerTemplate: '{content}',
                    onRenderTemplate: null, 
                    onRenderHeader: function (index) {
                        $(this).find('div.tablesorter-header-inner').addClass('roundedCorners');
                    },
                
                    cancelSelection: true,
                    dateFormat: "mmddyyyy",
                    sortMultiSortKey: "shiftKey",
                    sortResetKey: 'ctrlKey',
                    usNumberFormat: true,
                    delayInit: false,
                    serverSideSorting: false,
                    headers: {
                        0: {
                            sorter: "text",sortInitialOrder: 'desc'
                        },
                        6: {
                            sorter: "digit"
                        }
                    },
                    
                    ignoreCase: true,
                    sortForce: null,
                    sortList: [
                        [0, 1],
                        [1, 0],
                        [2, 0]
                    ],
                
                    sortAppend: null,
                    sortInitialOrder: "asc",
                    sortLocaleCompare: false,
                    sortReset: false,
                    sortRestart: false,
                    emptyTo: "bottom",
                    stringTo: "max",
                    
                    textExtraction: {
                        0: function (node) {
                            return $(node).text();
                        },
                        1: function (node) {
                            return $(node).text();
                        }
                    },
                
                    textSorter: null,
                    initWidgets: true,
                    widgets: ['zebra', 'columns', "filter" ],
                    widgetOptions: {
                        
                        zebra: [
                            "ui-widget-content even",
                            "ui-state-default odd"],
                        uitheme: 'jui',
                        columns: [
                            "primary",
                            "secondary",
                            "tertiary"],
                        columns_tfoot: true,
                        columns_thead: true,
                        filter_childRows: false,
                        filter_columnFilters: true,
                        filter_cssFilter: "tablesorter-filter",
                        filter_functions: null,
                        filter_hideFilters: false,
                        filter_ignoreCase: true,
                        filter_reset: null,
                        filter_searchDelay: 300,
                        filter_serversideFiltering: false,
                        filter_startsWith: false,
                        filter_useParsedData: false,
                        resizable: true,
                        saveSort: true,
                        stickyHeaders: "tablesorter-stickyHeader"
                    },
                
                
                    initialized: function (table) {},
                
                    // *** CSS CLASS NAMES ***
                    tableClass: 'tablesorter',
                    cssAsc: "tablesorter-headerSortUp",
                    cssDesc: "tablesorter-headerSortDown",
                    cssHeader: "tablesorter-header",
                    cssHeaderRow: "tablesorter-headerRow",
                    cssIcon: "tablesorter-icon",
                    cssChildRow: "tablesorter-childRow",
                    cssInfoBlock: "tablesorter-infoOnly",
                    cssProcessing: "tablesorter-processing",
                    selectorHeaders: '> thead th, > thead td',
                    selectorSort: "th, td",
                    selectorRemove: "tr.remove-me",
                    debug: false
                
                }).tablesorterPager({
                    container: $(".pager"),
                    ajaxUrl: null,
                    ajaxProcessing: function(ajax) {
                        if (ajax && ajax.hasOwnProperty('data')) {
                            // return [ "data", "total_rows" ]; 
                            return [ajax.data, ajax.total_rows];
                        }
                    },
                    output: '{startRow} to {endRow} ({totalRows})',
                    updateArrows: true,
                    page: 0,
                    size: 100,
                    fixedHeight: true,
                    removeRows: false,
                    cssNext: '.next',
                    cssPrev: '.prev',
                    cssFirst: '.first',
                    cssLast: '.last',
                    cssGoto: '.gotoPage',
                    cssPageDisplay: '.pagedisplay',
                    cssPageSize: '.pagesize',
                    cssDisabled: 'disabled'
                });
                
                $.extend($.tablesorter.themes.jui, {
                    table: 'ui-widget ui-widget-content ui-corner-all', // table classes
                    header: 'ui-widget-header ui-corner-all ui-state-default', // header classes
                    icons: 'ui-icon', // icon class added to the <i> in the header
                    sortNone: 'ui-icon-carat-2-n-s',
                    sortAsc: 'ui-icon-carat-1-n',
                    sortDesc: 'ui-icon-carat-1-s',
                    active: 'ui-state-active', // applied when column is sorted
                    hover: 'ui-state-hover', // hover class
                    filterRow: '',
                    even: 'ui-widget-content', // even row zebra striping
                    odd: 'ui-state-default' // odd row zebra striping
                });
                $( '.sadasdasd' ).tooltip();
            });
            <?php
        }
        ?>
    </script>
    <?php
    $sql = "SELECT * FROM `#__users`";
    $db->setquery($sql);
    $dbusers = $db->loadobjectlist();
    $arrusers = array();
    foreach($dbusers as $obj){
        $arrusers[$obj->id] = $obj;
    }
    $year = 2023;
    $year = date('Y');
    //echo '<pre>'; print_r($dbusers[0]); print_r($arrusers[0]);die();
    //send accept
    $sql = "SELECT * FROM `#__jobs_task_comment`"
            . " WHERE ( `comment` LIKE 'Approved counter of %' OR `comment` LIKE 'accepted' OR `comment` LIKE 'Approved recounter') and `date_created` > '".date('Y-m-d', time()-84600*180 )."' ORDER BY `id` ASC ";
    $db->setquery($sql);
    $checkedit = $db->loadobjectlist();
    //echo '<pre>'; print_r($checkedit[0]);
    $alledits = $checkedits = array();
    $alledits1 = $checkedits1 = array();
    foreach ($checkedit as $r){
        $checkedits[$r->task_id][] = $r->date_created;
        $checkedits1[$r->task_id][] = $r;
    }
    //send invite
    $sql = "SELECT * FROM `#__jobs_task_comment` where  `comment` like '%Auto Invite:%' or `comment` like '%Auto - Invite to appraiser%' or `comment` like 'Assign to appraiser' or `comment` like '%Enter articular appraiser%' and `date_created` > '".date('Y-m-d', time()-84600*180 )."' ORDER BY `id` ASC";
    $db->setquery($sql);
    $alledit = $db->loadobjectlist();
    //echo '<pre>'; print_r($alledit[0]);
    
    foreach ($alledit as $r){
        $alledits[$r->task_id][] = $r->date_created;
        $alledits1[$r->task_id][] = $r;
    }
    //send bid
    $sql = "SELECT * FROM `#__jobs_task_counter` where  `date_created` > '".date('Y-m-d', time()-84600*180 )."' ORDER BY `id` ASC";
    $sql = "SELECT * FROM `#__jobs_task_counter` where `old` = 0 and `date_created` > '".date('Y-m-d', time()-84600*180 )."' ORDER BY `id` ASC";
    $db->setquery($sql);
    $alleditbid = $db->loadobjectlist();
    //echo '<pre>'; print_r($alleditbid[0]);die();
    //echo '<pre>';
    foreach ($alleditbid as $r){
        $alleditbids[$r->task_id][] = $r;
        if($r->old == 1){
            //echo '<br/>';print_r($r);
        }
    }
    
    $sql = "SELECT * FROM `#__jobs_task` where  `date_created` > '{$year}-01-01'   ORDER BY `id` ASC";
    //$sql = "SELECT * FROM `#__jobs_task` where  `date_created` > '{$year}-01-01'  ORDER BY `id` ASC limit 0,1000";
    $db->setquery($sql);
    $tasks = $db->loadobjectlist();
    //echo '<br/>count='.count($tasks);    
    $ggstate = array();
    //echo '<pre>';
    foreach ($tasks as $r){  
        $arroldbids = array();
        $arrnewbids = array();
        $arrbids = array();
        $arraccept = array();    
        $arrinvite = array();    
        $arraccept1 = array();    
        $arrinvite1 = array();   
        $t = $t1 = $t2 = 0;
        $countbid = $countbid1 = 0;   
        $minbid = 0;
        $totalfee = 0;
        if(isset($alleditbids[$r->id])){   
            $arrbids = $alleditbids[$r->id];
            //echo '<pre>'; print_r($arrbids);die();
        }
        if(isset($alledits[$r->id])){ 
            $arrinvite = $alledits[$r->id];      
            $arrinvite1 = $alledits1[$r->id];    
        }
        if(isset($checkedits[$r->id])){ 
            $arraccept = $checkedits[$r->id];    
            $arraccept1 = $checkedits1[$r->id];   
        }
        $countbid = count((array)$arrbids);
        $timefirstbid = $timelastbid = $endinvite = $endaccept = $beginaccept = $begininvite = '';
        if($countbid > 0){
            if(count((array)$arraccept) < count((array)$arrinvite)){
                $newinvite = array();
                $newinvite1 = array();
                $ico = count((array)$arraccept);
                foreach($arrinvite as $pos => $add){
                    if($pos >= $ico){
                        break;
                    }
                    $newinvite[] = $add;
                }
                foreach($arrinvite1 as $pos => $add){
                    if($pos >= $ico){
                        break;
                    }
                    $newinvite1[] = $add;
                }
                $arrinvite = $newinvite;
                $arrinvite1 = $newinvite1;
            }
        }
        if($countbid > 0 && isset($alledits[$r->id])){  
            $obfirstbid = $arrbids[0];
            $oblastbid = $arrbids[count($arrbids) - 1];
            $timefirstbid = $obfirstbid->date_created;       
            $begininvite = $arrinvite[0];  
            $endinvite = end($arrinvite);  
            $timelastbid = $oblastbid->date_created; 
            if(strtotime($timefirstbid) < strtotime($endinvite)){
                foreach($arrbids as $obk){
                    if(strtotime($obk->date_created) > strtotime($endinvite)){
                        $obfirstbid = $obk;
                        $timefirstbid = $obfirstbid->date_created;       
                        break;
                    }
                }
            }
            if(strtotime($timefirstbid) < strtotime($endinvite)){
                if(count((array)$arrinvite) > 1){
                    $endinvite = $arrinvite[count($arrinvite) - 2];
                }
                //$endinvite = $begininvite;
            }
            $t1 = strtotime($timefirstbid) - strtotime($endinvite);
            $t2 = strtotime($timelastbid) - strtotime($endnivite);
            if($t1 < 0){
                $t1 = 0;
            }
            if($t2 < 0){
                $t2 = 0;
            }
            if($r->order_number == '202410280077' && 1 == 0){
                echo '<br/>order_number='.$r->order_number;
                echo '<br/>t1='.$t1;
                echo '<br/>t2='.$t2;
                echo '<br/>timefirstbid='.$timefirstbid;
                echo '<br/>timelastbid='.$timelastbid;
                echo '<br/>endinvite='.$endinvite;
                echo '<pre><br/>'; print_r($arrbids);print_r($arrinvite);die();
            }
            if($t1 < 0 && 1 == 0){
                echo '<br/>order_number='.$r->order_number;
                echo '<br/>t1='.$t1;
                echo '<br/>timefirstbid='.$timefirstbid;
                echo '<br/>endinvite='.$endinvite;
                echo '<pre><br/>'; print_r($arrbids);print_r($arrinvite);die();
            }
            if($t2 < 0 && 1 == 0){
                echo '<br/>order_number='.$r->order_number;
                echo '<br/>t2='.$t2;
                echo '<br/>timelastbid='.$timelastbid;
                echo '<br/>endinvite='.$endinvite;
                echo '<pre><br/>'; print_r($arrbids);print_r($arrinvite);die();
            }
        }
        if(isset($checkedits[$r->id]) && isset($alledits[$r->id])){
            $endaccept = end($arraccept);      
            $endinvite = end($arrinvite);     
            $beginaccept = $arraccept[0];      
            $begininvite = $arrinvite[0]; 
            if(strtotime($endinvite) > strtotime($endaccept)){
                for($i = count($arrinvite) - 1; $i >= 0; $i--){
                    $endinvite1 = $arrinvite[$i];
                    if(strtotime($endinvite1) < strtotime($endaccept)){
                        $endinvite = $endinvite1;
                        break;
                    }
                }
            }    
            //$t = strtotime($beginaccept) - strtotime($begininvite);     
            
            $t = strtotime($endaccept) - strtotime($endinvite);
            if($t < 0){
                $t = 0;
            }
            if($t > 86400/3 ){
                $t = 0;
            }
            if($endaccept == '' || $endinvite == ''){
                $t = 0;
            }
            //if($r->order_number == '202405130038' && 1 == 1){
            if($t < 0 && 1 == 0){
                echo '<br/>t='.$t;
                echo '<br/>order_number='.$r->order_number;
                echo '<pre><br/>'; print_r($arrinvite);print_r($arraccept);//die();
            }
        }
        foreach($arrbids as $obj){
            if($obj->appraiser_fee != ''){
                $totalfee += $obj->appraiser_fee;
            }
            if($obj->old == 1){
                //echo '<pre>'; print_r($r); print_r($obj);//die();
                $arroldbids[] = $obj;
            }
            else{
                $arrnewbids[] = $obj;
            }
        }
        if($countbid > 0){
            $minbid = $totalfee / $countbid;
        }  
        $info = array();
        $info['order'] = $r;
        $info['bid'] = $arrbids;
        $info['oldbid'] = $arroldbids;
        $info['newbid'] = $arrnewbids;
        $info['invite'] = $arrinvite;
        $info['accept'] = $arraccept;
        $info['invite1'] = $arrinvite1;
        $info['accept1'] = $arraccept1;
        if($countbid > 0 && count((array)$arrinvite) > 0 && count((array)$arraccept) > 0 && $t > 0){
            $ggstate[$r->property_state][$r->property_county]['bid'][] = $countbid;
            $ggstate[$r->property_state][$r->property_county]['time1st'][] = $t1; 
            $ggstate[$r->property_state][$r->property_county]['lasttime'][] = $t2; 
            $ggstate[$r->property_state][$r->property_county]['time'][] = $t; 
            $ggstate[$r->property_state][$r->property_county]['minbid'][] = $minbid;    
            $ggstate[$r->property_state][$r->property_county]['info'][] = $info;     
            if($r->property_state == 'Florida' && $r->property_county == 'Osceola County' && 1 == 0){
                echo '<br>arrbids='; print_r($arrbids);
                echo '<br>invite='.$endinvite;
                echo '<br>timefirstbid='.$timefirstbid;
                echo '<br>timelastbid='.$timelastbid;
                echo '<br>endaccept='.$endaccept;
                echo '<br>t1='.$t1; 
                $hours = floor($t1 / 3600);
                $minutes = floor(($t1 / 60) % 60);
                $seconds = $t1 % 60;
                echo '<br>hours='.$hours.'|minutes='.$minutes.'|seconds='.$seconds;
                echo '<br>t2='.$t2;
                $hours = floor($t2 / 3600);
                $minutes = floor(($t2 / 60) % 60);
                $seconds = $t2 % 60;
                echo '<br>hours='.$hours.'|minutes='.$minutes.'|seconds='.$seconds;
                echo '<br>t='.$t;
                $hours = floor($t / 3600);
                $minutes = floor(($t / 60) % 60);
                $seconds = $t % 60;
                echo '<br>hours='.$hours.'|minutes='.$minutes.'|seconds='.$seconds;
            }
        }
        if(count((array)$arroldbids) > 0 && 1 == 0){
            echo '<br/>countbid='.$countbid;
            echo '<br/>t='.$t;
            echo '<br/>countbid1='.$countbid1;
            echo '<br/>t1='.$t1;
            echo '<pre>'; print_r($info);die();
        }
    }
    //echo '<pre>'; print_r($ggstate);
    function get_info_from_data($data,$arrusers){
        $infoshow = array();
        //echo '<pre>'; print_r($data);die();
        $info = $data['info'];
        //echo '<pre>'; print_r($info);die();
        $str = '';
        $totalbids = $totalinvite = 0;
        foreach($info as $obj){
            $arrbid = $obj['bid'];
            $invite = $obj['invite'];
            $totalbids += count((array)$arrbid);
            $totalinvite += count((array)$invite);
        }
        $infoshow[] = '<strong>Order Number:</strong> '.count((array)$info).' | <strong>Invite:</strong> '.$totalinvite.' | <strong>Bids:</strong> '.$totalbids;
        foreach($info as $obj){
            $arrbid = $obj['bid'];
            $oldbid = $obj['oldbid'];
            $invite = $obj['invite'];
            $accept = $obj['accept'];
            $invite1 = $obj['invite1'];
            $accept1 = $obj['accept1'];            
            $infoshow[] = '<br/>'.$obj['order']->order_number;
            if(count((array)$invite1) > 0){
                $infoshow[] = '<strong>Invite:</strong> '.count((array)$invite1);
                foreach($invite1 as $obj){
                    $infoshow[] = $arrusers[$obj->user_id]->name.': '. JHtml::_('date', $obj->date_created, 'M d, Y - h:i a', false);
                }
            }
            if(count((array)$arrbid) > 0){
                $infoshow[] = '<strong>Bids:</strong> '.count((array)$arrbid);
                foreach($arrbid as $obj){
                    $str = $arrusers[$obj->user_id]->name.': '. $obj->appraiser_fee.' : '. $obj->date_created;
                    if($obj->old == 1){
                        $str = ' (old)';
                    }
                    $infoshow[] = $str;
                }
            }
            if(count((array)$accept1) > 0){
                $infoshow[] = '<strong>Accept:</strong> '.count((array)$accept1);
                foreach($accept1 as $obj){
                    $infoshow[] = $arrusers[$obj->user_id]->name.': '. JHtml::_('date', $obj->date_created, 'M d, Y - h:i a', false);
                }
            }
        }
        return $infoshow;
    }
    ?>
    <h1 style="font-size: 40px;font-weight: bold;">Average time for invite / accept time for each state</h1>
    <table id="maintabvl" class="table table-bordered" role="grid" style="width:100%;">
        <thead>
            <tr role="row">
                <th style="width:25%"><strong>State</strong></th>
                <th colspan="6" style="padding:0px;">
                    <table class="table table-bordered" style="width:100%;margin-bottom:0px;">
                        <tbody>
                            <tr>
                                <th><strong>County</strong></th>
                                <th style="width:13.5%;text-align:center;"><strong>Bids</strong></th>
                                <th style="width:13.5%;text-align:center;"><strong>Time First Bid</strong></th>
                                <th style="width:13.5%;text-align:center;display:none;"><strong>Time Last Bid</strong></th>
                                <th style="width:13.5%;text-align:center;"><strong>Accept Time</strong></th>
                                <th style="width:13.5%;text-align:center;"><strong>Amount</strong></th>
                                <th style="width:13.5%;text-align:center;"></th>
                            </tr>
                        </tbody>
                    </table>
                </th>
            </tr> 
        </thead>
        <tbody>
            <?php 
            //echo '<pre>';print_r($arruserappraisers);
            $idn = 0;
            $datajsons = array();
            foreach($ggstate as $property_state => $arrcountys){ 
                ?>
                <tr role="row">
                    <td><?php 
                    echo $property_state;
                    ?></td>
                    <td colspan="6" style="padding:0px;">                        
                        <table class="table table-bordered" style="width:100%;margin-bottom:0px;">
                            <tbody>
                                <?php
                                foreach($arrcountys as $property_county => $obj){ 
                                    if($property_state == 'Florida' && $property_county == 'Osceola County'){
                                        //$obj['info'] = array();echo '<pre>'; print_r($obj);
                                    }
                                  
                                    $infoshow = get_info_from_data($obj,$arrusers);
                                    $strinfoshow = implode('&#10;',$infoshow);
                                    $bidv = array_sum($obj['bid'])/count($obj['bid']);
                                    //$bidv = floor($bidv);
                                    $bidv = number_format($bidv,1);
                                    $timev = array_sum($obj['time'])/count($obj['time']);
                                    $strime = $strime1 = $strime2 = '';  
                                    $itimeaccept = 0;
                                    if($timev != 0){
                                        $itimeaccept = $timev;
                                        $hours = floor($timev / 3600);
                                        $minutes = floor(($timev / 60) % 60);
                                        $seconds = $timev % 60;
                                        if($hours != 0){
                                            $strime .= $hours."hours ".$minutes."mins";
                                        }
                                        else{      
                                            if($minutes != 0){
                                                $strime .= $minutes."mins";
                                            }
                                            else{
                                                $strime .= $seconds."mins";
                                            }
                                        }    
                                    }                             
                                    $time1stv = array_sum($obj['time1st'])/count($obj['time1st']);
                                    if($time1stv != 0){
                                        $hours1 = floor($time1stv / 3600);
                                        $minutes1 = floor(($time1stv / 60) % 60);
                                        $seconds1 = $time1stv % 60;
                                        if($hours1 != 0){
                                            $strime1 .= $hours1."hours ".$minutes1."mins";
                                        }
                                        else{      
                                            if($minutes1 != 0){
                                                $strime1 .= $minutes1."mins";
                                            }
                                            else{
                                                $strime1 .= $seconds1."seconds";
                                            }
                                        }
                                    }                            
                                    $lasttimev = array_sum($obj['lasttime'])/count($obj['lasttime']);
                                    if($lasttimev != 0){
                                        $hours1 = floor($lasttimev / 3600);
                                        $minutes1 = floor(($lasttimev / 60) % 60);
                                        $seconds1 = $lasttimev % 60;
                                        if($hours1 != 0){
                                            $strime2 .= $hours1."hours ".$minutes1."mins";
                                        }
                                        else{      
                                            if($minutes1 != 0){
                                                $strime2 .= $minutes1."mins";
                                            }
                                            else{
                                                $strime2 .= $seconds1."seconds";
                                            }
                                        }
                                    }
                                    $minbidv = array_sum($obj['minbid'])/count($obj['minbid']);
                                    $minbidv = number_format($minbidv,2);
                                    ?>
                                    <tr role="row" class="sadasdasd" title="<?php //echo str_replace("'",'',$strinfoshow); ?>">
                                        <td>
                                            <?php echo $property_county; ?>
                                        </td>
                                        <td style="width:13.5%;text-align:center;" title="<?php //echo json_encode($obj['bid']); ?>">
                                        <?php echo $bidv; ?>
                                        </td>
                                        <td style="width:13.5%;text-align:center;" title="<?php //echo json_encode($obj['time1st']); ?>">
                                        <?php echo $strime1; ?>
                                        </td>
                                        <td style="width:13.5%;text-align:center;display:none;" title="<?php //echo json_encode($obj['lasttime']); ?>">
                                        <?php echo $strime2; ?>
                                        </td>
                                        <td style="width:13.5%;text-align:center;" title="<?php //echo json_encode($obj['time']); ?>">
                                        <?php echo $strime; ?>
                                        </td>
                                        <td style="width:13.5%;text-align:center;" title="<?php //echo json_encode($obj['minbid']); ?>">
                                        <?php echo $minbidv; 
                                        ?>
                                        </td>
                                        <td style="width:13.5%;text-align:center;">
                                            <a href="#divtooltip_<?php echo $idn; ?>" class="showtooltip">Detail</a>
                                        <?php    
                                        echo '<div style="display:none;" id="divtooltip_'.$idn.'">'.implode('<br/>',$infoshow).'</div>';
                                        //echo '<textarea style="width:100%;">'.json_encode($obj['info']).'</textarea>';
                                        ?>
                                        </td>
                                    </tr> 
                                    <?php
                                    $idn++;
                                    $datajsons[$property_state][$property_county][] = array(
                                        'bid' => $bidv,
                                        'time1st' => $strime1,
                                        'timelastbid' => $strime2,
                                        'timeaccept' => $strime,
                                        'itimeaccept' => $itimeaccept,
                                        'amount' => $minbidv
                                    );
                                }
                                ?>
                            </tbody>
                        </table>
                    </td>
                </tr> 
                <?php
            }
            ?> 
        </tbody>
    </table>
    <?php 
    //echo '<pre>'; print_r($datajsons);
    file_put_contents(JPATH_ROOT.'/logs/averagetime.txt',json_encode($datajsons));
    if(1 == 0){
        ?>        
        <div class="pager"> 
            <img src="https://mottie.github.io/tablesorter/addons/pager/icons/first.png" class="first"/> 
            <img src="https://mottie.github.io/tablesorter/addons/pager/icons/prev.png" class="prev"/> 
            <span class="pagedisplay"></span> <!-- this can be any element, including an input --> 
            <img src="https://mottie.github.io/tablesorter/addons/pager/icons/next.png" class="next"/> 
            <img src="https://mottie.github.io/tablesorter/addons/pager/icons/last.png" class="last"/> 
            <select class="pagesize" title="Select page size"> 
                <option value="20">20</option> 
                <option value="30">30</option> 
                <option value="50">50</option> 
                <option selected="selected" value="100">100</option> 
                <option value="all">All</option> 
            </select>
            <select class="gotoPage" title="Select page number"></select>
        </div>
        <?php
    }
    ?>
    <div class="divwap" style="display:none;">
        <div class="contentview">
            <span class="hidetooltip">X</span>
            <div class="setcontentview">
            </div>
        </div>
    </div>
    <?php    
    die;
}



$scripassign =    file_get_contents('https://suntendervaluations.com/logs/scripassign_20241018.txt');

$staffandappraiser = array();
//Anato Nguyen
$staffandappraiser[30522] = 31778;
//Andy Cai
$staffandappraiser[766] = 748;
//Phoebe Zhou
$staffandappraiser[22470] = 49731;
//Quoc Nguyen
$staffandappraiser[24198] = 52592;
//Sarah Cho
$staffandappraiser[24857] = 51259;
//Trami Nguyen
$staffandappraiser[23765] = 50434;
//Sophie Hung
$staffandappraiser[7722] = 24888; 

foreach($staffandappraiser as $kk => $vv){
    $userstaffids[] = $kk;
    $userappraiids[] = $vv;
    $usedsandaids[] = $vv;
}
if(file_exists("Y:\\live-site\\")){
   $log_file = 'Y:\\live-site\\logsjoomla\\assignlog.txt';
   
}else{
   $log_file = $app->getCfg('log_path').'/assignlog.txt';
}

$datalog = file_get_contents($log_file);
if($datalog){
    $datalog = json_decode($datalog,true);
}else{
    $datalog = array();
}

if(file_exists("Y:\\live-site\\")){
    $log_file1 = 'Y:\\live-site\\logsjoomla\\acceptlog.txt';   
}
else{
    $log_file1 = $app->getCfg('log_path').'/acceptlog.txt';
}
$acceptlog = file_get_contents($log_file1);
if($acceptlog){
    $acceptlog = json_decode($acceptlog,true);
}else{
    $acceptlog = array();
}
$acceptlogbydate = array();


/*foreach($acceptlog as $ordernumber => $log){
    $shortdate = substr($ordernumber,0,8);
    $acceptlogbydate[$shortdate]++;
}*/
$option = array(); 
$option['driver']   = 'mysqli';       
$option['host']     = '192.168.1.39';
$option['user']     = 'root';
$option['password'] = 'Green@123!';
//$option['database'] = 'db677995585'; //live
$option['database'] = 'dbs541050'; //exlive
$option['prefix']   = 'plat_';
$db2 = JDatabaseDriver::getInstance( $option );
function invenDescSort($item1,$item2)
{
    if ($item1['price'] == $item2['price']) return 0;
    return ($item1['price'] < $item2['price']) ? 1 : -1;
}
function get_price_of_property($item){
    $re = '';
    if($item){
        if($item->id == 95539){
            //echo '<pre>'; print_r($item);
        }
        if($item->zillow){ 
            $re = '$'. number_format($item->zillow);
        }
        elseif(stripos($item->history,'>1')!== false || stripos($item->history,'> 1')!== false){ 
            $re = '>1 mil';
        }
        elseif(stripos($item->history,'Zestimate®: ')){ 
            $Zestimate = explode('Zestimate®: ',$item->history); 
            if(count($Zestimate) > 1){
                $Zestimate =  explode(', ',$Zestimate[1]);
                $Zestimate =  explode(' ',$Zestimate[0]);
                $Zestimate =  explode(PHP_EOL,$Zestimate[0]);            
                if(stripos($Zestimate[0],'mil') === false){
                    $Zestimate =  explode(' ',$Zestimate[0]);
                }
                if($item->id == 95539){
                    //echo '<pre>'; print_r($Zestimate);die();
                }
                if($Zestimate[0] != ''){
                    $re = $Zestimate[0];
                }    
            }   
        }elseif($item->purchase_price){
            $re = '$'. number_format($item->purchase_price);
        }
    }
    if($item->id == 95539){
        //echo '<pre>re='; print_r($re);die();
    }
    $re = str_replace('Same','',$re);
    return $re;
}
function get_log_change($alljobcomments, $item){    
    $rownotes = array();
    foreach($alljobcomments as $jobcomment){
        if($jobcomment->task_id == $item->id){
            $strnote = 'Date: '.(date('Y-m-d',strtotime($jobcomment->date_created)-7*3600));
            $strnote .='&#10;';
            $strnote .= $jobcomment->comment;
            $rownotes[] = $strnote;
            break;
            if($rownotes > 5){ break; }
        }
    } 
    $res = '';      
    if(count($rownotes) > 0){
        $strnotes = implode('&#10;',$rownotes);
        $res = "<span class='sajkdljas' style='color: blue;display: block;border: 0px solid red;width: 35px;text-align: center;' title='".str_replace("'",'',$strnotes)."'>".count($rownotes)."</span>";
    }                 
    return $res;
}
 $states = array(
    'AL'=>'Alabama',
    'AK'=>'Alaska',
    'AZ'=>'Arizona',
    'AR'=>'Arkansas',
    'CA'=>'California',
    'CO'=>'Colorado',
    'CT'=>'Connecticut',
    'DE'=>'Delaware',
    'DC'=>'District of Columbia',
    'FL'=>'Florida',
    'GA'=>'Georgia',
    'HI'=>'Hawaii',
    'ID'=>'Idaho',
    'IL'=>'Illinois',
    'IN'=>'Indiana',
    'IA'=>'Iowa',
    'KS'=>'Kansas',
    'KY'=>'Kentucky',
    'LA'=>'Louisiana',
    'ME'=>'Maine',
    'MD'=>'Maryland',
    'MA'=>'Massachusetts',
    'MI'=>'Michigan',
    'MN'=>'Minnesota',
    'MS'=>'Mississippi',
    'MO'=>'Missouri',
    'MT'=>'Montana',
    'NE'=>'Nebraska',
    'NV'=>'Nevada',
    'NH'=>'New Hampshire',
    'NJ'=>'New Jersey',
    'NM'=>'New Mexico',
    'NY'=>'New York',
    'NC'=>'North Carolina',
    'ND'=>'North Dakota',
    'OH'=>'Ohio',
    'OK'=>'Oklahoma',
    'OR'=>'Oregon',
    'PA'=>'Pennsylvania',
    'RI'=>'Rhode Island',
    'SC'=>'South Carolina',
    'SD'=>'South Dakota',
    'TN'=>'Tennessee',
    'TX'=>'Texas',
    'UT'=>'Utah',
    'VT'=>'Vermont',
    'VA'=>'Virginia',
    'WA'=>'Washington',
    'WV'=>'West Virginia',
    'WI'=>'Wisconsin',
    'WY'=>'Wyoming',
);
$arrstates = $states;
$states = array_flip($states);
?>
<div class="divreport">
<link href="https://mottie.github.io/tablesorter/docs/css/jq.css" rel="stylesheet">
  <link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<!--<script src="https://code.jquery.com/jquery-3.6.0.js"></script>-->
  <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/css/theme.default.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/jquery.tablesorter.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/jquery.tablesorter.widgets.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/extras/jquery.tablesorter.pager.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script>
<style>   
    .autohide {
        display: none!important;
    }
    .select2-container {
        min-width: 250px;
        max-width: 250px;
    }
    .select2-results__option {
        padding-right: 20px;
        vertical-align: middle;
    }
    .select2-results__option:before {
        content: "";
        display: inline-block;
        position: relative;
        height: 20px;
        width: 20px;
        border: 2px solid #e9e9e9;
        border-radius: 4px;
        background-color: #fff;
        margin-right: 20px;
        vertical-align: middle;
    }
    .select2-results__option[aria-selected=true]:before {
        font-family:fontAwesome;
        content: "\f00c";
        color: #fff;
        background-color: #f77750;
        border: 0;
        display: inline-block;
        padding-left: 3px;
    }
    .select2-container--default .select2-results__option[aria-selected=true] {
        background-color: #fff;
    }
    .select2-container--default .select2-results__option--highlighted[aria-selected] {
        background-color: #eaeaeb;
        color: #272727;
    }
    .select2-container--default .select2-selection--multiple {
        margin-bottom: 10px;
    }
    .select2-container--default.select2-container--open.select2-container--below .select2-selection--multiple {
        border-radius: 4px;
    }
    .select2-container--default.select2-container--focus .select2-selection--multiple {
        border-color: #f77750;
        border-width: 2px;
    }
    .select2-container--default .select2-selection--multiple {
        border-width: 2px;
    }
    .select2-container--open .select2-dropdown--below {
        
        border-radius: 6px;
        box-shadow: 0 0 10px rgba(0,0,0,0.5);

    }
    .select2-selection .select2-selection--multiple:after {
        content: 'hhghgh';
    }
</style>
<script>
$(function(){
 $('table').tablesorter({
    theme: 'blackice',
    widthFixed: false,
    showProcessing: false,
    headerTemplate: '{content}',
    onRenderTemplate: null, 
    onRenderHeader: function (index) {
        $(this).find('div.tablesorter-header-inner').addClass('roundedCorners');
    },

    cancelSelection: true,
    dateFormat: "mmddyyyy",
    sortMultiSortKey: "shiftKey",
    sortResetKey: 'ctrlKey',
    usNumberFormat: true,
    delayInit: false,
    serverSideSorting: false,
    headers: {
        0: {
            sorter: "text",sortInitialOrder: 'desc'
        },
        2: {
            sorter: "text"
        },
        3: {
            sorter: "digit"
        }
    },
    
    ignoreCase: true,
    sortForce: null,
    sortList: [
        [0, 1],
        [1, 0],
        [2, 0]
    ],

    sortAppend: null,
    sortInitialOrder: "asc",
    sortLocaleCompare: false,
    sortReset: false,
    sortRestart: false,
    emptyTo: "bottom",
    stringTo: "max",
    
    textExtraction: {
        0: function (node) {
            return $(node).text();
        },
        1: function (node) {
            return $(node).text();
        }
    },

    textSorter: null,
    initWidgets: true,
    widgets: ['zebra', 'columns', "filter" ],
    widgetOptions: {
        
        zebra: [
            "ui-widget-content even",
            "ui-state-default odd"],
        uitheme: 'jui',
        columns: [
            "primary",
            "secondary",
            "tertiary"],
        columns_tfoot: true,
        columns_thead: true,
        filter_childRows: false,
        filter_columnFilters: true,
        filter_cssFilter: "tablesorter-filter",
        filter_functions: null,
        filter_hideFilters: false,
        filter_ignoreCase: true,
        filter_reset: null,
        filter_searchDelay: 300,
        filter_serversideFiltering: false,
        filter_startsWith: false,
        filter_useParsedData: false,
        resizable: true,
        saveSort: true,
        stickyHeaders: "tablesorter-stickyHeader"
    },

   
    initialized: function (table) {},

    // *** CSS CLASS NAMES ***
    tableClass: 'tablesorter',
    cssAsc: "tablesorter-headerSortUp",
    cssDesc: "tablesorter-headerSortDown",
    cssHeader: "tablesorter-header",
    cssHeaderRow: "tablesorter-headerRow",
    cssIcon: "tablesorter-icon",
    cssChildRow: "tablesorter-childRow",
    cssInfoBlock: "tablesorter-infoOnly",
    cssProcessing: "tablesorter-processing",
    selectorHeaders: '> thead th, > thead td',
    selectorSort: "th, td",
    selectorRemove: "tr.remove-me",
    debug: false

}).tablesorterPager({
    container: $(".pager"),
    ajaxUrl: null,
    ajaxProcessing: function(ajax) {
        if (ajax && ajax.hasOwnProperty('data')) {
            // return [ "data", "total_rows" ]; 
            return [ajax.data, ajax.total_rows];
        }
    },
    output: '{startRow} to {endRow} ({totalRows})',
    updateArrows: true,
    page: 0,
    size: 100,
    fixedHeight: true,
    removeRows: false,
    cssNext: '.next',
    cssPrev: '.prev',
    cssFirst: '.first',
    cssLast: '.last',
    cssGoto: '.gotoPage',
    cssPageDisplay: '.pagedisplay',
    cssPageSize: '.pagesize',
    cssDisabled: 'disabled'
});

$.extend($.tablesorter.themes.jui, {
    table: 'ui-widget ui-widget-content ui-corner-all', // table classes
    header: 'ui-widget-header ui-corner-all ui-state-default', // header classes
    icons: 'ui-icon', // icon class added to the <i> in the header
    sortNone: 'ui-icon-carat-2-n-s',
    sortAsc: 'ui-icon-carat-1-n',
    sortDesc: 'ui-icon-carat-1-s',
    active: 'ui-state-active', // applied when column is sorted
    hover: 'ui-state-hover', // hover class
    filterRow: '',
    even: 'ui-widget-content', // even row zebra striping
    odd: 'ui-state-default' // odd row zebra striping
});
 $( '.sadasdasd' ).tooltip();
});
</script>
<style>.tablesorter-default input.tablesorter-filter, .tablesorter-default select.tablesorter-filter { min-width: 99.5%;}body.tablesorter-disableSelection { -ms-user-select: none; -moz-user-select: -moz-none;-khtml-user-select: none; -webkit-user-select: none; user-select: none; }.tablesorter-resizable-container { position: relative; height: 1px; }.tablesorter-resizable-handle { position: absolute; display: inline-block; width: 8px;top: 1px; cursor: ew-resize; z-index: 3; user-select: none; -moz-user-select: none; }
    .asdhjbasjk {
        
        display:none;
    }
    .case_processed td{
        background-color: #ffe0e0!important;
    }    
     .case_processed2 td{
        background-color: #fffbe0!important;
    }    
</style>   
<style>.pager{ width:100% !important;}</style>
<?php if(1 == 0){ ?>
<div class="pager" style="float: left;" > 
        <img src="https://mottie.github.io/tablesorter/addons/pager/icons/first.png" class="first"/> 
        <img src="https://mottie.github.io/tablesorter/addons/pager/icons/prev.png" class="prev"/> 
        <span class="pagedisplay"></span> <!-- this can be any element, including an input --> 
        <img src="https://mottie.github.io/tablesorter/addons/pager/icons/next.png" class="next"/> 
        <img src="https://mottie.github.io/tablesorter/addons/pager/icons/last.png" class="last"/> 
        <select class="pagesize" title="Select page size"> 
            <option selected="selected" value="20">20</option> 
            <option value="30">30</option> 
            <option value="50">50</option> 
            <option value="all">All</option> 
        </select>
        <select class="gotoPage" title="Select page number"></select>
</div>
<hr>
<?php } ?>
<style>
tr.trdate{background-color:#449d44;} tr.trdate td, tr.trdate td a{color:#fff;}
.table tr td.tdfirst{background-color:#5cb85c;color:#fff;}
.table tr:not(.trdate) td:nth-child(2n+3){background-color:#eee;}
.table-responsive{width: 100%;}
.table-responsive .table{
    table-layout: fixed;}
.table-responsive .table tr td.tdfirst {
    width: 145px;
}
</style>
<!--table-bordered  table-borderless-->

<!-- Owl Stylesheets -->
<link rel="stylesheet" href="https://owlcarousel2.github.io/OwlCarousel2/assets/owlcarousel/assets/owl.carousel.min.css"/>
<link rel="stylesheet" href="https://owlcarousel2.github.io/OwlCarousel2/assets/owlcarousel/assets/owl.theme.default.min.css"/>
<script src="https://owlcarousel2.github.io/OwlCarousel2/assets/owlcarousel/owl.carousel.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
-->
<script>
$(document).ready(function() {
    jQuery("#lendername").select2();
    $('.select2[multiple]').select2({
        closeOnSelect : false,
        placeholder : "Choose Multiple County",
        allowHtml: true,
        allowClear: true,
        tags: true
    });
    if($('.owl-carousel').length > 0){
        var owl = $('.owl-carousel');
        owl.owlCarousel({
        margin: 10,
        nav: true,
        dots: false,
        loop: false,
        responsive: {
            0: {
            items: 3
            },
            600: {
            items: 5
            },
            1000: {
            items: 12
            }
        }
        });
    }
});
</script>
<!--<hr>-->
<style>
.owl-carousel .owl-item{    
    border-width: 1px;
    border-color: rgb(219, 219, 219);
    border-style: solid;
    padding: 0px;
    background-color: rgb(219, 219, 219);
}
.owl-carousel .owl-item .boxcontent{ 
    width:100%; 
    height:60px;
    overflow-x:hidden; 
    overflow-y:auto;
    box-sizing: border-box;
    padding:10px;    
    font-size: 11px; 
    color: rgb(0, 0, 0);
    font-family: Arial, sans-serif;
    word-wrap: break-word;
    text-align:center;
}
.owl-carousel .owl-item .boxcontent .small{
    font-size: 9px; }
.owl-carousel .owl-item .boxcontent .big{
    font-size: 20px; display:block; text-align:center; font-weight: bold;
    line-height: normal;}
.owl-theme .owl-nav [class*=owl-] {
    position: absolute;
    top: -15%;
    z-index: 9999;}
    
.owl-theme .owl-nav [class*=owl-] span{font-size:60px !important;}
.owl-theme .owl-nav .owl-prev {left:-30px;}
.owl-theme .owl-nav .owl-next {right:-30px;}
.owl-theme .owl-nav [class*=owl-]:hover, .owl-theme .owl-nav [class*=owl-]{
    background: #fff;
    color: #000;}
.isred{
    color: red!important;
}
.isblue{
    color: blue!important;
}
</style>
<div style="position: relative; padding: 0px 30px;">
    <div class="owl-carousel owl-theme">
        <?php 
        $rocase_processed = array();
        foreach($rocase_processed as $key => $ro){ ?>
            <div class="item">
                <div class="boxcontent">
                <strong><?php echo $key; ?></strong><br/><span class="big"><?php echo $ro; ?></span>
                </div>
            </div>
            <?php
        } 
        ?>
    </div>
</div>
<?php    


$currentyear = date('Y');
if(isset($_POST['btnsubmit'])){
    $fiterstate = isset($_POST['debug']) ? $_POST['debug'] : '';
    $yearnumber = isset($_POST['yearnumber']) ? $_POST['yearnumber'] : $currentyear;
    $lendername = isset($_POST['lendername']) ? $_POST['lendername'] : '';
    $acityname = isset($_POST['cityname']) ? $_POST['cityname'] : array();
    $bidvalue = isset($_POST['bidvalue']) ? $_POST['bidvalue'] : '';
}else{
    $fiterstate = isset($_GET['debug']) ? $_GET['debug'] : '';
    $yearnumber = isset($_GET['yearnumber']) ? $_GET['yearnumber'] : $currentyear;
    $lendername = isset($_GET['lendername']) ? $_GET['lendername'] : '';
    $acityname = isset($_GET['cityname']) ? $_GET['cityname'] : array();
    $bidvalue = isset($_GET['bidvalue']) ? $_GET['bidvalue'] : '';
}
$subtime = 2*86400;


if($fiterstate != ''){
    if(!in_array($fiterstate,array('0','1'))){ 
        $sql = "SELECT * FROM `#__jobs_task_comment` where  `comment` like '%changed from%' and YEAR(`date_created`) = {$yearnumber}";
        //echo '<br/>sql='.$sql;
        $db->setquery($sql);
        $alljobcomments = $db->loadobjectlist();
        //echo '<pre>'; print_r($alljobcomments);
        //echo '<pre>'; print_r($_POST); 
        //echo '<pre>'; print_r($arrstates);
        $fullstate = trim($arrstates[strtoupper($fiterstate)]);
        //echo '<br/>fullstate='.$fullstate;
        $sql = "SELECT id,company_name,order_number,property_address,appraiser_id,property_state,property_county,ordered_date FROM `#__jobs_task` where  `ordered_date` > '".date('Y-m-d',time()-$subtime)."' order by id desc";
        $db->setquery($sql);
        $items = $db->loadobjectlist();
        $itemsa = $appspec = $appspec2 = array();
        $groupbylenders = array();
        $arrcitys = array();
        foreach ($items as $item){
            $itemsa[$item->id] = $item;
            if(stripos($item->ordered_date,$yearnumber) !== false && trim(strtolower($item->property_state)) == trim(strtolower($fullstate)) && $item->appraiser_id > 0){
                if($item->company_name != ''){
                    if(!in_array($item->company_name,$groupbylenders)){
                        $groupbylenders[] = $item->company_name;
                    }
                }
            }
            $cityn = trim(str_replace('County','',$item->property_county));
            if($cityn != ''){
                if(!in_array($cityn,$arrcitys)){
                    $arrcitys[] = $cityn;
                }
            }
        }   
        /*$sql = "select c.company_name from (select distinct company_name from plat_jobs_task where `status` = 'complete' and YEAR(ordered_date) >= 2023 and company_name != '' group by company_name) c order by c.company_name asc";
        $db->setquery($sql);
        $groupbylenders = $db->loadresult();*/ 
        if(count($groupbylenders) > 0){
            sort($groupbylenders); 
        } 
        //echo '<pre>'; print_r($groupbylenders);die();
        if(count($arrcitys) > 0){
            sort($arrcitys); 
        } 
        $sql = "SELECT * FROM `#__jobs_task_comment` where  `comment` like '%flt_county_app:%' and DATE(DATE_SUB(`date_created`, INTERVAL 7 HOUR))  > '".date('Y-m-d H:i:s',time()-$subtime)."' group by `task_id` ";
        $db->setquery($sql);
        $alledit = $db->loadobjectlist();
        foreach ($alledit as $k => $ro) {
            $item  = $itemsa[$ro->task_id];
            $quick  = explode('Available: ',$ro->comment);
            $quick  = explode('/',$quick[1]);
            $quick = $quick[0];  
            $property_address = $item->property_address;
            $addres_a = explode(',',$property_address);
            $zipcode = end($addres_a);
            $zipcode = explode(' ',$zipcode);
            $zipcode = end($zipcode);  
            if($quick == 1){
                $uname = jfactory::getUser($item->appraiser_id)->name;
                $appspec[$uname.'-'.$item->property_state.'-'.trim(str_replace('County','',$item->property_county))] += 1;                
                $appspec2[$item->property_state.'-'.trim(str_replace('County','',$item->property_county)).'-'.$uname] += 1;
            }
        } 
        $sql = "select * from plat_jobs_task where property_state = '{$fullstate}' and `appraiser_id` > 0";    
        //$sql .=" and `ordered_date` > '".date('Y-m-d',time()-$subtime)."'";  
        if($yearnumber != ''){
            $sql .= " and ordered_date like '%".$yearnumber."-%'";
        }         
        if($lendername != ''){
            $sql .= " and company_name IN ('".implode("','",$lendername)."') ";
        }       
        if(count($acityname) > 0){
            $wherecity = '';
            foreach($acityname as $cityname){
                if($cityname != ''){
                    if($wherecity != ''){
                        $wherecity .= ' or ';
                    }
                    $wherecity .= "property_county like '$cityname%'";
                }
            }
            if($wherecity != ''){
                $sql .= " and (".$wherecity.")";
            }
        }
        $sql .= " order by id desc";
        //print_r($lendername);
        //echo $sql;die;
        $db->setquery($sql);
        //echo '<br/>sql='.$sql;
        $orders = $db->loadobjectlist(); 
        $arrids = array();
        foreach($orders as $r){
            $arrids[] = $r->id;
        }
        $arrbids = array();
        $arrcheckedits = array();
        $taskcounters = array();
        $appraiserfees = array();
        $jobusers = array();
        $appraiserorders = array();
        $arrtotals = array();
        $checkinvi = array();
        $allreports = array();

        if(count($arrids) > 0){
            $sql = "SELECT id,date_created,task_id FROM `#__jobs_task_comment`"
            . " WHERE ( `comment` LIKE 'Approved counter of %' OR `comment` LIKE 'accepted') and `task_id` in (".implode(",",$arrids).") ORDER BY `id` DESC";
            $db->setquery($sql);
            $checkedit2 = $db->loadobjectlist();
            foreach($checkedit2 as $obj){
                if(!in_array($obj->task_id,array_keys($arrcheckedits))){
                    $arrcheckedits[$obj->task_id] = $obj->date_created;
                }
            }
            $sql =  "SELECT task_id, date_created FROM `#__jobs_task_counter` where `task_id` in (".implode(",",$arrids).")";
            $db->setquery($sql);  
            $taskcounters = $db->loadobjectlist();  
            
            $sql =  "SELECT appraiser_fee, user_id , task_id, counter_due_date FROM `#__jobs_task_counter`  where `appraiser_fee` > 1 and  `task_id` in (".implode(",",$arrids).") ORDER BY `appraiser_fee` ASC";
            $db->setquery($sql);  
            $appraiserfees = $db->loadobjectlist();

            $arruserids = array();
            if(count($appraiserfees) > 0){
                foreach($appraiserfees as $appraiserfee){
                    if(!in_array($appraiserfee->user_id,$arruserids)){
                        $arruserids[] = $appraiserfee->user_id;
                    }
                }
            }
            foreach($orders as $item){
                if(!in_array($item->appraiser_id,$arruserids)){
                    $arruserids[] = $item->appraiser_id;
                }
            }
            //echo '<pre>'; print_r($arruserids);
            if(count($arruserids) > 0){
                $sql = "select * from #__jobs_task where appraiser_id in (".implode(",",$arruserids).") order by `id` DESC";
                $db->setquery($sql); 
                $appraiserorders = $db->loadobjectlist(); 
            }
            //echo 'count='.count($appraiserorders); die();

            $sql = "SELECT * FROM `#__jobs_task_comment` where  `comment` like '%flt_county_app:%' and `task_id` in (".implode(",",$arrids).") order by id desc";
            $db->setquery($sql);
            $checkinvi = $db->loadobjectlist();
            //echo '<pre>'; print_r($checkinvi[0]);
            if(count($appraiserfees) > 0){
                foreach($appraiserfees as $appraiserfee){
                    if($appraiserfee->task_id > 0){
                        if(!in_array($appraiserfee->task_id,$arrids)){
                            $arrids[] = $appraiserfee->task_id;
                        }
                    }
                }
            }
            if(count($appraiserorders) > 0){
                foreach($appraiserorders as $appraiserfee){
                    if($appraiserfee->id > 0){
                        if(!in_array($appraiserfee->id,$arrids)){
                            $arrids[] = $appraiserfee->id;
                        }
                    }
                }
            }
            //echo '<pre>'; print_r($arrids);
            $sql = "select id,task_id,file_title,date_created from #__jobs_task_file where `task_id` in (".implode(",",$arrids).") and `file_title` = 'pdf_report' order by `id` ASC";
            $db->setquery($sql);
            $allreports = $db->loadobjectlist();

            if(count($arruserids) > 0){
                $sql =  "SELECT * FROM `#__jobs_users` where `user_id` in (".implode(",",$arruserids).")";
                $db->setquery($sql);  
                $dbjobusers = $db->loadobjectlist();
                foreach($dbjobusers as $u){
                    $jobusers[$u->user_id] = $u;
                }
            } 
        }
        //echo '<br/>count='.count($orders);
        foreach($orders as $pp => $item){
            $isuset = 0;
            if(isset($arrcheckedits[$item->id])){
                $date_created = $arrcheckedits[$item->id];
                $icountbids = 0;
                foreach($taskcounters as $taskcounter){
                    if($taskcounter->task_id == $item->id && $taskcounter->date_created < $date_created){
                        $icountbids++;
                    }
                }
                if($bidvalue != ''){
                    if($bidvalue == '0or1'){
                        if($icountbids > 1){
                            $isuset = 1;
                        }
                    }else{
                        if($icountbids <= 1){
                            $isuset = 1;
                        }
                    }
                }
            }
            $arrbids[$item->id] = $icountbids;
            if($isuset == 1){
                unset($orders[$pp]);
            }
        }
        //echo '<br/>count1='.count($orders);
        //echo '<pre>'; print_r($orders[0]);die();
        //position: absolute;top: 10px;left:10px;background: #ffffff;height:155px;
        $arruserappraisers = array();
        foreach($orders as $item){
            if($item->appraiser_id > 0){
                if(!in_array($item->appraiser_id,array_keys($arruserappraisers))){
                    $arruserappraisers[$item->appraiser_id] = jfactory::getUser($item->appraiser_id)->name;
                }
            }
            $arrtotals[$item->appraiser_id]['uid'] = $item->appraiser_id;
            $arrtotals[$item->appraiser_id]['price']++; 
            $county = isset($arrtotals[$item->appraiser_id]['county']) ? $arrtotals[$item->appraiser_id]['county'] : array();
            $lender = isset($arrtotals[$item->appraiser_id]['lender']) ? $arrtotals[$item->appraiser_id]['lender'] : array();
            $property_county = trim(str_replace('County','',$item->property_county));
            if(!in_array($property_county,$county)){
                $county[] = $property_county;
            }
            $company_name = $item->company_name;
            $isalender = 1;
            if($company_name != ''){
                if(stripos($company_name,'html') !== false){
                    $isalender = 0;
                }
            }
            if($isalender == 1){
                if(!in_array($company_name,$lender)){
                    $lender[] = $company_name;
                }
            }
            sort($county);
            sort($lender);
            $arrtotals[$item->appraiser_id]['county'] = $county; 
            $arrtotals[$item->appraiser_id]['lender'] = $lender; 
            $arrtotals[$item->appraiser_id]['ordernumber'][] = $item->order_number; 
        }
        //echo '<pre>'; print_r($arrtotals);
        if(count($arrtotals) > 0){
            usort($arrtotals,'invenDescSort');
        }
        //echo '<pre>'; print_r($arrtotals[0]);
        ?>
        <div style="width: 100%; margin-top: 10px;">
         <div style="display:inline-block; float:left;">
             <form method="post" id="dsadsad" style="margin-bottom: 15px;">
                <table>
                     <tr>
                        <td>
                        <label style="width:70px;text-align: right;">Year: </label>
                        <select name="yearnumber" style="height:30px;width:150px;">
                            <?php 
                            $arryear =  array();
                            for($y = $currentyear - 5; $y <= $currentyear; $y++){
                                $arryear[] = $y;
                            }
                            foreach($arryear as $year){
                                $selecte = '';
                                if($year == $yearnumber){
                                    $selecte = 'selected="selected"';
                                }
                                ?>
                                <option <?php echo $selecte ?> value="<?php echo $year ?>"><?php echo $year ?></option>
                                <?php
                            }
                            ?>
                        </select>
                        </td>
                        <td>
                        <label style="width:70px;text-align: right;">State: </label>
                        <select name="debug" style="height:30px;width:200px;">
                            <!--<option value="">Select State</option>--> 
                            <?php 
                            foreach($arrstates as $keystate => $statename){
                                $selecte = '';
                                if(strtolower($keystate) == strtolower($fiterstate)){
                                    $selecte = 'selected="selected"';
                                }
                                ?>
                                <option <?php echo $selecte ?> value="<?php echo $keystate ?>"><?php echo $statename ?></option>
                                <?php
                            }
                            ?>
                        </select>
                        </td>
                        <td>
                        <label style="width:70px;text-align: right;">County: </label>            
                        <select name="cityname[]" style="height:30px;width:250px;" multiple="multiple" class="select2 selectcounty">
                        <?php 
                        foreach($arrcitys as $cityn){
                            $selected = '';
                            foreach($acityname as $cityname){
                                if($cityname == $cityn){ 
                                    $selected = 'selected="true"'; 
                                    break;
                                }
                            }
                            ?>
                            <option <?php echo $selected; ?> value="<?php echo $cityn; ?>"><?php echo $cityn; ?></option>
                            <?php
                        }
                        ?>
                        </select> 
                        </td>
                        <td>
                        <label style="width:70px;text-align: right;">Lender: </label>            
                        <select name="lendername[]" id="lendername" multiple style="height:30px;width:250px;">
                        <option value="">---All---</option>
                        <?php 
                        foreach($groupbylenders as $company_name){
                            $selected = '';
                             if(in_array($company_name, (array)$_POST['lendername'] )){ $selected = 'selected="true"';  } 
                            ///if($lendername == $company_name){ $selected = 'selected="true"'; }
                            ?>
                            <option <?php echo $selected; ?> value="<?php echo $company_name; ?>"><?php echo $company_name; ?></option>
                            <?php
                        }
                        ?>
                        </select>
                        </td>
                        <td>
                        <label style="width:70px;text-align: right;">Bids: </label>            
                        <select name="bidvalue" style="height:30px;width:100px;">
                        <option value="">---All---</option>                     
                        <option value="0or1" <?php if($bidvalue == '0or1'){ echo 'selected="true"'; } ?>>0 or 1</option>                    
                        <option value="more1" <?php if($bidvalue == 'more1'){ echo 'selected="true"'; } ?>>>1</option>
                        </select> 
                        </td>
                        <td>
                        <label style="width:90px;"></label>   
                        <button type="submit" style="padding:5px 20px;background-color:#ccc;border: 1px solid #aaa; box-shadow: none;height: 30px;" name="btnsubmit">Submit</button>
                        </td>
                        <td style="padding-left: 20px;" >
                            <input type="checkbox" onclick="if(jQuery(this).is(':checked')){ jQuery('.isstaff').addClass('autohide'); }else{ jQuery('.isstaff').removeClass('autohide'); }" /> auto hide staff invite <br>
                            <input type="checkbox" onclick="if(jQuery(this).is(':checked')){ jQuery('tr.ui-state-default,tr.ui-widget-content').addClass('autohide'); jQuery('.lowestbidnotpick').each(function(){ jQuery(this).parents('tr').eq(0).removeClass('autohide'); }); }else{ jQuery('tr.ui-state-default,tr.ui-widget-content').removeClass('autohide');  }" /> lowest bid only
                            
                        </td>
                     </tr>
                </table>
             </form>
             <?php
            $top = 1;
            $perapp = 0;
            $perorder = 0;
            $ordertotals = count($orders); 
            ?>
            <div style="display:block;margin-top:10px;margin-left:10px;">
                <strong>Order Totals: </strong><?php echo $ordertotals; ?>
            </div>
             <div style="margin-top:10px;display: flex; margin-top: 10px;vertical-align: top;justify-content: left;align-items: start;">
             <?php 
                 if(count($arrtotals) > 0){
                    ?>
                    <div style="display:inline-block; margin-left:10px;">
                        <table class="table table-striped table-bordered table-hover">
                            <tbody>
                                <tr role="row">
                                    <td><strong>Appraiser</strong></td>
                                    <td><strong>Orders</strong></td>
                                    <td><strong>Zipcode</strong></td>
                                    <td><strong>Lender</strong></td>
                                    <td><strong>%</strong></td>
                                </tr> 
                                <?php 
                                //echo '<pre>';print_r($arruserappraisers);
                                foreach($arrtotals as $pp => $obj){  
                                    if($pp > 4){ break; }   
                                    $uid = $obj['uid'];    
                                    $totals = $obj['price'];              
                                    ?>
                                    <tr role="row">
                                        <td >
                                            <?php 
                                        if(isset($arruserappraisers[$uid])){ 
                                            echo $arruserappraisers[$uid]; 
                                            //echo '<br/>uid='.$uid;
                                        } 
                                        else {  
                                            //echo '<br/>suid='.$uid; 
                                            echo jfactory::getUser($uid)->name; 
                                        }
                                        ?></td>
                                        <td >
                                            <?php 
                                        $perorder = $perorder + $totals;
                                        if($totals > 0){
                                            ?>
                                            <span class='sajkdljas' title='<?php //echo implode("&#10;",$obj['ordernumber']); ?>'>
                                                <?php echo $totals; ?>
                                            </span>
                                            <?php 
                                        }else{
                                            echo $totals;
                                        }
                                        ?></td>
                                        <td >
                                        <?php 
                                        if(count($obj['county']) > 0){
                                            ?>
                                            <span class='sajkdljas' title='<?php echo implode("&#10;",$obj['county']); ?>'>
                                                <?php echo count($obj['county']); ?>
                                            </span>
                                            <?php 
                                        }
                                         ?>
                                         </td>
                                        <td >
                                        <?php 
                                        if(count($obj['lender']) > 0){
                                            ?>
                                            <span class='sajkdljas' title='<?php echo implode("&#10;",$obj['lender']); ?>'>
                                                <?php echo count($obj['lender']); ?>
                                            </span>
                                            <?php
                                        }
                                        ?></td>
                                        <td ><?php 
                                        $per1 = 0;
                                        if($ordertotals > 0){
                                            $per1 = number_format(($totals/$ordertotals)*100,2); 
                                            $perapp = $perapp + $per1;
                                    }
                                    else{ $per1 = 0; } echo $per1; ?>%</td>
                                    </tr> 
                                    <?php
                                    $top++;
                                }
                                ?> 
                            </tbody>
                        </table>
                    </div>
                    <?php
                } ?>
                 <?php 
                 if(count($arrtotals) > 5){
                    ?>
                    <div style="display:inline-block; margin-left:20px;">
                       <table class="table table-striped table-bordered table-hover">
                           <tbody>
                               <tr role="row">
                                    <td><strong>Appraiser</strong></td>
                                    <td><strong>Orders</strong></td>
                                    <td><strong>Zipcode</strong></td>
                                    <td><strong>Lender</strong></td>
                                    <td><strong>%</strong></td>
                               </tr> 
                               <?php  
                               //echo '<pre>';print_r($arruserappraisers);
                               foreach($arrtotals as  $pp => $obj){  
                                    if($pp > 9){ break; }
                                    if($pp > 4 && $pp <= 9){     
                                        $uid = $obj['uid'];    
                                        $totals = $obj['price'];              
                                        ?>
                                        <tr role="row">
                                            <td >
                                                <?php 
                                            if(isset($arruserappraisers[$uid])){ 
                                                echo $arruserappraisers[$uid]; 
                                                //echo '<br/>uid='.$uid;
                                            } 
                                            else {  
                                                //echo '<br/>suid='.$uid; 
                                                echo jfactory::getUser($uid)->name; 
                                            }
                                            ?></td>
                                            <td ><?php 
                                            $perorder = $perorder + $totals;
                                            if($totals > 0){
                                                ?>
                                                <span class='sajkdljas' title='<?php //echo implode("&#10;",$obj['ordernumber']); ?>'>
                                                    <?php echo $totals; ?>
                                                </span>
                                                <?php 
                                            }else{
                                                echo $totals;
                                            }
                                            ?></td>
                                            <td >
                                        <?php 
                                        if(count($obj['county']) > 0){
                                            ?>
                                            <span class='sajkdljas' title='<?php echo implode("&#10;",$obj['county']); ?>'>
                                                <?php echo count($obj['county']); ?>
                                            </span>
                                            <?php 
                                        }
                                         ?>
                                         </td>
                                        <td >
                                        <?php 
                                        if(count($obj['lender']) > 0){
                                            ?>
                                            <span class='sajkdljas' title='<?php echo implode("&#10;",$obj['lender']); ?>'>
                                                <?php echo count($obj['lender']); ?>
                                            </span>
                                            <?php
                                        }
                                        ?></td>
                                            <td ><?php 
                                            $per1 = 0;
                                            if($ordertotals > 0){
                                                $per1 = number_format(($totals/$ordertotals)*100,2); 
                                                $perapp = $perapp + $per1;
                                        }
                                        else{ $per1 = 0; } echo $per1; ?>%</td>
                                        </tr> 
                                        <?php
                                        $top++;
                                    } 
                               }
                               ?> 
                           </tbody>
                       </table>
                    </div><?php
                 } ?>
                 <?php 
                 if(count($arrtotals) > 10){
                    ?>
                    <div style="display:inline-block; margin-left:20px;">
                       <table class="table table-striped table-bordered table-hover">
                           <tbody>
                               <tr role="row">
                                    <td><strong>Appraiser</strong></td>
                                    <td><strong>Orders</strong></td>
                                    <td><strong>Zipcode</strong></td>
                                    <td><strong>Lender</strong></td>
                                    <td><strong>%</strong></td>
                               </tr> 
                               <?php  
                               //echo '<pre>';print_r($arruserappraisers);
                               foreach($arrtotals as  $pp => $obj){    
                                    if($pp > 14){ break; }   
                                    if($pp > 9 && $pp <= 14){        
                                        $uid = $obj['uid'];    
                                        $totals = $obj['price'];              
                                        ?>
                                        <tr role="row">
                                            <td >
                                                <?php 
                                            if(isset($arruserappraisers[$uid])){ 
                                                echo $arruserappraisers[$uid]; 
                                                //echo '<br/>uid='.$uid;
                                            } 
                                            else {  
                                                //echo '<br/>suid='.$uid; 
                                                echo jfactory::getUser($uid)->name; 
                                            }
                                            ?></td>
                                            <td ><?php 
                                            $perorder = $perorder + $totals;
                                            if($totals > 0){
                                                ?>
                                                <span class='sajkdljas' title='<?php //echo implode("&#10;",$obj['ordernumber']); ?>'>
                                                    <?php echo $totals; ?>
                                                </span>
                                                <?php 
                                            }else{
                                                echo $totals;
                                            }
                                            ?></td>
                                            <td >
                                        <?php 
                                        if(count($obj['county']) > 0){
                                            ?>
                                            <span class='sajkdljas' title='<?php echo implode("&#10;",$obj['county']); ?>'>
                                                <?php echo count($obj['county']); ?>
                                            </span>
                                            <?php 
                                        }
                                         ?>
                                         </td>
                                        <td >
                                        <?php 
                                        if(count($obj['lender']) > 0){
                                            ?>
                                            <span class='sajkdljas' title='<?php echo implode("&#10;",$obj['lender']); ?>'>
                                                <?php echo count($obj['lender']); ?>
                                            </span>
                                            <?php
                                        }
                                        ?></td>
                                            <td ><?php 
                                            $per1 = 0;
                                            if($ordertotals > 0){
                                                $per1 = number_format(($totals/$ordertotals)*100,2); 
                                                $perapp = $perapp + $per1;
                                        }
                                        else{ $per1 = 0; } echo $per1; ?>%</td>
                                        </tr> 
                                        <?php
                                        $top++; 
                                    }
                               }
                               ?> 
                           </tbody>
                       </table>
                    </div><?php
                 } ?>
                 <?php 
                 if(count($arrtotals) > 15){
                    ?>
                    <div style="display:inline-block; margin-left:20px;">
                       <table class="table table-striped table-bordered table-hover">
                           <tbody>
                               <tr role="row">
                                    <td><strong>Appraiser</strong></td>
                                    <td><strong>Orders</strong></td>
                                    <td><strong>Zipcode</strong></td>
                                    <td><strong>Lender</strong></td>
                                    <td><strong>%</strong></td>
                               </tr> 
                               <?php  
                               //echo '<pre>';print_r($arruserappraisers);
                               foreach($arrtotals as  $pp => $obj){  
                                    if($pp > 19){ break; } 
                                    if($pp > 14 && $pp <= 19){           
                                        $uid = $obj['uid'];    
                                        $totals = $obj['price'];              
                                        ?>
                                        <tr role="row">
                                            <td >
                                                <?php 
                                            if(isset($arruserappraisers[$uid])){ 
                                                echo $arruserappraisers[$uid]; 
                                                //echo '<br/>uid='.$uid;
                                            } 
                                            else {  
                                                //echo '<br/>suid='.$uid; 
                                                echo jfactory::getUser($uid)->name; 
                                            }
                                            ?></td>
                                            <td ><?php 
                                            $perorder = $perorder + $totals;
                                            if($totals > 0){
                                                ?>
                                                <span class='sajkdljas' title='<?php //echo implode("&#10;",$obj['ordernumber']); ?>'>
                                                    <?php echo $totals; ?>
                                                </span>
                                                <?php 
                                            }else{
                                                echo $totals;
                                            }
                                            ?></td>
                                            <td >
                                        <?php 
                                        if(count($obj['county']) > 0){
                                            ?>
                                            <span class='sajkdljas' title='<?php echo implode("&#10;",$obj['county']); ?>'>
                                                <?php echo count($obj['county']); ?>
                                            </span>
                                            <?php 
                                        }
                                         ?>
                                         </td>
                                        <td >
                                        <?php 
                                        if(count($obj['lender']) > 0){
                                            ?>
                                            <span class='sajkdljas' title='<?php echo implode("&#10;",$obj['lender']); ?>'>
                                                <?php echo count($obj['lender']); ?>
                                            </span>
                                            <?php
                                        }
                                        ?></td>
                                            <td ><?php 
                                            $per1 = 0;
                                            if($ordertotals > 0){
                                                $per1 = number_format(($totals/$ordertotals)*100,2); 
                                                $perapp = $perapp + $per1;
                                        }
                                        else{ $per1 = 0; } echo $per1; ?>%</td>
                                        </tr> 
                                        <?php
                                        $top++;   
                                    } 
                               }
                               ?> 
                           </tbody>
                       </table>
                    </div><?php
                 } 
                 //echo '<pre>'; print_r($arrtotals);
                 ?>
            </div> 
            <!--<div style="display:block;margin-top:10px;">
                <table>
                    <tbody>
                        <tr role="row">
                            <td >Other Appraisers</td>
                            <td ><?php echo $ordertotals - $perorder; ?></td>
                            <td ><?php 
                            $perother = 100 - $perapp;
                            echo $perother; ?>%</td>
                        </tr>
                    </tbody>
                </table>
            </div>-->
         </div>
         <div style="clear:both;"></div>
     </div>
        <div style="margin-top: 10px;">
         <table class="tablesorter tablesorter-default" role="grid" style="width:100%; z-index: 10; position: relative;">
        <thead>
        <tr role="row">
            <th style="width:5.5%;">Order</th>
            <th>Appraiser Type</th>
            <th style="width:4%;">Price</th>
            <th >Appraiser</th>
            <th style="width:5%;">Zipcode</th>
            <th >Lender</th>
            <th >Logs</th>
            <th >Lowest Bid               
                
            </th>
            <th style="width:3.5%;">Bids</th>
            <th style="width:5%;">Staff Invite</th>
            <th >Accept/Assign</th>
        </tr>  
        </thead>
        <tbody>
            <?php 
                foreach($orders as $key => $item){                    
                    if(stripos($item->appraisal_type,'1004d') !== false){
                        continue;
                    }
                    $staffinv = '';
                    foreach($checkinvi as $obj){
                                if($obj->task_id == $item->id){
                                    if(strpos($obj->comment,'Available: ') !== false){
                                        $staffinv = explode('Available: ',$obj->comment);
                                        $staffinv  = explode('/',$staffinv[1]);
                                        $staffinv = $staffinv[0];
                                    } 
                                    break;
                                }
                    }
                            
                    if($staffinv > 1){
                        continue;
                    }
                    $icountbids = 0;
                    if(isset($arrbids[$item->id])){
                            $icountbids = $arrbids[$item->id];
                    }
                    if($icountbids > 1){
                        continue;
                    }    
                    unset($orders[$key]);
                    
                    //print_r($item); break;
                     $property_address = $item->property_address;
                    $addres_a = explode(',',$property_address);
                    $classcity = str_replace(' ','-',trim($addres_a[1]));    
                    $city = '-'.trim($addres_a[1]);
                    if($states[$item->property_state] != 'CA'){
                            $city = '';
                        }
                    if(in_array($item->appraiser_id, $userappraiids)){
                         $isstaff = ' isstaff';   
                    }else{
                        $isstaff = '';   
                    }
                    $citylist[] = $classcity;    
                    ?>
                     <tr role="row" class="<?php echo $classcity.$isstaff; ?>"  rid="<?php echo $item->id; ?>">
                        <td ><?php echo $item->order_number;  ?></td>
                        <td ><?php echo $item->appraisal_type;  ?></td>
                        <td ><?php echo get_price_of_property($item); ?></td>
                        <td ><?php if(isset($arruserappraisers[$item->appraiser_id])){ echo $arruserappraisers[$item->appraiser_id]; } else { echo jfactory::getUser($item->appraiser_id)->name; } ?></td>
                        <td><?php echo $states[$item->property_state].'-'.str_replace('County','',$item->property_county).$city; ?></td>
                        <td ><?php echo $item->company_name;  ?></td>
                        <td>
                            <?php   
                                echo get_log_change($alljobcomments, $item);                                
                            ?>    
                        </td>
                        <td >
                        <?php 
                        $appraiserfee = new stdClass(); 
                        $appraiserrating = '';
                        if($item->id == 100709){ 
                            //echo '<pre>';print_r($item);
                        }
                        foreach($appraiserfees as $a){
                            //if($item->id == 95539){ echo '<pre>';print_r($a); die('sss'); } 
                            //break;
                            if($a->task_id == $item->id){
                                $appraiserfee = $a;
                                if($item->id == 100709){ 
                                    //echo '<pre>';print_r($appraiserfee);
                                }
                                if($item->appraiser_id == '' || $item->appraiser_id == 0){    
                                    echo '<span>';      
                                }elseif($a->user_id == $item->appraiser_id || $item->appraiser_fee == $a->appraiser_fee){    
                                    echo '<span style="color:blue;" >';      
                                }else{
                                    $dataprice = array();
                                    foreach($appraiserorders as $appraiserorder){
                                        if($a->user_id == $appraiserorder->appraiser_id){
                                            $dataprice[] = $appraiserorder;
                                        }
                                    }
                                    if($item->id == 100709){ 
                                        //echo '<pre>';print_r($dataprice);
                                    }
                                    $counter_rownotes = array();
                                    $completeorder = 0 ;
                                    $lowvalueorder = 0 ;
                                    $totalorder = 0;        
                                    foreach ($dataprice as $otp){
                                        if( $otp->status == 'complete' ){
                                            if(count((array)$counter_rownotes) < 5){
                                                /*$sql = "select * from #__jobs_task_file where `task_id`  = '".$otp->id."' and `file_title` = 'pdf_report' order by `id` ASC";
                                                $db->setquery($sql);
                                                $firstreport = $db->loadobject();*/
                                                $firstreport = new stdClass();
                                                $hasf = 0;
                                                foreach($allreports as $report){
                                                    if($report->task_id == $otp->id){
                                                        $firstreport = $report;
                                                        $hasf = 1;
                                                        break;
                                                    }
                                                }
                                                if($item->id == 100709){ 
                                                    //echo '<br>id='.$otp->id.'|hasf='.$hasf;
                                                }
                                                if($hasf > 0){
                                                    //echo '<pre>'; print_r($firstreport);
                                                    $reporttime = strtotime((date('Y-m-d',strtotime($firstreport->date_created)-7*3600)));
                                                    if($reporttime < strtotime($otp->due_date)){
                                                        if(stripos($otp->appraisal_type,'RUSH') !== false){
                                                        $counter_rownotes[] = $otp->order_number.' RUSH early';   
                                                        }else{
                                                        $counter_rownotes[] = $otp->order_number.' early';
                                                        }
                                                    }else if($reporttime == strtotime($otp->due_date)){
                                                        if(stripos($otp->appraisal_type,'RUSH') !== false){
                                                        $counter_rownotes[] = $otp->order_number.' RUSH on time';   
                                                        }else{
                                                        $counter_rownotes[] = $otp->order_number.' on time';
                                                        }
                                                    }else{
                                                        if(stripos($otp->appraisal_type,'RUSH') !== false){
                                                        $counter_rownotes[] = $otp->order_number.' RUSH ( '.round(($reporttime-strtotime($otp->due_date))/86400).' days ) late';   
                                                        }else{
                                                        $counter_rownotes[] = $otp->order_number.' ( '.round(($reporttime-strtotime($otp->due_date))/86400).' days ) late';
                                                        }
                                                    }
                                                }
                                            }    
                                            $totalorder++;
                                        }
                                        if($otp->status == 'assigned' || $otp->status == 'inspected' || $otp->status == 'inspection_complete'){
                                            $completeorder++;
                                        }
                                        if($otp->appraised_value > 0 && ( $otp->appraised_value <  $otp->estimated_value ||  $otp->appraised_value <  $otp->purchase_price)){
                                            $lowvalueorder++;
                                        }
                                    }
                                    $counter_rownotes = implode('&#10;',$counter_rownotes);
                                    echo "<span  class='sajkdljas lowestbidnotpick'  style='color:red;' title='".str_replace("'",'',$counter_rownotes)."'>";      
                                }
                                
                                /*$sql =  "SELECT * FROM `#__jobs_users` where `user_id` = '".$a->user_id."'  limit 0,1 ";
                                $db->setquery($sql);  
                                $b = $db->loadobject();*/ 
                                $b = $jobusers[$a->user_id];
                                $uname = '';
                                if(isset($arruserappraisers[$item->appraiser_id])){ 
                                    $uname = $arruserappraisers[$item->appraiser_id]; 
                                } else { 
                                    $uname = jfactory::getUser($item->appraiser_id)->name; 
                                }
                                $uname1 = '';
                                if(isset($arruserappraisers[$a->user_id])){ 
                                    $uname1 = $arruserappraisers[$a->user_id]; 
                                } else { 
                                    $uname1 = jfactory::getUser($a->user_id)->name; 
                                }
                                if(round((strtotime($a->counter_due_date) - strtotime($item->ordered_date)))  <  0){
                                    if($item->appraiser_fee == $a->appraiser_fee){///counter_due_date
                                        $appraiserrating = '['.$b->rank.'*]';
                                        echo '$'.str_replace('.00','',$item->appraiser_fee).' ('.$uname.')'.$appraiserrating; 
                                    }else{
                                        $appraiserrating = '['.$b->rank.'*]';
                                        echo '$'.str_replace('.00','',$a->appraiser_fee).' ('.$uname1.')'.$appraiserrating; 
                                    }
                                }else{
                                    if($item->appraiser_fee == $a->appraiser_fee){///counter_due_date
                                        $appraiserrating = '['.round((strtotime($a->counter_due_date) - strtotime($item->ordered_date))/86400).'D]['.$b->rank.'*]';
                                        echo '$'.str_replace('.00','',$item->appraiser_fee).' ('.$uname.')'.$appraiserrating; 
                                    }else{
                                        $appraiserrating = '['.round((strtotime($a->counter_due_date) - strtotime($item->ordered_date))/86400).'D]['.$b->rank.'*]';
                                        echo '$'.str_replace('.00','',$a->appraiser_fee).' ('.$uname1.')'.$appraiserrating; 
                                    }
                                }
                                echo '</span>';
                                break;
                            }
                        }
                        ?>
                        </td>
                        <td ><?php                       
                        echo $icountbids; 
                        ?></td>
                        <td >
                            <?php                           
                            echo $staffinv; ?>
                        </td>
                        <td > 
                            <span
                            <?php 
                            $a = $appraiserfee;
                            if( $item->appraiser_id == ''  ||  $item->appraiser_id == 0){    
                            
                            }elseif($a->user_id == $item->appraiser_id || $item->appraiser_fee == $a->appraiser_fee ){    
                            
                            }else{
                                $dataprice = array();
                                foreach($appraiserorders as $appraiserorder){
                                    if($item->appraiser_id == $appraiserorder->appraiser_id){
                                        $dataprice[] = $appraiserorder;
                                    }
                                }
                                $counter_rownotes = array();
                                $completeorder = 0 ;
                                $lowvalueorder = 0 ;
                                $totalorder = 0;  
                                foreach ($dataprice as $otp){
                                    if( $otp->status == 'complete' ){
                                        if(count((array)$counter_rownotes) < 5  ){
                                            /*$db->setquery("select * from #__jobs_task_file where `task_id`  = '".$otp->id."' and `file_title` = 'pdf_report' order by `id` ASC  ");
                                            $firstreport = $db->loadobject();*/
                                            $firstreport = new stdClass();   
                                            $hasf = 0;
                                            foreach($allreports as $report){
                                                if($report->task_id == $otp->id){
                                                    $firstreport = $report;
                                                    $hasf = 1;
                                                    break;
                                                }
                                            }
                                            if($item->id == 100709){ 
                                                //echo '<br>id='.$otp->id.'|hasf='.$hasf;
                                            }
                                            if($hasf > 0){
                                                $reporttime = strtotime((date('Y-m-d',strtotime($firstreport->date_created)-7*3600)));
                                                if( $reporttime < strtotime($otp->due_date) ){
                                                    if(stripos($otp->appraisal_type,'RUSH') !== false){
                                                    $counter_rownotes[] = $otp->order_number.' RUSH early';   
                                                    }else{
                                                    $counter_rownotes[] = $otp->order_number.' early';
                                                    }
                                                }else if( $reporttime == strtotime($otp->due_date) ){
                                                    if(stripos($otp->appraisal_type,'RUSH') !== false){
                                                    $counter_rownotes[] = $otp->order_number.' RUSH on time';   
                                                    }else{
                                                    $counter_rownotes[] = $otp->order_number.' on time';
                                                    }
                                                }else{
                                                    if(stripos($otp->appraisal_type,'RUSH') !== false){
                                                    $counter_rownotes[] = $otp->order_number.' RUSH ( '.round(($reporttime-strtotime($otp->due_date))/86400).' days ) late';   
                                                    }else{
                                                    $counter_rownotes[] = $otp->order_number.' ( '.round(($reporttime-strtotime($otp->due_date))/86400).' days ) late';
                                                    }
                                                }
                                            }
                                        }
                                        $totalorder++;
                                    }
                                    if( $otp->status == 'assigned' || $otp->status == 'inspected' || $otp->status == 'inspection_complete' ){
                                            $completeorder++;
                                    }
                                    if( $otp->appraised_value > 0 && ( $otp->appraised_value <  $otp->estimated_value ||  $otp->appraised_value <  $otp->purchase_price   )){
                                            $lowvalueorder++;
                                    }
                                }                
                                $counter_rownotes = implode('&#10;',$counter_rownotes);
                                echo " title='".str_replace("'",'',$counter_rownotes)."' class='sajkdljas'  ";      
                                } 
                                $uname = '';
                                if(isset($arruserappraisers[$item->appraiser_id])){ 
                                    $uname = $arruserappraisers[$item->appraiser_id]; 
                                } else { 
                                    $uname = jfactory::getUser($item->appraiser_id)->name; 
                                }
                                ?>
                                style="<?php if($appspec[$uname.'-'.$item->property_state.'-'.trim(str_replace('County','',$item->property_county))] > 1){ echo 'color:red;';}  ?>">
                                <?php 
                                if($item->appraiser_fee > 1){ echo '$'.str_replace('.00','',$item->appraiser_fee); }
                                if($item->appraiser_id){echo ' ('.$uname.')';} ?>
                                <?php if(in_array($item->appraiser_id, array(31778,49731,52592,51259,24888,50434,748))){ echo '[Staff]';}
                                if($item->appraiser_id){
                            /*$sql =  "SELECT * FROM `#__jobs_users`  where `user_id` = '".$item->appraiser_id."'  limit 0,1 ";
                            $db->setquery($sql);  
                            $b  =   $db->loadobject();*/  
                            $b = $jobusers[$item->appraiser_id];                     
                            echo  '['.round((strtotime($item->due_date) - strtotime($item->ordered_date))/86400).'D]['.$b->rank.'*]';}
                        ?> 
                        </span>
                        </td>
                    </tr>  
                     <?php
                }
            ?>
        </tbody>
        </table>    
        <table class="tablesorter tablesorter-default" role="grid" style="width:100%; z-index: 10; position: relative;">
        <thead>
        <tr role="row">
            <th style="width:5.5%;">Order</th>
            <th>Appraiser Type</th>
            <th style="width:4%;">Price</th>
            <th >Appraiser</th>
            <th style="width:5%;">Zipcode</th>
            <th >Lender</th>
            <th>Logs</th>
            <th >Lowest Bid</th>
            <th style="width:3.5%;">Bids</th>
            <th style="width:5%;">Staff Invite</th>
            <th >Accept/Assign</th>
        </tr>  
        </thead>
        <tbody>
            <?php 
                foreach($orders as $item){
                    $staffinv = '';
                    //print_r($item); break;
                    $property_address = $item->property_address;
                    $addres_a = explode(',',$property_address);
                    $classcity = str_replace(' ','-',trim($addres_a[1]));    
                    $city = '-'.trim($addres_a[1]);
                    
                    
                    if(in_array($item->appraiser_id, $userappraiids)){
                         $isstaff = ' isstaff';   
                    }else{
                        $isstaff = '';   
                    }
                    
                    $citylist[] = $classcity;    
                    
                    ?>
                     <tr class="<?php echo $classcity.$isstaff; ?>" role="row" rid="<?php echo $item->id; ?>">
                        <td ><?php echo $item->order_number;  ?></td>
                        <td ><?php echo $item->appraisal_type;  ?></td>
                        <td ><?php echo get_price_of_property($item); ?></td>
                        <td ><?php if(isset($arruserappraisers[$item->appraiser_id])){ echo $arruserappraisers[$item->appraiser_id]; } else { echo jfactory::getUser($item->appraiser_id)->name; } ?></td>
                        <td><?php 
                          
                        if($states[$item->property_state] != 'CA'){
                            $city = '';
                        }
                        echo $states[$item->property_state].'-'.str_replace('County','',$item->property_county).$city;
                        
                     
                        
                        ?></td>
                        <td ><?php echo $item->company_name;  ?></td>
                        <td><?php echo get_log_change($alljobcomments, $item); ?></td>
                        <td >
                        <?php 
                        $appraiserfee = new stdClass(); 
                        $appraiserrating = '';
                        if($item->id == 100709){ 
                            //echo '<pre>';print_r($item);
                        }
                        foreach($appraiserfees as $a){
                            //if($item->id == 95539){ echo '<pre>';print_r($a); die('sss'); } 
                            //break;
                            if($a->task_id == $item->id){
                                $appraiserfee = $a;
                                if($item->id == 100709){ 
                                    //echo '<pre>';print_r($appraiserfee);
                                }
                                if($item->appraiser_id == '' || $item->appraiser_id == 0){    
                                    echo '<span>';      
                                }elseif($a->user_id == $item->appraiser_id || $item->appraiser_fee == $a->appraiser_fee){    
                                    echo '<span style="color:blue;" >';      
                                }else{
                                    $dataprice = array();
                                    foreach($appraiserorders as $appraiserorder){
                                        if($a->user_id == $appraiserorder->appraiser_id){
                                            $dataprice[] = $appraiserorder;
                                        }
                                    }
                                    if($item->id == 100709){ 
                                        //echo '<pre>';print_r($dataprice);
                                    }
                                    $counter_rownotes = array();
                                    $completeorder = 0 ;
                                    $lowvalueorder = 0 ;
                                    $totalorder = 0;        
                                    foreach ($dataprice as $otp){
                                        if( $otp->status == 'complete' ){
                                            if(count((array)$counter_rownotes) < 5){
                                                /*$sql = "select * from #__jobs_task_file where `task_id`  = '".$otp->id."' and `file_title` = 'pdf_report' order by `id` ASC";
                                                $db->setquery($sql);
                                                $firstreport = $db->loadobject();*/
                                                $firstreport = new stdClass();
                                                $hasf = 0;
                                                foreach($allreports as $report){
                                                    if($report->task_id == $otp->id){
                                                        $firstreport = $report;
                                                        $hasf = 1;
                                                        break;
                                                    }
                                                }
                                                if($item->id == 100709){ 
                                                    //echo '<br>id='.$otp->id.'|hasf='.$hasf;
                                                }
                                                if($hasf > 0){
                                                    //echo '<pre>'; print_r($firstreport);
                                                    $reporttime = strtotime((date('Y-m-d',strtotime($firstreport->date_created)-7*3600)));
                                                    if($reporttime < strtotime($otp->due_date)){
                                                        if(stripos($otp->appraisal_type,'RUSH') !== false){
                                                        $counter_rownotes[] = $otp->order_number.' RUSH early';   
                                                        }else{
                                                        $counter_rownotes[] = $otp->order_number.' early';
                                                        }
                                                    }else if($reporttime == strtotime($otp->due_date)){
                                                        if(stripos($otp->appraisal_type,'RUSH') !== false){
                                                        $counter_rownotes[] = $otp->order_number.' RUSH on time';   
                                                        }else{
                                                        $counter_rownotes[] = $otp->order_number.' on time';
                                                        }
                                                    }else{
                                                        if(stripos($otp->appraisal_type,'RUSH') !== false){
                                                        $counter_rownotes[] = $otp->order_number.' RUSH ( '.round(($reporttime-strtotime($otp->due_date))/86400).' days ) late';   
                                                        }else{
                                                        $counter_rownotes[] = $otp->order_number.' ( '.round(($reporttime-strtotime($otp->due_date))/86400).' days ) late';
                                                        }
                                                    }
                                                }
                                            }    
                                            $totalorder++;
                                        }
                                        if($otp->status == 'assigned' || $otp->status == 'inspected' || $otp->status == 'inspection_complete'){
                                            $completeorder++;
                                        }
                                        if($otp->appraised_value > 0 && ( $otp->appraised_value <  $otp->estimated_value ||  $otp->appraised_value <  $otp->purchase_price)){
                                            $lowvalueorder++;
                                        }
                                    }
                                    $counter_rownotes = implode('&#10;',$counter_rownotes);
                                    echo "<span  class='sajkdljas lowestbidnotpick'  style='color:red;' title='".str_replace("'",'',$counter_rownotes)."'>";      
                                }
                                
                                /*$sql =  "SELECT * FROM `#__jobs_users` where `user_id` = '".$a->user_id."'  limit 0,1 ";
                                $db->setquery($sql);  
                                $b = $db->loadobject();*/ 
                                $b = $jobusers[$a->user_id];
                                $uname = '';
                                if(isset($arruserappraisers[$item->appraiser_id])){ 
                                    $uname = $arruserappraisers[$item->appraiser_id]; 
                                } else { 
                                    $uname = jfactory::getUser($item->appraiser_id)->name; 
                                }
                                $uname1 = '';
                                if(isset($arruserappraisers[$a->user_id])){ 
                                    $uname1 = $arruserappraisers[$a->user_id]; 
                                } else { 
                                    $uname1 = jfactory::getUser($a->user_id)->name; 
                                }
                                if(round((strtotime($a->counter_due_date) - strtotime($item->ordered_date)))  <  0){
                                    if($item->appraiser_fee == $a->appraiser_fee){///counter_due_date
                                        $appraiserrating = '['.$b->rank.'*]';
                                        echo '$'.str_replace('.00','',$item->appraiser_fee).' ('.$uname.')'.$appraiserrating; 
                                    }else{
                                        $appraiserrating = '['.$b->rank.'*]';
                                        echo '$'.str_replace('.00','',$a->appraiser_fee).' ('.$uname1.')'.$appraiserrating; 
                                    }
                                }else{
                                    if($item->appraiser_fee == $a->appraiser_fee){///counter_due_date
                                        $appraiserrating = '['.round((strtotime($a->counter_due_date) - strtotime($item->ordered_date))/86400).'D]['.$b->rank.'*]';
                                        echo '$'.str_replace('.00','',$item->appraiser_fee).' ('.$uname.')'.$appraiserrating; 
                                    }else{
                                        $appraiserrating = '['.round((strtotime($a->counter_due_date) - strtotime($item->ordered_date))/86400).'D]['.$b->rank.'*]';
                                        echo '$'.str_replace('.00','',$a->appraiser_fee).' ('.$uname1.')'.$appraiserrating; 
                                    }
                                }
                                echo '</span>';
                                break;
                            }
                        }
                        ?>
                        </td>
                        <td ><?php
                        $icountbids = 0;
                        if(isset($arrbids[$item->id])){
                            $icountbids = $arrbids[$item->id];
                        }
                        echo $icountbids; 
                        ?></td>
                        <td >
                            <?php 
                            foreach($checkinvi as $obj){
                                if($obj->task_id == $item->id){
                                    if(strpos($obj->comment,'Available: ') !== false){
                                        $staffinv = explode('Available: ',$obj->comment);
                                        $staffinv  = explode('/',$staffinv[1]);
                                        $staffinv = $staffinv[0];
                                    } 
                                    break;
                                }
                            }
                            echo $staffinv; ?>
                        </td>
                        <td > 
                            <span
                            <?php 
                            $a = $appraiserfee;
                            if( $item->appraiser_id == ''  ||  $item->appraiser_id == 0){    
                            
                            }elseif($a->user_id == $item->appraiser_id || $item->appraiser_fee == $a->appraiser_fee ){    
                            
                            }else{
                                $dataprice = array();
                                foreach($appraiserorders as $appraiserorder){
                                    if($item->appraiser_id == $appraiserorder->appraiser_id){
                                        $dataprice[] = $appraiserorder;
                                    }
                                }
                                $counter_rownotes = array();
                                $completeorder = 0 ;
                                $lowvalueorder = 0 ;
                                $totalorder = 0;  
                                foreach ($dataprice as $otp){
                                    if( $otp->status == 'complete' ){
                                        if(count((array)$counter_rownotes) < 5  ){
                                            /*$db->setquery("select * from #__jobs_task_file where `task_id`  = '".$otp->id."' and `file_title` = 'pdf_report' order by `id` ASC  ");
                                            $firstreport = $db->loadobject();*/
                                            $firstreport = new stdClass();   
                                            $hasf = 0;
                                            foreach($allreports as $report){
                                                if($report->task_id == $otp->id){
                                                    $firstreport = $report;
                                                    $hasf = 1;
                                                    break;
                                                }
                                            }
                                            if($item->id == 100709){ 
                                                //echo '<br>id='.$otp->id.'|hasf='.$hasf;
                                            }
                                            if($hasf > 0){
                                                $reporttime = strtotime((date('Y-m-d',strtotime($firstreport->date_created)-7*3600)));
                                                if( $reporttime < strtotime($otp->due_date) ){
                                                    if(stripos($otp->appraisal_type,'RUSH') !== false){
                                                    $counter_rownotes[] = $otp->order_number.' RUSH early';   
                                                    }else{
                                                    $counter_rownotes[] = $otp->order_number.' early';
                                                    }
                                                }else if( $reporttime == strtotime($otp->due_date) ){
                                                    if(stripos($otp->appraisal_type,'RUSH') !== false){
                                                    $counter_rownotes[] = $otp->order_number.' RUSH on time';   
                                                    }else{
                                                    $counter_rownotes[] = $otp->order_number.' on time';
                                                    }
                                                }else{
                                                    if(stripos($otp->appraisal_type,'RUSH') !== false){
                                                    $counter_rownotes[] = $otp->order_number.' RUSH ( '.round(($reporttime-strtotime($otp->due_date))/86400).' days ) late';   
                                                    }else{
                                                    $counter_rownotes[] = $otp->order_number.' ( '.round(($reporttime-strtotime($otp->due_date))/86400).' days ) late';
                                                    }
                                                }
                                            }
                                        }
                                        $totalorder++;
                                    }
                                    if( $otp->status == 'assigned' || $otp->status == 'inspected' || $otp->status == 'inspection_complete' ){
                                            $completeorder++;
                                    }
                                    if( $otp->appraised_value > 0 && ( $otp->appraised_value <  $otp->estimated_value ||  $otp->appraised_value <  $otp->purchase_price   )){
                                            $lowvalueorder++;
                                    }
                                }                
                                $counter_rownotes = implode('&#10;',$counter_rownotes);
                                echo " title='".str_replace("'",'',$counter_rownotes)."' class='sajkdljas'  ";      
                                } 
                                $uname = '';
                                if(isset($arruserappraisers[$item->appraiser_id])){ 
                                    $uname = $arruserappraisers[$item->appraiser_id]; 
                                } else { 
                                    $uname = jfactory::getUser($item->appraiser_id)->name; 
                                }
                                ?>
                                style="<?php if($appspec[$uname.'-'.$item->property_state.'-'.trim(str_replace('County','',$item->property_county))] > 1){ echo 'color:red;';}  ?>">
                                <?php 
                                if($item->appraiser_fee > 1){ echo '$'.str_replace('.00','',$item->appraiser_fee); }
                                if($item->appraiser_id){echo ' ('.$uname.')';} ?>
                                <?php if(in_array($item->appraiser_id, array(31778,49731,52592,51259,24888,50434,748))){ echo '[Staff]';}
                                if($item->appraiser_id){
                            /*$sql =  "SELECT * FROM `#__jobs_users`  where `user_id` = '".$item->appraiser_id."'  limit 0,1 ";
                            $db->setquery($sql);  
                            $b  =   $db->loadobject();*/  
                            $b = $jobusers[$item->appraiser_id];                     
                            echo  '['.round((strtotime($item->due_date) - strtotime($item->ordered_date))/86400).'D]['.$b->rank.'*]';}
                        ?> 
                        </span>
                        </td>
                    </tr>  
                     <?php
                }
            ?>
        </tbody>
        </table>
       </div>
    <div class="pager"> 
            <img src="https://mottie.github.io/tablesorter/addons/pager/icons/first.png" class="first"/> 
            <img src="https://mottie.github.io/tablesorter/addons/pager/icons/prev.png" class="prev"/> 
            <span class="pagedisplay"></span> <!-- this can be any element, including an input --> 
            <img src="https://mottie.github.io/tablesorter/addons/pager/icons/next.png" class="next"/> 
            <img src="https://mottie.github.io/tablesorter/addons/pager/icons/last.png" class="last"/> 
            <select class="pagesize" title="Select page size"> 
                <option value="20">20</option> 
                <option value="30">30</option> 
                <option value="50">50</option> 
                <option selected="selected" value="100">100</option> 
                <option value="all">All</option> 
            </select>
            <select class="gotoPage" title="Select page number"></select>
    </div>
    <style>
    body{overflow-x:hidden;}</style>
    
    <?php if($citylist){
        $citylist = array_unique($citylist);
        $citylist = array_filter($citylist);
        
        ?>
    <select name="city" style="height:30px;width:200px;position: absolute;top:15px;right:10px;" onchange="jQuery('.tablesorter-filter-row > td:nth-child(5) > input').val(jQuery(this).val());jQuery('.tablesorter-filter-row > td:nth-child(5) > input').change();" >
    <option value="">Select city</option> 
    <?php 
    foreach($citylist as $keystate => $statename){                               
        ?>
        <option  value="<?php echo str_replace('-',' ',$statename); ?>"><?php echo str_replace('-',' ',$statename); ?></option>
        <?php
    }
    ?>
</select>
<?php } ?>
    
    <?php
    die;
    }
} 
?>    
<div style="height: 700px; overflow: auto; margin-top: 210px;position: relative;">
<table class="tablesorter tablesorter-default" role="grid" style="width:100%">
<thead>
    <tr role="row">
        <th style="width:2%;">Time</th>
        <th style="width:5%;">Order</th>      
        <!--<th style="width:5%;">Price</th>-->
        <th style="width:12%;">Appraisal type</th>
        <th style="width:3%;">License</th>
        <th style="width:5%;">Zipcode</th>
        <th style="width:11%;">Lender
         <div style="width: 100%;float: left;" >
                        <div class='newbox blue'></div> <small>Turn on auto accept</small>
                    </div>
        </th>
        <th style="width:3%;">Logs</th>
        <?php /* 
        <th style="width:3%;display:none;">Prefer</th>
        <th style="width:3%;display:none;">DNU</th>
         * 
         */ ?>
        <th style="width:2%;" >SI</th>
         <th style="width:4%;">Invite</th>
        <th style="width:3%;">Cost</th>
        <th style="width:3%;">Profit</th>
        <th style="width:3%;">Last Profit</th>
        <th style="width:3%;">Due Time</th>
       <!-- <th style="width:14%;">
                <div>
                    <div style="width: 49%;float: left;" >
                        <div class='newbox red'></div> <small>Accept not match with lowest bid</small>
                    </div>
                    <div style="width: 49%;float: left;" >
                        <div class='newbox blue'></div> <small>Accept match with lowest bid</small>
                    </div>
                </div></th> -->
        <th style="width:2%;">Bids</th>
        <th style="width:5%;">Time accepted</th>
       
       
        <th style="width:22%;">
                <div>
                    <div style="width: 49%;float: left;" >
                        <div class='newbox red'></div> <small>Not match with staff Accept/Assign</small>
                    </div>
                    <div style="width: 49%;float: left;" >
                        <div class='newbox blue'></div> <small>Match with staff Accept/Assign</small>
                    </div>
                </div>
        </th>
        <?php /* <th style="width:5%;">Auto accept</th> */ ?>
        <th style="width:3%;">Payment</th>
       
    </tr>
</thead>
<tbody>
<?php  
    //  <th style="width:2%;">Staff Invite</th>
    //$db = jfactory::getDbo();
    //$ocrtimepath = $app->getCfg('log_path').'/ocrtime.txt';
    //$ocrtime = file_get_contents($ocrtimepath);
    //$ocrtime = json_decode($ocrtime,true);
    //$ocrtime = array_reverse($ocrtime);
    //foreach ($ocrtime as $k => $ro) {
    //    $sql = "select * from `#__jobs_ocrtime_log` where `reportpdf` like '".$k."' ";  
    //    $db->setquery($sql);
    //    $checkocrlog = $db->loadobject();  
    //    if(!$checkocrlog){
    //        $sql = "INSERT INTO `#__jobs_ocrtime_log` (`id`,`reportpdf`, `timecheck`, `appraisal_type`, `tesseract_pdftotext`, `googleocr`, `imageocr`, `easy`, `begintoocr`, `ocrrun`, `imagerun`, `afterimagetoend`, `afterocrtoimage` , `revisionrequest` , `server` , `ocrimage_epoch` , `ocrimage_php`) VALUES (NULL, '".$k."', '". $ro['timecheck'] ."', '". $ro['appraisal_type'] ."', '". $ro['tesseract+pdftotext'] ."', '". $ro['googleocr'] ."', '". $ro['ocrimage_php'] ."', '". $ro['easyocr'] ."', '". $ro['begintoocr'] ."', '". $ro['ocrrun'] ."', '". $ro['imagerun'] ."', '". $ro['afterimagetoend'] ."', '". $ro['afterocrtoimage'] ."', '". $ro['revisionrequest'] ."', '". $ro['server'] ."', '". $ro['ocrimage_epoch'] ."', '". $ro['ocrimage_php'] ."')";
    //       
    //        $db->setquery($sql);
    //        $db->query();   
    //    } 
    //}
    $bs = $f = array();
   $sql = "SELECT * FROM `#__jobs_task` where  `ordered_date` > '".date('Y-m-d',time()-$subtime)."' ";
   $db->setquery($sql);
   $items = $db->loadobjectlist();
   //echo '<br/>countorders='.count($items);
   foreach ($items  as $item){
       $itemsa[$item->id] = $item;
   }     
 
   
   
   $sql = "SELECT * FROM `#__jobs_task_comment` where  `comment` like '%flt_county_app:%' and `date_created` > '".date('Y-m-d H:i:s',time()-$subtime)."' group by `task_id` ";
 
   
   $db->setquery($sql);
   $alledit = $db->loadobjectlist();
   //echo '<br/>countcomment='.count($alledit);
   $arrtaskids = array();
   foreach ($alledit as $k => $ro) {
    if(!in_array($ro->task_id,$arrtaskids)){
        $arrtaskids[] = $ro->task_id;
    }
   }
   
 
   //echo '<br/>arrtaskids='.count($arrtaskids);
   foreach ($alledit as $k => $ro) {
        $item  = $itemsa[$ro->task_id];
        $quick  = explode('Available: ',$ro->comment);
        $quick  = explode('/',$quick[1]);
        $quick = $quick[0];        
        
        $property_address = $item->property_address;
        $addres_a = explode(',',$property_address);
        $zipcode = end($addres_a);
        $zipcode = explode(' ',$zipcode);
        $zipcode = end($zipcode);  
    
        if($quick == 1){
            $appspec[jfactory::getUser($item->appraiser_id)->name.'-'.$item->property_state.'-'.trim(str_replace('County','',$item->property_county))] += 1;
            
            $appspec2[$item->property_state.'-'.trim(str_replace('County','',$item->property_county)).'-'.jfactory::getUser($item->appraiser_id)->name] += 1;
        }
   } 
    if($_GET['debug'] == 1){  
        foreach ($appspec2 as $key => $r){
            if($r > 1){
                echo $key.'<br>';
            }
        }   
        ///echo '<pre>';
        //print_r($appspec);
        die;
    }
if($_GET['date'] != ''){
    $sql = "SELECT * FROM `#__jobs_task_comment` where  `comment` like '%flt_county_app:%' and DATE(DATE_SUB(`date_created`, INTERVAL 7 HOUR))  = '".$_GET['date']."' group by `task_id`  ";
    $db->setquery($sql);
    $checkedit = $db->loadobjectlist();

    $sql = "SELECT * FROM `#__jobs_task_comment` where  `comment` like '%changed from%' and DATE(DATE_SUB(`date_created`, INTERVAL 7 HOUR)) >= '".$_GET['date']."'  group by `task_id` ";
    //echo '<br/>sql='.$sql;
    $db->setquery($sql);
    $alljobcomments = $db->loadobjectlist();
    //echo '<pre>'; print_r($alljobcomments);
    
}else{
    $sql = "SELECT * FROM `#__jobs_task_comment` where  `comment` like '%flt_county_app:%' and DATE(DATE_SUB(`date_created`, INTERVAL 7 HOUR))  = '".date('Y-m-d')."' group by `task_id` ";
    $db->setquery($sql);
    $checkedit = $db->loadobjectlist();

    $sql = "SELECT * FROM `#__jobs_task_comment` where  `comment` like '%changed from%' and DATE(DATE_SUB(`date_created`, INTERVAL 7 HOUR)) >= '".date('Y-m-d')."' group by `task_id` ";
    //echo '<br/>sql='.$sql;
    $db->setquery($sql);
    $alljobcomments = $db->loadobjectlist();
    //echo '<pre>'; print_r($alljobcomments);

    $_GET['date'] = date('Y-m-d');
}

$aorderid = array();
foreach ($checkedit as $k => $ro) {
    if(!in_array($ro->task_id, $aorderid)){
        $aorderid[] = $ro->task_id;
    }
}
$arrsiinfos = array();
if(count($aorderid) > 0){
    
    
    $sql = "SELECT id,date_created,task_id FROM `#__jobs_task_comment`"
                . " WHERE ( `comment` LIKE 'Approved counter of %' OR `comment` LIKE 'accepted' or `comment` LIKE '%Approved recounter%'  ) and `task_id` in (".implode(",",$aorderid).") ORDER BY `id` ASC";
    $db->setquery($sql);
    $checkedit2 = $db->loadobjectlist();
    foreach($checkedit2 as $obj){
        
            $arrcheckedits[$obj->task_id] = $obj->date_created;
        
    }
    
    
    $useragent="Opera/9.80 (J2ME/MIDP; Opera Mini/4.2.14912/870; U; id) Presto/2.4.15"; 
    $url = 'https://suntendervaluations.com/specialfilter.php?aorderid='.implode('_',$aorderid);
    //echo '<br/>url='.$url;
    $ch=curl_init ("");
    curl_setopt($ch, CURLOPT_URL, $url);
    //echo '<textarea style="display:none;">'.$url.'</textarea>';
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent); // set user agent
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $strsiinfos = curl_exec($ch);
    $arrsiinfos = json_decode($strsiinfos,true);
    if(!is_array($arrsiinfos)){ $arrsiinfos = array(); }
    curl_close($ch);
    //echo '<pre>'; print_r($arrsiinfos);
}
function getspecialfilterinfo($ro,$arrsiinfos){
    $strresult = '';
    $objsi = isset($arrsiinfos[$ro->task_id]) ? $arrsiinfos[$ro->task_id] : array();
    $sibefore = isset($objsi['before']) ? $objsi['before'] : '';
    $siafter = isset($objsi['after']) ? $objsi['after'] : '';
    $passai = isset($objsi['passai']) ? $objsi['passai'] : 0;
    $isnew = $objsi['isnew'];
    $isrush = $objsi['isrush'];   
    $isinvoice = $objsi['isinvoice'];   
    $isinspect = $objsi['isinspect'];
    $isschedule = $objsi['isschedule'];
    $iscontact = $objsi['iscontact']; 
    $isappraiser = $objsi['isappraiser']; 
    $isblacklist = $objsi['isblacklist'];
    $istotal = $objsi['istotal'];
    if($sibefore != ''){
        $siinfo = '';
        $siinfo = 'Before:&#10;'.$sibefore;
        if($siafter != ''){
            $siinfo .= '&#10;---------&#10;After:&#10;';        
            $siinfo .= $siafter;
            $siinfo .= '&#10;---------&#10;Checked:'; 
            if($passai == 1){
                $siinfo .= '&#10;AI: Pass'; 
            } 
            else{
                if($istotal > 0){
                    if($isnew == 1){
                        $siinfo .= '&#10;New Construction: True';
                    }
                    if($isrush == 1){
                        $siinfo .= '&#10;Rush: True';
                    }
                    if($isinvoice == 1){
                        $siinfo .= '&#10;Invoice: True';
                    }
                    if($isinspect == 1){
                        $siinfo .= '&#10;Inspect: True';
                    }
                    if($isschedule == 1){
                        $siinfo .= '&#10;Schedule: True';
                    }
                    if($iscontact == 1){
                        $siinfo .= '&#10;Contact: True';
                    }
                    if($isappraiser == 1){
                        $siinfo .= '&#10;Appraiser: True';
                    }
                    if($isblacklist == 1){
                        $siinfo .= '&#10;Blacklist: True';
                    }
                }
                else{
                    $siinfo .= '&#10;AI: No';
                }
            }
        }
        $style = 'style="color:red;"';
        if($siafter == ''){
        if($siafter == '' || $passai == 1){
            $style = 'style="color:green;"';
        }
        $strresult = "<span class='sajkdljas' ".$style." title='".str_replace("'",'',$siinfo)."'>SI</span>";
    }
    else{
        $siinfo = 'Before:&#10;'.$sibefore.' &#10;After:&#10;'.$siafter;
        if($siafter){
            $style = 'style="color:red;"';
        }else{
            $style = 'style="color:green;"';
        }
        $strresult = "<span class='sajkdljas' ".$style." title='".str_replace("'",'',$siinfo)."'>SI</span>";
    }
    return $strresult;
    }else{
        $strresult = "<span class='sajkdljas' style='color:green;' title='No SI'>SI</span>";
        return $strresult;
    }
}
foreach ($checkedit as $k => $ro) {
    $sql = "SELECT * FROM `#__jobs_task` where  `id` = '".$ro->task_id."' ";
    $db->setquery($sql);
    $item = $db->loadobject();
    $quick  = explode('Available: ',$ro->comment);
    $quick  = explode('/',$quick[1]);
    $quick = $quick[0];
  
    $property_address = $item->property_address;
    $addres_a = explode(',',$property_address);
    $zipcode = end($addres_a);
    $zipcode = explode(' ',$zipcode);
    $zipcode = end($zipcode);
    $pricevalue = get_price_of_property($item);
    $dblpricevalue = (float)str_replace(array('$',','),'',$pricevalue);
    if($item->order_number == '202003200003'){
        continue;
    }
    ?>
    <tr role="row">
         <td>
            <?php 
            //echo JHtml::_('date', $ro->date_created, 'y-m-d H:i', false);
            echo JHtml::_('date', $ro->date_created, 'H:i', false);
            ?>
        </td>
         <td><?php echo $item->order_number; ?></td>
        <!--<td>
            <?php 
            echo $pricevalue;
           ?>
        </td>-->
         <td>
            <?php 
            echo $item->appraisal_type;
            if($dblpricevalue > 1000000){
                echo ' (> 1 mil)';
            }
            //if(stripos($item->appraisal_type,'fha')!== false){ echo ' (FHA)';}
             ?> 
        </td>
         <td>
            <?php 
            $type  = explode('flt_license_type: ',$ro->comment);
            $type  = explode('flt_county_app',$type[1]);
            $type = $type[0]; 
            if($type){ echo $type; } else{ echo 'All'; } 
            ?>
        </td>
         <td>
            <?php echo $states[$item->property_state].'-'.str_replace('County','',$item->property_county) ; ?>
        </td>
        <td><a class="<?php if((stripos($item->company_name,'Googain') !== false
            || ( stripos($item->company_name,'First Lending') !== false && stripos($item->company_name,'Advantage First Lending') === false )
            || (stripos($item->company_name,'AAXY LLC dba Austin First Mortgage') !== false && $item->payment_received)
            || (stripos($item->company_name,'Panorama Mortgage Group') !== false && $item->payment_received)
            || (stripos($item->company_name,'Royal Business Bank') !== false && $item->payment_received)
            || (stripos($item->company_name,'Neighborhood loans') !== false && $item->payment_received) 
            || (stripos($item->company_name,'Alameda Mortgage Corporation') !== false))
            
            || ( stripos($item->company_name,'PRMG') !== false )  
            || ( stripos($item->company_name,'Guaranteed Rate') !== false )  
            || ( stripos($item->company_name,'Advantage First Lending') !== false )       
            //|| $item->source_type == 'reggora'        
            //|| ( stripos($item->company_name,'New Wave') !== false )          
            ){ echo 'isblue'; } ?>" ><?php echo $item->company_name; ?></a></td>
        <td><?php echo get_log_change($alljobcomments, $item); ?></td>
        <?php /* 
        <td style="display:none;" >
            <?php if(stripos($ro->comment,'Lender preferred:') !== false){  ?><a href="#" title="<?php $preferred  = explode('Lender preferred:',$ro->comment); $preferred  = explode('<b>',$preferred[1]);  $preferred = $preferred[0]; echo $preferred;   ?>">Prefer</a>  <?php } ?>
        </td>
         <td  style="display:none;" >
            <?php if(stripos($ro->comment,'flt_bank_approved: ') !== false){  ?><a href="#"  title="<?php $dnu  = explode('flt_bank_approved: ',$ro->comment); $dnu  = explode('Available:',$dnu[1]);  $dnu = $dnu[0]; echo $dnu;   ?>" >DNU</a> <?php } ?>
        </td>
         */ ?>
        
         <td>
            <?php 
            echo getspecialfilterinfo($ro,$arrsiinfos);
            ?>
        </td>
        
         <td>
             <?php 
             
             
                $sql = "SELECT * FROM `#__jobs_task_comment` where "
                . " `task_id` = '$item->id' "            
                . " and (  `comment` like '%Assign to appraiser%'  ) "
                . " ORDER BY `id` ASC limit 0,1  ";
                $db->setquery($sql);
                $checkedit = $db->loadobject();
                
             /*    <td><?php echo $quick; ?></td> */
                $sql = "select * from #__jobs_task_appraiser_script where `task_id` = '".$item->id."' group by `assign_to_id` ";
                ///echo $sql;
                $db->setquery($sql);
                $appraiser_script = $db->loadobjectlist();
                $appraiser_script_list = array();
                foreach($appraiser_script as $as){
                    $appraiser_script_list[] = jfactory::getUser($as->assign_to_id)->name;
                }
                $sdnln = 0;
                if(!$datalog[$item->order_number] && count($appraiser_script_list) == 0){
                    if(strtotime($checkedit->date_created) - strtotime($item->date_created) < 60*30){
                        $datalog[$item->order_number] =  'staff invite < 8 mins from order created';
                    }
                }
                if($datalog[$item->order_number] && count($appraiser_script_list) == 0){
                    echo "<a title='".$datalog[$item->order_number]."' class='sajkdljas'>Note/Staff ".$quick."</a>";
                }elseif(count($appraiser_script_list) == 0){
                   
                    if(strtotime($ro->date_created) - (strtotime($item->date_created)) > 450 && $item->order_number > date('Ymd',strtotime($_GET['date'])).'0000'){
                        echo "<a title='".$datalog[$item->order_number]."' time='".(strtotime($ro->date_created) - (strtotime($item->date_created)))."' class='sajkdljas '>Staff ".$quick."</a>";
                    }else{
                        if($item->order_number > date('Ymd',strtotime($_GET['date'])).'0000'){
                            echo "<a title='".$datalog[$item->order_number]."' time='".(strtotime($ro->date_created) - (strtotime($item->date_created)))."' class='sajkdljas '>Staff ".$quick."</a>";
                        }else{
                            echo "<a title='".$datalog[$item->order_number]."' time='".(strtotime($ro->date_created) - (strtotime($item->date_created)))."' class='sajkdljas '>R-Staff ".$quick."</a>";
                        }
                    }
                    
                    
                }else{
                     $sdnln = 1;
                    echo "<a title='".str_replace("'",'',implode('&#10;',$appraiser_script_list))."' class='sajkdljas'>Auto ".count($appraiser_script).'</a>';
                    if(count($appraiser_script) > 0 && stripos($scripassign,$item->order_number.'|begin invite') !== false ){
                        
                        $scripassign1 = explode($item->order_number.'|begin invite',$scripassign);
                    
                        $scripassign1 = explode('}',$scripassign1[1]);
                          
                        $scripassign1 = $scripassign1[0];
 //echo '<textarea>'.$item->order_number.'|begin invite-'.$scripassign1.'</textarea>';die;
                        if(stripos($scripassign1,'"after":""') === false && stripos($scripassign1,'"passai":1') !== false ){
                            echo '<br>AI False';
                        }
                    }
                }
                 
             ?>
         </td>
         <td><?php echo '$'.$item->appraisal_cost; ?></td>
          <td <?php if(stripos($item->appraisal_type,'disaster') !== false){ if(stripos($item->appraisal_type,'Interior') !== false){ echo 'class="isred"'; }else{ echo 'class="isblue"'; } } ?> ><?php if($item->appraiser_fee > 1){ echo '$'; echo ( $item->appraisal_cost - $item->appraiser_fee ); } ?></td>
          <td>
          <?php 
          $sql =  "SELECT * FROM `#__jobs_task`  where `appraisal_type` like '".$db->escape($item->appraisal_type)."' and  `id` <> '".$item->id."'  and `property_state` = '".$db->escape($item->property_state)."' and   `property_county` = '".$db->escape($item->property_county)."' ORDER BY `id` DESC limit 0,3 ";
          $db->setquery($sql);  
          $lastorders = $db->loadobjectlist();
          $appraisal_costlast = array();
          $lastorderstr = '';
          foreach ($lastorders as $lastorder){
              if($lastorder->appraiser_id > 0){
                  if( $lastorder->appraisal_cost - $lastorder->appraiser_fee > 0){
                      $appraisal_costlast[] = ($lastorder->appraisal_cost - $lastorder->appraiser_fee);
                      $lastorderstr .= $lastorder->order_number.' - $'.($lastorder->appraisal_cost - $lastorder->appraiser_fee).' - '.jfactory::getUser($lastorder->appraiser_id)->name.'&#10;';
                  }
              }
          }
          if(count($appraisal_costlast) > 0){
              
              $appraisal_costlastavg = number_format(array_sum($appraisal_costlast)/count($appraisal_costlast),0);
              if($item->appraisal_cost - $item->appraiser_fee > 0 && $item->appraisal_cost - $item->appraiser_fee < $appraisal_costlastavg){
                   echo '<span style="color:red;" title="'.$lastorderstr.'&#10;($'.(($appraisal_costlastavg-25 < 200)?200:($appraisal_costlastavg-25)).'~$'.($appraisal_costlastavg+25).')" >$'; echo ( $appraisal_costlastavg ).'</span>';
              }else{
                   echo '<span title="'.$lastorderstr.'&#10;($'.(($appraisal_costlastavg-25 < 200)?200:($appraisal_costlastavg-25)).'~$'.($appraisal_costlastavg+25).')" >$'; echo ( $appraisal_costlastavg ).'</span>';
              }
             
          }
          ?>
        </td>
         <td>
            <?php echo round((strtotime($item->client_due) - strtotime($item->ordered_date))/86400); ?>
        </td>
          <!--<td>
            <?php 
          $sql =  "SELECT appraiser_fee, user_id , counter_due_date FROM `#__jobs_task_counter`  where `appraiser_fee` > 1 and  `task_id` = '".$item->id."' ORDER BY `appraiser_fee` ASC limit 0,1 ";
          $db->setquery($sql);  
          $a  =   $db->loadobject(); 
          if($a->user_id){
            if( $item->appraiser_id == ''  ||  $item->appraiser_id == 0){    
              echo '<span>';      
            }elseif($a->user_id == $item->appraiser_id || $item->appraiser_fee == $a->appraiser_fee ){    
              echo '<span style="color:blue;" >';      
            }else{
              $db->setquery("select `id` , `order_number` , `appraisal_type` , `status`, `purchase_price`, `estimated_value`, `appraised_value` , `due_date`  from #__jobs_task where appraiser_id  = '".$a->user_id."' order by `id` DESC  ");
              $dataprice = $db->loadobjectlist();
              
              //if($item->id == 100709){  echo '<pre>';print_r($a);print_r($dataprice); }
              $counter_rownotes = array();
              $completeorder = 0 ;
              $lowvalueorder = 0 ;
              $totalorder = 0;
                                              
               foreach ($dataprice as $otp){
                if( $otp->status == 'complete' ){
                       if(count((array)$counter_rownotes) < 5  ){
                        $db->setquery("select * from #__jobs_task_file where `task_id`  = '".$otp->id."' and `file_title` = 'pdf_report' order by `id` ASC  ");
                        $firstreport = $db->loadobject();
                        $reporttime = strtotime((date('Y-m-d',strtotime($firstreport->date_created)-7*3600)));
                        if( $reporttime < strtotime($otp->due_date) ){
                            if(stripos($otp->appraisal_type,'RUSH') !== false){
                             $counter_rownotes[] = $otp->order_number.' RUSH early';   
                            }else{
                             $counter_rownotes[] = $otp->order_number.' early';
                            }
                        }else if( $reporttime == strtotime($otp->due_date) ){
                            if(stripos($otp->appraisal_type,'RUSH') !== false){
                             $counter_rownotes[] = $otp->order_number.' RUSH on time';   
                            }else{
                             $counter_rownotes[] = $otp->order_number.' on time';
                            }
                        }else{
                            if(stripos($otp->appraisal_type,'RUSH') !== false){
                             $counter_rownotes[] = $otp->order_number.' RUSH ( '.round(($reporttime-strtotime($otp->due_date))/86400).' days ) late';   
                            }else{
                             $counter_rownotes[] = $otp->order_number.' ( '.round(($reporttime-strtotime($otp->due_date))/86400).' days ) late';
                            }
                        }
                       }

                       $totalorder++;
                }
                if( $otp->status == 'assigned' || $otp->status == 'inspected' || $otp->status == 'inspection_complete' ){
                        $completeorder++;
                }
                if( $otp->appraised_value > 0 && ( $otp->appraised_value <  $otp->estimated_value ||  $otp->appraised_value <  $otp->purchase_price   )){
                        $lowvalueorder++;
                }
                }
                
                $counter_rownotes = implode('&#10;',$counter_rownotes);

                echo "<span  class='sajkdljas'  style='color:red; lowestbidnotpick' title='".str_replace("'",'',$counter_rownotes)."'  >";      
            }
            $sql =  "SELECT * FROM `#__jobs_users`  where `user_id` = '".$a->user_id."'  limit 0,1 ";
            $db->setquery($sql);  
            $b  =   $db->loadobject(); 
            
            
            $sql =  "SELECT appraiser_fee, user_id , counter_due_date FROM `#__jobs_task_counter`  where `appraiser_fee` > 1 and  `task_id` = '".$item->id."'  ORDER BY `appraiser_fee` ASC  ";//limit 0,5 // and user_id <> '".$a->user_id."'
            $db->setquery($sql);  
            $la  =   $db->loadobjectlist(); 
          
          
            $tooltipautoaccept1 = '';
            foreach($la as $l){
                 $tooltipautoaccept1 .= '&#10;'.jfactory::getUser($l->user_id)->name.' - $'.number_format($l->appraiser_fee);
            }
           
             
             
            if(round((strtotime($a->counter_due_date) - strtotime($item->ordered_date)))  <  0){
                if($item->appraiser_fee == $a->appraiser_fee){///counter_due_date
                    echo '<a href="#" style="color:blue;" >$'.str_replace('.00','',$item->appraiser_fee).' ('.jfactory::getUser($item->appraiser_id)->name.')['.$b->rank.'*][match]</a>'; 
                    $matchwithlowest = '[Lowest]';
                }else{
                    echo '<a href="#"  style="color:red;" >$'.str_replace('.00','',$a->appraiser_fee).' ('.jfactory::getUser($a->user_id)->name.')['.$b->rank.'*]</a>';     
                     $matchwithlowest = '<a  title="'.$tooltipautoaccept1.'"  >[Not Lowest]</a>';
                }
            }else{
                if($item->appraiser_fee == $a->appraiser_fee){///counter_due_date
                echo '<a href="#"  style="color:blue;" >$'.str_replace('.00','',$item->appraiser_fee).' ('.jfactory::getUser($item->appraiser_id)->name.')['.round((strtotime($a->counter_due_date) - strtotime($item->ordered_date))/86400).'D]['.$b->rank.'*][match]</a>'; 
                    $matchwithlowest = '[Lowest]';
                }else{
                    echo '<a href="#"  style="color:red;" >$'.str_replace('.00','',$a->appraiser_fee).' ('.jfactory::getUser($a->user_id)->name.')['.round((strtotime($a->counter_due_date) - strtotime($item->ordered_date))/86400).'D]['.$b->rank.'*]</a>'; 
                     $matchwithlowest = '<a  title="'.$tooltipautoaccept1.'"  >[Not Lowest]</a>';
                }
            }
            
            echo '</span>';
          } ?>
          </td>-->
         <td><?php 
            $sql = "SELECT * FROM `#__jobs_task_comment` where "
            . " `task_id` = '$item->id' "            
            . " and (  `comment` like '%Assign to appraiser%' or   `comment` like '%Invite to appraiser%' ) "
            . " ORDER BY `id` DESC limit 0,1  ";
            $db->setquery($sql);
            $checkedit = $db->loadobject();
        
            $sql = "SELECT * FROM `#__jobs_task_comment`"
            . " WHERE ( `comment` LIKE 'Approved counter of %' OR `comment` LIKE 'accepted' ) and `task_id` = '".$item->id."' "
            . " ORDER BY `id` DESC limit 0,1  ";
            $db->setquery($sql);
        
            $checkedit2 = $db->loadobject();
           
                    
            $sql = "SELECT * FROM `#__jobs_task_comment` where  ( `comment` LIKE '%Approved recounter%'  ) and `task_id` = '".$item->id."'  ";
        
            $db->setquery($sql);
            $acceptcomments = $db->loadobject();
       
        

            $sql =  "SELECT count(*) FROM `#__jobs_task_counter`  where `task_id` = '".$item->id."'  ";// and  `date_created`  < '".$checkedit2->date_created."'
            $db->setquery($sql);  
            echo '<a title="'.$tooltipautoaccept1.'" >'.$db->loadresult().'</a>'; 
            if(!$db->loadresult()){
                $matchwithlowest = '[Lowest]';
            }
          ?><?php if($acceptcomments){ echo 'Yes'; } ?></td>
        
         <td><?php 
         $strmin = '';$lessthan4h = '';
         if($checkedit2 && $checkedit && $item->appraiser_id){  
            $itime = (strtotime($checkedit2->date_created) - strtotime($checkedit->date_created));
            if($itime > 0){
                $h = (int)($itime/(60 * 60));
                if($h < 120){
                    $lessthan4h = 'Staff Accept < 2H';
                }
                if(stripos($item->appraisal_type,'1004d') !== false){
                    if($item->appraiser_fee > 1){ 
                        if($item->appraisal_cost - $item->appraiser_fee < 100){
                            $lessthan4h = 'Staff pick profit < $100';
                        }
                        }
                   
                }else{
                        if($item->appraiser_fee > 1){ 
                            if($item->appraisal_cost - $item->appraiser_fee < 100){
                                $lessthan4h = 'Staff pick profit < $200';
                            }
                        }
                }
                
                //echo 'h0='.$h.'|h1='.(int)$h;
                $itime = $itime - ($h * 60 * 60);
                $m = 0;
                if($itime > 0){
                    $m = (int)($itime/60);
                }
                if($h > 0){
                    $strmin .= $h.'H';
                }
                if($m > 0){
                    if($h > 0){
                        $strmin .= ':';
                    }
                    $strmin .= $m.'M';
                }
                if(isset($countyfee[$item->property_state][$item->property_county])){
                 if($itime < $countyfee[$item->property_state][$item->property_county][0]['itimeaccept']){
                     $style = 'style="color:red"';
                 }else{
                     $style = 'style="color:blue"';
                 }   
                 $strmin = '<a '.$style.' title="last invite to accept. average this county ~'. $countyfee[$item->property_state][$item->property_county][0]['timeaccept'].'" >'.$strmin.'</a>';   
                 
                }else{
                 $strmin = '<span title="last invite to accept , no data average time" >'.$strmin.'</span>';
                }
            }
            
        }elseif($countyfee[$item->property_state][$item->property_county][0]['timeaccept']){
             $strmin = '~'.$countyfee[$item->property_state][$item->property_county][0]['timeaccept'];
        } 
        //$strmin .= ' / ';
//        if($checkedit2 && $checkedit && $item->appraiser_id){  
//            $itime = (strtotime($checkedit2->date_created) - strtotime($item->ordered_date));
//            if($itime > 0){
//                $h = (int)($itime/(60 * 60));
//                //echo '<br/>h2='.$h.'|h2='.(int)$h;
//                $itime = $itime - ($h * 60 * 60);
//                $m = 0;
//                if($itime > 0){
//                    $m = (int)($itime/60);
//                }                
//                if($h > 0){
//                    $strmin .= $h.'H';
//                }
//                if($m > 0){
//                    if($h > 0){
//                        $strmin .= ':';
//                    }
//                    $strmin .= $m.'M';
//                }
//                $strmin = '<span title="Order created to accept" >'.$strmin.'</span>';
//            }
//        }
        
        if($item->status == 'cancelled' && $strmin == '/' ){
            $strmin = 'Cancelled';
        }
        if($item->status == 'waiting' && $strmin == '/' ){
            $strmin = 'Lender Approval Needed';
        }
        
        echo $strmin;
        
        
         ?>
        </td>         
      
        
         <td>
              <?php 
                $match = '';
                $appraisenameass = '';
                $lcscolor = $tooltipautoaccept = ''; 
                if(isset($acceptlog[$item->order_number])){
                    $straccept = $acceptlog[$item->order_number];
                    $acceptlogby = (array)str_replace(array('<br/>','<br>'),'&#10;',$straccept);
                    if($straccept != ''){
                        $tooltipautoaccept = str_replace("'",'',implode('&#10;',$acceptlogby));
                        if(stripos($straccept,'Accept bid of') !== false){ 
                            $lcscolor = '';
                            if(strpos($straccept,'Appraiser:') !== false){                                
                                $appraisenameass = trim(explode('Appraiser:',$straccept)[1]); 
                            } 
                            if($item->appraiser_id > 0){
                                $namewithorder = jfactory::getUser($item->appraiser_id)->name;
                                if(    $checkedit2->user_id == '30259' ){
                                    $appraisenameass = 'Auto:'.$appraisenameass;
                                    $match = 'Match';
                                    $lcscolor = 'style="color:blue;" title="script accept" ';
                                    $tooltipautoaccept = 'script accept';
                                }else if(stripos($straccept,$namewithorder) !== false){
                                    $match = 'Match';
                                    $lcscolor = 'style="color:blue;" title="match with staff accept" ';
                                    $tooltipautoaccept = 'match with staff accept';
                                } 
                                
                                else{
                                    $lcscolor = 'style="color:red;" ';
                                    $tooltipautoaccept = 'Appraiser auto accept: '.$appraisenameass;
                                    $tooltipautoaccept .= '&#10;Appraiser assign order: '.$namewithorder;
                                } 
                            }
                            if($appraisenameass != ''){
                                if( $item->appraiser_id == 0){
                                    if($lcscolor == ''){
                                        $lcscolor = 'style="color:blue;" title="match with lowest bid but not accept yet"  ';
                                        $tooltipautoaccept = 'match with lowest bid but not accept yet';
                                    }
                                }else{
                                    if($lcscolor == ''){
                                        $lcscolor = 'style="color:blue;" title="match with lowest bid but not match with staff accept"  ';
                                        $tooltipautoaccept = 'match with lowest bid but not match with staff accept';
                                    }
                                }
                            }
                            if($match != ''){
                                //echo '('.$match.')';
                            }
//                            echo "<a title='".$tooltipautoaccept."' ".$lcscolor." class='sajkdljas'>";
//                            echo $appraisenameass;
//                            echo "</a>";
                        }
                        else{
                            //echo '<pre>'; print_r($acceptlogby);
//                            echo "<a title='".$tooltipautoaccept."' class='sajkdljas'>No accept</a>";
                        }
                    }                
                }else{
                     
                }
            ?>
             
             <span
                 <?php 
            if( $item->appraiser_id == ''  ||  $item->appraiser_id == 0){    
              
            }elseif($a->user_id == $item->appraiser_id || $item->appraiser_fee == $a->appraiser_fee ){    
             
            }else{
              $db->setquery("select `id` , `order_number` , `appraisal_type` , `status`, `purchase_price`, `estimated_value`, `appraised_value` , `due_date`  from #__jobs_task where appraiser_id  = '".$item->appraiser_id."' order by `id` DESC  ");
              $dataprice = $db->loadobjectlist();
              $counter_rownotes = array();
              $completeorder = 0 ;
              $lowvalueorder = 0 ;
              $totalorder = 0;
                                              
               foreach ($dataprice as $otp){
                if( $otp->status == 'complete' ){
                       if(count((array)$counter_rownotes) < 5  ){
                        $db->setquery("select * from #__jobs_task_file where `task_id`  = '".$otp->id."' and `file_title` = 'pdf_report' order by `id` ASC  ");
                        $firstreport = $db->loadobject();
                        $reporttime = strtotime((date('Y-m-d',strtotime($firstreport->date_created)-7*3600)));
                        if( $reporttime < strtotime($otp->due_date) ){
                            if(stripos($otp->appraisal_type,'RUSH') !== false){
                             $counter_rownotes[] = $otp->order_number.' RUSH early';   
                            }else{
                             $counter_rownotes[] = $otp->order_number.' early';
                            }
                        }else if( $reporttime == strtotime($otp->due_date) ){
                            if(stripos($otp->appraisal_type,'RUSH') !== false){
                             $counter_rownotes[] = $otp->order_number.' RUSH on time';   
                            }else{
                             $counter_rownotes[] = $otp->order_number.' on time';
                            }
                        }else{
                            if(stripos($otp->appraisal_type,'RUSH') !== false){
                             $counter_rownotes[] = $otp->order_number.' RUSH ( '.round(($reporttime-strtotime($otp->due_date))/86400).' days ) late';   
                            }else{
                             $counter_rownotes[] = $otp->order_number.' ( '.round(($reporttime-strtotime($otp->due_date))/86400).' days ) late';
                            }
                        }
                       }

                       $totalorder++;
                }
                if( $otp->status == 'assigned' || $otp->status == 'inspected' || $otp->status == 'inspection_complete' ){
                        $completeorder++;
                }
                if( $otp->appraised_value > 0 && ( $otp->appraised_value <  $otp->estimated_value ||  $otp->appraised_value <  $otp->purchase_price   )){
                        $lowvalueorder++;
                }
                }                
                $counter_rownotes = implode('&#10;',$counter_rownotes);
                echo " title='".str_replace("'",'',$counter_rownotes)."' class='sajkdljas1'  ";      
                }                 
             ?>
                 style="<?php if($sdnln){if(in_array(jfactory::getUser($item->appraiser_id)->name, $appraiser_script_list)){ echo 'color:blue;';  }else{ echo 'color:red;'; }}  if($appspec[jfactory::getUser($item->appraiser_id)->name.'-'.$item->property_state.'-'.trim(str_replace('County','',$item->property_county))] > 1){ echo 'color:red;';}  ?>"   ><?php 
                  if($item->appraiser_fee > 1){
                      
                      
                  if(isset($acceptlog[$item->order_number])){
                     if($checkedit2->user_id  ==  '30259' || $acceptcomments->user_id == '30259' ){
                        echo '<span title="'.$appraisenameass.' | '.$tooltipautoaccept.'" >[AUTO]</span> ';
                    }else{
                        echo '<span title="'.$appraisenameass.' | '.$tooltipautoaccept.'" '.$lcscolor.' >[STAFF '.jfactory::getUser($checkedit2->user_id)->name.']</span> ';
                    }  
                  }else{
                    if($checkedit2->user_id  ==  '30259' || $acceptcomments->user_id == '30259' ){
                        echo '<span title="'.$lessthan4h.'" >[AUTO]</span> ';
                    }else{
                        echo '<span title="'.$lessthan4h.'" >[STAFF '.jfactory::getUser($checkedit2->user_id)->name.']</span> ';
                    }
                  }
                  }elseif( $appraisenameass != '' || $tooltipautoaccept != '' || $lcscolor != '' ){
                      $matchwithlowest = '';
                      echo '<span title="'.$appraisenameass.' | '.$tooltipautoaccept.'" '.$lcscolor.' >[SIMULATION]</span> ';
                  }else{
                        
                  }
                 if($item->appraiser_fee > 1){ echo '$'.str_replace('.00','',$item->appraiser_fee); }
         if($item->appraiser_id){echo  ' ('.jfactory::getUser($item->appraiser_id)->name.')';} ?>
         <?php if(in_array($item->appraiser_id, array(31778,49731,52592,51259,24888,50434,748))){ echo '[Staff]';}
         if($item->appraiser_id){
             $sql =  "SELECT * FROM `#__jobs_users`  where `user_id` = '".$item->appraiser_id."'  limit 0,1 ";
             $db->setquery($sql);  
             $b  =   $db->loadobject(); 
             
             echo  '['.round((strtotime($item->due_date) - strtotime($item->ordered_date))/86400).'D]['.$b->rank.'*]'.$matchwithlowest;}
         ?> 
         </span>
        </td>
      
        
         <td>
          <?php  if($item->appraiser_id > 0){
                          if(strtotime( $arrcheckedits[$item->id] ) > strtotime($item->payment_received_date)){
                              $payment = 'Before'; 
                          }else{
                              $payment = 'After';
                          }
                          echo $payment;
                      } ?>
        </td>
    </tr>   
 <?php  
 }
  ?>
 </tbody>
</table>
<style>
tr.trdate{background-color:#449d44;} tr.trdate td, tr.trdate td a{color:#fff;}
.table tr td.tdfirst{background-color:#5cb85c;color:#fff;}
.table tr:not(.trdate) td:nth-child(2n+3){background-color:#eee;}
.table-responsive{width: 100%;}
.table-responsive .table{
    table-layout: fixed;}
.table-responsive .table tr td.tdfirst {
    width: 120px;
}
</style>
</div>
<table class="table" style="    position: absolute;    top: 0;    background: #ffffff;">
<tbody><tr class="trdate">
<td class="tdfirst"><b>Date</b></td>
<?php
//$sql = "SELECT DATE(DATE_SUB(`date_created`, INTERVAL 7 HOUR)) as date_created , count(*) as sl  FROM `#__jobs_task_comment` where  `comment` like '%flt_county_app:%' and DATE(DATE_SUB(`date_created`, INTERVAL 7 HOUR)) > '".date('Y-m-d',strtotime('-31 day'))."' group by DATE(DATE_SUB(`date_created`, INTERVAL 7 HOUR))  ";
//$db->setquery($sql);
//$ta = $db->loadobjectlist();
//foreach ($ta as $r){
//    $t[$r->date_created] =  $r->sl;
//    
//}
$checkstaff = array();
$sql = "SELECT  id , order_number FROM `#__jobs_task` where   DATE(DATE_SUB(`date_created`, INTERVAL 7 HOUR)) > '".date('Y-m-d',strtotime('-31 day'))."'  ";
$db->setquery($sql);
$ta = $db->loadobjectlist();
foreach ($ta as $r){
   $ornum_id[$r->id] = $r->order_number;
}



$sql = "SELECT * FROM `#__jobs_task_comment`"
. " WHERE ( `comment` LIKE 'Approved counter of %'  ) and `user_id` = '30259' "
. " ORDER BY `id` DESC  ";
$db->setquery($sql);

$checkedit2 = $db->loadobjectlist();

$sql = "SELECT DATE(DATE_SUB(`date_created`, INTERVAL 7 HOUR)) as date_created , task_id FROM `#__jobs_task_comment` where  `comment` like '%flt_county_app:%' and DATE(DATE_SUB(`date_created`, INTERVAL 7 HOUR)) > '".date('Y-m-d',strtotime('-31 day'))."'  ";
$db->setquery($sql);
$ta = $db->loadobjectlist();
foreach ($ta as $r){
    if(!is_countable($t2[$r->date_created])){
        $t2[$r->date_created] = array();
    }
    
    if(!in_array($r->task_id,$t2[$r->date_created])){
    $t2[$r->date_created][] =  $r->task_id;
     $t[$r->date_created]++;
    }
    if(!isset($checkstaff[$r->task_id])){
        $checkstaff[$r->task_id] = $r->date_created;
    }
}
for ($i= 0 ; $i < 30 ; $i++){
    $linkcall = 'https://suntendervaluations.com/invite-accept.php?date='.date('Y-m-d',  strtotime('-'.$i.' day'));  
    ?>
<td><a href="<?php echo $linkcall; ?>"><?php echo date('m/d',  strtotime('-'.$i.' day')); ?></a></td>
<?php } ?>
</tr>
<tr >
<td class="tdfirst"><b>Total</b></td>
<?php for ($i= 0 ; $i < 30 ; $i++){ ?>
<td><?php echo $t[date('Y-m-d',  strtotime('-'.$i.' day'))]; ?></td>
<?php } ?>
</tr>
<tr>
<td class="tdfirst"><b>Auto invite pass</b></td>
<?php for ($i= 0 ; $i < 30 ; $i++){  
       $sql = "select count(*) as sl from `#__jobs_task_appraiser_script` where DATE(`date_approved`) = '".date('Y-m-d',  strtotime('-'.$i.' day'))."' group by `task_id` ";      
       $db->setquery($sql);
       $c = $db->loadobjectlist();
                           
      $autoinvitepass[date('Y-m-d',  strtotime('-'.$i.' day'))] =        count($c);              
    ?>
<td> <?php  echo number_format(count($c));     ?></td>
<?php } ?>
</tr>
<tr>
<td class="tdfirst"><b>Auto invite check</b></td>
<?php for ($i= 0 ; $i < 30 ; $i++){     
     $invitecheck = 0;
     foreach ($t2[date('Y-m-d',  strtotime('-'.$i.' day'))] as $r  ){
       if(isset($datalog[$ornum_id[$r]])){
           $invitecheck++;
       }
     }      
     $autoinvitecheck[date('Y-m-d',  strtotime('-'.$i.' day'))] =        $invitecheck;              
    
    ?>
<td> <?php  echo number_format($invitecheck); ?></td>
<?php } ?>
</tr>
<tr>
<td class="tdfirst"><b>Auto accept</b></td>
<?php for ($i= 0 ; $i < 30 ; $i++){ 
    $ymdinviteaccept = date('Ymd',strtotime('-'.$i.' day'));
    ?>
<td><?php 
 //$arrcheckedits[$obj->task_id] = $obj->date_created;

$k = 0;


foreach($checkedit2 as $obj){
    if(date('Ymd',strtotime($obj->date_created)-7.5*3600) == $ymdinviteaccept && $obj->user_id == 30259){
        $k++;
    }
}
echo number_format($k); 


?></td>
<?php } ?>
</tr>
<tr>
<td class="tdfirst"><b>Auto invite (%)</b></td>
<?php for ($i= 0 ; $i < 30 ; $i++){ ?>
<td><?php if($t[date('Y-m-d',  strtotime('-'.$i.' day'))] > 0){ 
    if((( $autoinvitecheck[date('Y-m-d',  strtotime('-'.$i.' day'))]) / $t[date('Y-m-d',  strtotime('-'.$i.' day'))])*100 > 100){
        echo '100%';
    }else{
    echo number_format ( (( $autoinvitecheck[date('Y-m-d',  strtotime('-'.$i.' day'))]) / $t[date('Y-m-d',  strtotime('-'.$i.' day'))])*100 , 0 ).'%' ; } 
    } ?></td>
<?php } ?>
</tr>
</tbody>
</table>
<div class="pager"> 
    <img src="https://mottie.github.io/tablesorter/addons/pager/icons/first.png" class="first"/> 
    <img src="https://mottie.github.io/tablesorter/addons/pager/icons/prev.png" class="prev"/> 
    <span class="pagedisplay"></span> <!-- this can be any element, including an input --> 
    <img src="https://mottie.github.io/tablesorter/addons/pager/icons/next.png" class="next"/> 
    <img src="https://mottie.github.io/tablesorter/addons/pager/icons/last.png" class="last"/> 
    <select class="pagesize" title="Select page size"> 
        <option selected="selected" value="20">10</option> 
        <option value="30">30</option> 
        <option value="50">50</option> 
        <option value="all">All</option> 
    </select>
    <select class="gotoPage" title="Select page number"></select>
</div>
</div>

<?php 
if($showchart){
?>
<script>
$(document).ready(function() {
    var height1 = jQuery(window).height();
    var height = screen.height;
    if(window.parent){
        height = jQuery(window).height();
        //height = window.parent.jQuery("#frm4").attr('height');        
    }
    var hiframe = height - 30;
    console.log('windowheight='+height1+'|height='+height+'|hiframe='+hiframe);
    $('.divreport').css('height', hiframe+'px');
})
 jQuery( function() {
      jQuery( '.sajkdljas' ).tooltip();
    } );
</script>
<style>
 html, body{ overflow:hidden; height: 100%;}
.divreport{
    overflow-x:hidden; 
    overflow-y:auto;
    width:100%; 
    height:500px;
}</style>
<?php
} ?>
<style>
.tablesorter thead {

    position: sticky;
    top: 0px;
    z-index: 1000000;
}
.tablesorter-default .header, .tablesorter-default .tablesorter-header {   
    background-color: #e9e9e9;
}

.newbox {
  float: left;
  height: 20px;
  width: 20px;
  margin-bottom: 15px;
  border: 1px solid black;
  clear: both;
  margin-right: 5px;
}

.red {
  background-color: red;
}

.green {
  background-color: green;
}

.blue {
  background-color: blue;
}
</style>