<?php

// DISPLAY ALL ERRORS
error_reporting(E_ALL);
ini_set('display_errors',0);


function recurse_copy($src,$dst) { 
    $dir = opendir($src); 
    @mkdir($dst); 
    while(false !== ( $file = readdir($dir)) ) { 
        if (( $file != '.' ) && ( $file != '..' )) { 
            if ( is_dir($src . '/' . $file) ) { 
                recurse_copy($src . '/' . $file,$dst . '/' . $file); 
            } 
            else { 
                copy($src . '/' . $file,$dst . '/' . $file); 
            } 
        } 
    } 
    closedir($dir); 
} 

// SEARCH HELPER FUNCTION
function contains(array $array, $string) {
    $count = 0;
    foreach ($array as $value) {
        if (false !== stripos($string, $value)) {
            ++$count;
        }
    }
    return $count == count((array)$array);
}

// START & CONFIG
ob_start();
require 'setup/config.php';


$LANG =  'cn';
// SET LANGUAGE
if (isset($_GET['lang'])){	
	$_SESSION['HTTP_ACCEPT_LANGUAGE'] = $_GET['lang'];
}
if (isset($_SESSION['HTTP_ACCEPT_LANGUAGE']) and file_exists('lang/' . $_SESSION['HTTP_ACCEPT_LANGUAGE'] . '.php')) {	
	if((@include 'lang/' . $_SESSION['HTTP_ACCEPT_LANGUAGE'] . '.php') === false){
		echo 'Caught exception: Translate file is wrong';
	}else{
		@include_once('lang/' . $_SESSION['HTTP_ACCEPT_LANGUAGE'] . '.php');
	}
} else {
	if((@include 'lang/' . $LANG . '.php') === false){
		echo 'Caught exception: Translate file is wrong';
	}else{
		@include_once('lang/' . $LANG . '.php');
	}
}


// INI VARs
$found = 0;                     // MARKER HOW MANY HITS FOUND A SEARCH
$done = 0;                     // MARKER HOW MANY ENTRYs ARE DONE
$msg = '';                    // TOAST MESSAGE
$TYPE = 'DocumentsLocal';
$file = 'data/' . $TYPE . '.json'; // DATA FILE NAME

// LOGIN CHECK
session_start();
$login = check_current_user_login($ARR_USERS, $SALT);
$currentuser = $login['user'];

//var_dump($login);
if ($login['status'] == 200) {
  if($currentuser->gm  != '1'){
		header('location: index.php');
        exit;
  } 
} else {
    header('location: login.php');
    exit;
}
/* $sessionname = md5($USER . $SALT);
  if (!@$_SESSION[$sessionname]) {
  header('location: login.php');
  exit;
  } */
$tabs = json_decode(file_get_contents('data/TabsLocal.json'));
$user = json_decode(file_get_contents('data/User.json'));
$tabdocfull = $tabdoc = json_decode(file_get_contents('data/TabDocLocal.json'));
$tabfull = $tabs;

// DELETE ENTRY IF DEL LINK IS CLICKED
if (@$_GET['delete_id'] != '') {
    $data = json_decode(file_get_contents($file), true);
    foreach ( $data as $key => $r  ){
        if($r['id'] == @$_GET['delete_id']){
            unset($data[$key]);
        }
    }
    $convert_array_to_json = array_values($data);
    $write_json = json_encode($convert_array_to_json);
    file_put_contents($file, $write_json);
    header('location: local.php?msg=' . $i18n['Entry successfully deleted.']);
}



         
// ADD NEW TAB
if($_POST['adddoctotab'] == '1'){
    foreach ($tabdocfull as $vt => $tb) {
        if($tb->iddoc == $_POST['iddoc']){
             unset($tabdocfull[$vt]);
        }
    }
    $tabdocfull = array_values($tabdocfull);
    if ($_POST['idtab']){
    $tabdocfull[] = array(
        'iddoc' => $_POST['iddoc'],      
        'idtab' => $_POST['idtab'],
    );    
    }
    file_put_contents('data/TabDocLocal.json', json_encode($tabdocfull));
    header('location: local.php?msg=' . $i18n['Tab Imported']);
}

// ADD NEW TAB
if($_POST['tab'] != ''){
    $dataFile = file_get_contents('data/TabsLocal.json');
    $data = json_decode($dataFile,true);
    $ta['id'] = time();
    $ta['name'] = $_POST['tab'];
    $ta['iduser'] = $currentuser->id;
    $data[] = $ta;
    $data = array_values($data);
    $data = json_encode($data);
    file_put_contents('data/TabsLocal.json',$data);
    header('location: local.php?msg=' . $i18n['Tab Created']);
}
//DELETE TAB
$delIdTab = $_GET['delete_tab'];

if($delIdTab){
    $tabfull = (array) $tabfull;
    $tabdocfull = (array) $tabdocfull;
    foreach ($tabfull as $key => $t) {       
        if($t->id == $delIdTab){
            unset($tabfull[$key]);
        }
    }
    foreach ($tabdocfull as $vt => $tb) {
        if($tb->idtab == $delIdTab){
            unset($tabdocfull[$vt]);
        }
    }
    file_put_contents('data/TabsLocal.json',json_encode($tabfull));
    file_put_contents('data/TabDocLocal.json',json_encode($tabdocfull));
    header('location: local.php?msg=' . $i18n['Entry successfully deleted.']);
}

if($_POST['tabname'] != '' && $_POST['id_tabname'] !=''){
    $dataFile = file_get_contents('data/TabsLocal.json');
    $data = json_decode($dataFile,true);
    for($i=0;$i<count((array)$data);$i++){
        if($data[$i]['id'] == $_POST['id_tabname']){
            $data[$i]['name'] = $_POST['tabname'];
            break;
        }
    }
    $data = json_encode($data);
    file_put_contents('data/TabsLocal.json',$data);
    header('location: local.php');
}


// SAVE NEW ENTRY IF FORM POSTED
if (isset($_POST['status'])) {
    if ($_POST['status'] == "") {
        $_POST['status'] = 'YES';
    }
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' and @ $_POST['date'] != '' and @ $_POST['nonumber'] != '' and @ $_POST['name'] != '' and @ $_POST['workno'] != '' and @ $_POST['receivable'] != '' and @ $_POST['amount'] != '' and @ $_POST['status'] != '') {
    $receivable = $amount = 0;
    if (isset($_POST['receivable'])) {
        $receivable = $_POST['receivable'];
    }
    if (isset($_POST['amount'])) {
        $amount = $_POST['amount'];
    }
    if (isset($_POST['profit'])) {
        $profit = $_POST['profit'];
    }
    //$profit = $receivable - $amount;    
    //var_dump($_POST);die();
	$id = time();
    $formdata = array(
        'id' => $id
        , 'nonumber' => $_POST['nonumber']
        , 'name' => $_POST['name']
        , 'workno' => $_POST['workno']
        , 'receivable' => $receivable
        , 'amount' => $amount
        , 'profit' => $profit
        , 'status' => $_POST['status']
        , 'date' => $_POST['date']
		, 'location' => $_POST['location'],
    );
	
	if ($_POST['tabs'] == 'auto'){		
			// find work no
			$year = substr($_POST['workno'],0,2);
			$month = substr($_POST['workno'],2,2);
			
			foreach ($tabs as $omg ){
				if ( $omg->name == $month.'_20'.$year ) {
						$idtabd =  $omg->id;
				}
			}
			$tabdocfull[] = array(
				'iddoc' => $id,      
				'idtab' => $idtabd,
			);    
			file_put_contents('data/TabDocLocal.json', json_encode($tabdocfull));
	}else{
			//$tabdocfull = array_values($tabdocfull);
			$tabdocfull[] = array(
				'iddoc' => $id,      
				'idtab' => $_POST['tabs'],
			);    
			file_put_contents('data/TabDocLocal.json', json_encode($tabdocfull));
	}
	
    $arr_data = array();
    if (file_exists($file)) {
        $jsondata = file_get_contents($file);
        $arr_data = json_decode($jsondata, true);
    }
    $arr_data[] = $formdata;
    $jsondata = json_encode($arr_data);
    if (file_put_contents($file, $jsondata)) {
        $msg = $i18n['Data successfully saved!'];
    } else {
        $msg = $i18n['ERROR &mdash; Data not saved!'];
    }
    header('location: local.php?msg=' . $msg);
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $_GET['msg'] = $i18n['All fields are required!'];
}

// CREATE DATA FILE IF NOT EXISTS
if (!is_file($file)) {
    file_put_contents($file, '');
}



// READ DATA
$newdata = array();
$data = json_decode(file_get_contents($file), true); 
foreach ($data as  $key => $ln){
			$ln['key'] = $key;
			if($ln['workno'] == 'TAI'){
				$newdata[$key] = $ln;
			}else{
				$newdata[$ln['workno']] = $ln;

			}
			
		
}
ksort($newdata);
$data = $newdata;
$newdata = array();
foreach ($data as   $ln){
			 
	$newdata[$ln['key']] = $ln;
		
}
$data = $newdata;
$newdata = array();

//echo '<pre>';
//print_r($data);
//die;


if ($_GET['location'] != ''){
	foreach ($data as $key => $ln){
		if ( $ln['location'] == $_GET['location'] ){
			$newdata[$key] = $ln;
		}
	}
	$data = $newdata;
}


# var_dump( $data );
// HEADER
ob_end_flush();
include 'tpl/header.php';


// FORM FOR NEW ENTRY
if (@$_GET['q'] == '') {

    ?>
	
    <div class="badge grey lighten-3 hoverable show-table" style="padding:0.5em">
	
        <h3 class="grey-text text-darken-2"><?php echo $i18n['New Issue']; ?></h3>
        <form method="POST">
            <div class="row">
                <div class="input-field col s3">
                    <input 
                        value="<?php echo @$_POST['nonumber']; ?>" 
                        id="nonumber" 
                        name="nonumber" 
                        type="text" 
                        class="validate" 
                        maxlength="32" 
                        data-length="32" 
                        required="required"/>
                    <label for="nonumber">序号</label>
                    <span class="helper-text" data-error="Error" data-success="OK">                        
                        The No. enter here.                    
                    </span>
                </div>
			
                <div class="input-field col s3">
                    <input 
                        value="<?php @$_POST['date']; ?>" 
                        id="date" 
                        name="date" 
                        type="text" 
                        class="validate" 
                        maxlength="32" 
                        data-length="32" 
                        required="required"/>
                    <label for="date">到港日期</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                       
                        The No. Container enter here                    
                    </span>
                </div>
                <div class="input-field col s3">
                    <input 
                        value="<?php echo @$_POST['name']; ?>" 
                        id="name" 
                        name="name" 
                        type="text" 
                        class="validate" 
                        maxlength="32" 
                        data-length="32" 
                        required="required"/>
                    <label for="name">Name</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        <?php echo $i18n['Quick summary or projectname.']; ?>
                    </span>
                </div>
                <div class="input-field col s3">
                    <input 
                        value="<?php echo @$_POST['workno']; ?>" 
                        id="workno" 
                        name="workno" 
                        type="text" 
                        class="validate" 
                        maxlength="32" 
                        data-length="32" 
                        required="required"/>
                    <label for="workno">Work No.</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        The Work No. enter here.                    
                    </span>
                </div>
            </div>
            <div class="row">
                <div class="input-field col s2">
                    <input 
                        value="<?php echo @$_POST['receivable']; ?>" 
                        id="receivable" 
                        name="receivable" 
                        type="text" 
                        class="validate" 
                        maxlength="32" 
                        data-length="32" 
                        required="required"/>
                    <label for="receivable">Receivable</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        The Receivable enter here.                    
                    </span>
                </div>
                <div class="input-field col s2">
                    <input 
                        value="<?php echo @$_POST['amount']; ?>" 
                        id="amount" 
                        name="amount" 
                        type="text" 
                        class="validate" 
                        maxlength="32" 
                        data-length="32" 
                        required="required"/>
                    <label for="amount">Payment</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        
                        The Payment enter here.                    
                    </span>
                </div>
                <div class="input-field col s2">
                    <input 
                        value="<?php echo @$_POST['profit']; ?>" 
                        id="profit" 
                        name="profit" 
                        type="text" 
                        class="validate" 
                        maxlength="32" 
                        data-length="32" 
                        required="required"
                        readonly="true" />
                    <label for="profit">Profit</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                       
                        Auto Subtract Data                    
                    </span>
                </div>
                <div class="input-field col s2" style="display:none;">
                    <select name="status" id="status">
                        <?php if (@$_POST['status'] != '') echo '<option>' . $_POST['status'] . '</option>'; ?>
                        <option value=""><?php echo $i18n['Choose']; ?></option>
                        <?php //require 'types/' . $TYPE . '/status.txt'; ?>
                    </select>
                    <label for="status"><?php echo $i18n['Label']; ?></label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        <?php echo $i18n['Select one label.']; ?>
                    </span>
                </div>
                  	
                <div class="input-field col s2">
                    <select name="tabs" id="tabs">
						<option value="auto"  >Auto Fill</option>
                        <?php 
                            foreach($tabs as $tab){
                                ?> 
                                    <option value="<?php echo $tab->id ?>"><?php echo $tab->name ?></option>';
                                <?php
                            }
                        ?>
                    </select>
                    <label for="tab">选择</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Select custom tab or auto fill via Work No.
                    </span>
                </div>
				
				<div class="input-field col s2">
                    <select name="location" id="Location">
						<option value="vn"  >VietNam</option>
						<option value="tha"  >ThaiLand</option>
						<option value="cn"  >China</option>
                       
                    </select>
                    <label for="Location">Location</label>
                    <span class="helper-text" data-error="Error" data-success="OK">
                        Select location of orders
                    </span>
                </div>
                
                <div class="input-field col s4">
                     <div class="input-field col s8 ">
                    <button class="colortoptran btn waves-effect waves-light" style="float: right;" type="submit" name="action">
                        <?php echo $i18n['Save New Issue']; ?>
                        <i class="material-icons right">add_circle_outline</i>
                    </button>
                          </div>
                    <div class="input-field col s4  ">
                        <button type="button" class="btn waves-effect waves-light toggle" style="background: #999999;" >Close</button>
                    </div>
                </div>
            </div>
        </form>
    </div>
    <br>
     <ul style="display:flex;background:#eeeeee;align-items:center;height:unset;" class="tabs">
        
        <?php if($currentuser->role != 'Operator') { ?>
        <li data-tab="tab-0" class="tab-link">All</li>
        <?php } ?>
        <?php
              foreach($tabs as $tab){
                  if ($currentuser->role != 'Manager' && $currentuser->role != 'Finance'){
                       echo '<li data-tab="tab-'.$tab->id.'" data-id="'.$tab->id.'" class="tab-link">'.$tab->name.'</li>';
                  }else{
                        foreach ($user as $us){
                            if ($us->id == $tab->iduser) {
                                $name = $us->name;                                break;
                            }
                        }
                       echo '<li data-tab="tab-'.$tab->id.'" data-id="'.$tab->id.'"  class="tab-link">'.$tab->name.'</li>';
                  }
                  
                        echo '<form method="post" style="position:relative">
                            <input type="hidden" name="id_tabname" value="'.$tab->id.'">
                            <input required onblur="if( $(this).val() == \'Tab 1\' ){$(this).val(\'\');}" type="text" value="'.$tab->name.'" name="tabname" class="tab-'.$tab->id.'" style="width: 100px;    margin-right: 50px;display:none;" /> 
                        <button class="tab-'.$tab->id.'" id="tabnameSave"> <i class="material-icons">save</i></button>
                        </form>
                        <a href=?delete_tab='.$tab->id.' class="material-icons close tab-'.$tab->id.'">close</a>' ;
                 
                }   
        ?>
       
                <button data-target="addNewTab" class="btn modal-trigger" style="margin-left:10px;"><i class="material-icons right" style="line-height:1.5;font-size: 25px;margin: 0;padding: 0;">add_circle_outline</i></button>
             
        </ul>
    <?php
// SEARCH HEADER
}else {
    echo '<div class="badge grey lighten-3 hoverable" style="padding:1em">
        <h3 class="grey-text text-darken-2">' . $i18n['Search for'] . ' [&nbsp;' .
    htmlentities($_GET['q']) . '&nbsp;]</h3></div><br>';
    $searchArray = explode(' ', $_GET['q']);
}


// DATA TABLE
if (!empty($data) && $currentuser->role == 'Manager' ) {

    // TABLE HEADER
  $table = '
  <table  class="striped responsive-table hoverable tablesorter tab-content"  id="tab-0" >
  <thead>
  <tr>
  <th>序号</th>
  <th>到港日期</th>
  <th>Name</th>
  <th style="width:15%;" >Work No.</th>
  <th style="width:5%;" >Tab</th>
  <th>Receivable</th>
  <th>Payment</th>
  <th>Profit</th>';
  $table .= '<th style="text-align:center">Action</th>';
  $table .= '</tr>
  </thead>
  <tbody>';

    // LOOP EACH ENTRY
    $total_receivable = $total_amount = $total_profit = 0;
    $countNo = 0;
    foreach ($data as $key => $values) {        
        //var_dump($values);
        // CHECK SEARCH
        //$values['profit'] = $values['receivable'] - $values['amount'];
        $dataLine = $values['nonumber'] . $values['date'] . ' ' . $values['name'] . ' ' . $values['workno'] . ' ' . $values['receivable'] . ' ' . $values['amount'] . ' ' . $values['profit'] . ' ' . $values['status'];
        if (@$_GET['q'] != '' AND contains($searchArray, $dataLine) != count((array)$searchArray)) {
            continue;
        } else {
            $found = 1;
        }
        if(trim($values['date']) != ""){
            $nocontent = explode('*', trim($values['date']));
            $var_name1 = $nocontent[0];
            if (is_numeric($var_name1))
            {
                $countNo += (float)$var_name1;
            }
        }
        
        // SET TABLE LINE
        $css = '';
        //require 'types/' . $TYPE . '/status.php';
        $toast = 'M.toast({html: "<span>' . $values['name'] . '</span>' .
                '<a href=?delete_id=' . $values['id'] . ' class=toast-action>' .
                $i18n['DELETE'] . '</a> &nbsp; &nbsp;"});';
        $table .= '<tr><td  style="padding-left:20px">' . ++$kfgn .
                '</td><td class="cjndljnl" data-id="'.$values['id'].'" style="padding-left:20px">' . $values['date'];

        // CHECK IF DATE IS REACHED AND ENTRY IS NOT DONE OR Ready
        if ($values['date'] <= date($DATE) AND $values['status'] != 'DONE' AND $values['status'] != 'Ready') {
            /* $table .= '<span style="margin-left:10px;font-size:1rem;min-width:22px;padding:2px"' .
              ' class="new badge black pulse" data-badge-caption=""><i' .
              ' class="material-icons tiny tooltipped" data-position="top"' .
              ' data-tooltip="' . $i18n['Date reached!'] . '">update</i></span>'; */
        }

        // ACTION BUTTONS (DEL & EDIT)
        /*$receivable = str_replace(array(',', '.', ' '), array('', '', ''), $values['receivable']);
        $numamount = str_replace(array(',', '.', ' '), array('', '', ''), $values['amount']);
        $profit = str_replace(array(',', '.', ' '), array('', '', ''), $values['profit']);*/
        
        $receivable = str_replace(array(','), array(''), trim($values['receivable'])); 
        $numamount = str_replace(array(','), array(''), trim($values['amount']));
        $profit = str_replace(array(','), array(''), trim( $values['profit']));
        $total_receivable += (float)$receivable;
        $total_amount += (float)$numamount;
        $total_profit += (float)$profit;
        //number_format((float)$receivable, 0)
        
        $tabname = '';
        foreach ($tabdocfull as $r){
            if ( $values['id'] == $r->iddoc  ) {
                foreach($tabs as $tab){  
                    if( $tab->id == $r->idtab ){
                        $tabname = $tab->name;
                    }
                }
            }
        }
        
        $table .= '</td><td style="padding-left:20px">' . mb_strimwidth($values['name'], 0, 20, '...') .
                '</td><td style="padding-left:20px">' . $values['workno'] .
                '</td><td style="padding-left:20px">' . $tabname .
                '</td><td style="padding-left:20px;">' . trim($values['receivable']) .
                '</td><td style="padding-left:20px;">' . trim($values['amount']) .
                '</td><td style="padding-left:20px;">' . trim($values['profit']) .
                '</td>';
        if ($currentuser->role == 'Manager') {
            $table .= '<td style="text-align:center"><a class="tooltipped" data-position="top" ' .
                    'data-tooltip="' . $i18n['Click alert link for delete!'] . '" ' .
                    'href="#" onclick=\'' . $toast . '\'><i class="red-text text-darken-4 small ' .
                    'material-icons">delete_forever</i></a> ';
            $table .= '<a class="tooltipped" ' .
                    'data-position="top" data-tooltip="' . $i18n['EDIT'] . '" ' .
                    'href="edit.php?id=' . $key . '"><i class="grey-text small ' .
                    'material-icons">mode_edit</i></a></td>';
        }
        $table .= '</tr>';

        // CALC FOR PROGRESS BAR   
        if ($values['status'] == 'DONE' OR $values['status'] == 'Ready') {
            $done++;
        }

        // END LOOP
		$alltab++;
    }
    if (count((array)$data) > 0) {
       
        $table .= '<tr class="tr_total"><td style="padding-left:20px;" >'.$alltab.'</td><td style="padding-left:20px;">'.number_format((float)$countNo, 0, '.', ',').'</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
        if ($currentuser->role == 'Manager') {
            $table .= '<td style="padding-left:20px;">' . number_format((float)$total_receivable, 2, '.', ',') . '</td>';
            $table .= '<td style="padding-left:20px;">' . number_format((float)$total_amount, 2, '.', ',') . '</td>';
            $table .= '<td style="padding-left:20px;">' . number_format((float)$total_profit, 2, '.', ',') . '</td>';
            $table .='<td>&nbsp;</td>';
        }else{
            $table .= '<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
        }
        $table .= '</tr>';
    }
 

    // SEARCH FOUND NO DATA
    if ($found == 0) {
      //  echo '<tr><td colspan="5"><h3 class="center grey-text text-darken-2">';
      //  echo $i18n['Nothing Found!'] . '</h3></td></tr>';
    } else {
        // ECHO TABLE
        echo $table . '</tbody></table>';
    }

// ENDIF no data
}

foreach($tabs as $tab){
$numtab = 0 ;	
if (!empty($data)  ) {
 
    // TABLE HEADER
  if ($currentuser->role != 'Manager' && $kk++ == 0){
      $current= 'current';
  }else{
      $current= '';
  }  
    
  $table = '
  <table class="striped responsive-table hoverable tablesorter tab-content '.$current.' "  id="tab-'.$tab->id.'"  >
  <thead>
  <tr>
  <th>' . $i18n['NoNumber'] . '</th>
  <th>' . $i18n['Date'] . '</th>
  <th>' . $i18n['Name'] . '</th>
  <th>' . $i18n['WorkNo'] . '</th>
  <th>' . $i18n['Receivable'] . '</th>
  <th>' . $i18n['Amount'] . '</th>
  <th>' . $i18n['Profit'] . '</th>';
 
        $table .= '<th style="text-align:center">' . $i18n['Action'] . '</th>';
  
  $table .= '</tr>
  </thead>
  <tbody>';

    // LOOP EACH ENTRY
    $total_receivable = $total_amount = $total_profit = 0;
    $countNo = 0;
    foreach ($data as $key => $values) {       
        $appprove = 0;
        foreach ($tabdocfull as $r){
            if ( $values['id'] == $r->iddoc && $tab->id == $r->idtab ) {
                $appprove = 1;
            }
        }
        if ($appprove == 0){
             continue;
        }
         
         
         $numtab++;
         
         
        //var_dump($values);
        // CHECK SEARCH
        //$values['profit'] = $values['receivable'] - $values['amount'];
        $dataLine = $values['nonumber'] . $values['date'] . ' ' . $values['name'] . ' ' . $values['workno'] . ' ' . $values['receivable'] . ' ' . $values['amount'] . ' ' . $values['profit'] . ' ' . $values['status'];
        if (@$_GET['q'] != '' AND contains($searchArray, $dataLine) != count((array)$searchArray)) {
            continue;
        } else {
            $found = 1;
        }
        if(trim($values['date']) != ""){
            $nocontent = explode('*', trim($values['date']));
            $var_name1 = $nocontent[0];
            if (is_numeric($var_name1))
            {
                $countNo += (float)$var_name1;
            }
        }
        
        // SET TABLE LINE
        $css = '';
        //require 'types/' . $TYPE . '/status.php';
        $toast = 'M.toast({html: "<span>' . $values['name'] . '</span>' .
                '<a href=?delete_id=' . $values['id']  . ' class=toast-action>' .
                $i18n['DELETE'] . '</a> &nbsp; &nbsp;"});';
        $table .= '<tr><td  style="padding-left:20px">' .$numtab .
                '</td><td class="cjndljnl" data-id="'.$values['id'].'" style="padding-left:20px">' . $values['date'];

        // CHECK IF DATE IS REACHED AND ENTRY IS NOT DONE OR Ready
        if ($values['date'] <= date($DATE) AND $values['status'] != 'DONE' AND $values['status'] != 'Ready') {
            /* $table .= '<span style="margin-left:10px;font-size:1rem;min-width:22px;padding:2px"' .
              ' class="new badge black pulse" data-badge-caption=""><i' .
              ' class="material-icons tiny tooltipped" data-position="top"' .
              ' data-tooltip="' . $i18n['Date reached!'] . '">update</i></span>'; */
        }

        // ACTION BUTTONS (DEL & EDIT)
        /*$receivable = str_replace(array(',', '.', ' '), array('', '', ''), $values['receivable']);
        $numamount = str_replace(array(',', '.', ' '), array('', '', ''), $values['amount']);
        $profit = str_replace(array(',', '.', ' '), array('', '', ''), $values['profit']);*/
        
        $receivable = str_replace(array(','), array(''), trim($values['receivable'])); 
        $numamount = str_replace(array(','), array(''), trim($values['amount']));
        $profit = str_replace(array(','), array(''), trim( $values['profit']));
        $total_receivable += (float)$receivable;
        $total_amount += (float)$numamount;
        $total_profit += (float)$profit;
        //number_format((float)$receivable, 0)
        $table .= '</td><td style="padding-left:20px">' . mb_strimwidth($values['name'], 0, 20, '...') .
                '</td><td style="padding-left:20px">' . $values['workno'] .
                '</td><td style="padding-left:20px;">' . trim($values['receivable']) .
                '</td><td style="padding-left:20px;">' . trim($values['amount']) .
                '</td><td style="padding-left:20px;">' . trim($values['profit']) .
                '</td>';
        if ($currentuser->role == 'Manager') {
            $table .= '<td style="text-align:center"><a class="tooltipped" data-position="top" ' .
                    'data-tooltip="' . $i18n['Click alert link for delete!'] . '" ' .
                    'href="#" onclick=\'' . $toast . '\'><i class="red-text text-darken-4 small ' .
                    'material-icons">delete_forever</i></a> ';
            $table .= '<a class="tooltipped" ' .
                    'data-position="top" data-tooltip="' . $i18n['EDIT'] . '" ' .
                    'href="edit.php?id=' . $key . '"><i class="grey-text small ' .
                    'material-icons">mode_edit</i></a></td>';
        }else{
              $timeleft =   300 - time() + $values['id'];
                    if($currentuser->role == 'Operator' && $timeleft > 0){
                        $table .= '<td style="text-align:center"><a class="tooltipped" ' .
                                    'data-position="top" data-tooltip="' . $i18n['EDIT'] . '" ' .
                                    'href="edit.php?id=' .$key . '"><i class="grey-text small ' .
                                    'material-icons">mode_edit</i></a> (<span style="font-weight:bold;display: inline;" id="time'.++$pgh.'" ></span>)';
                       $table .= ' <script> $(document).ready(function(){
                              var fiveMinutes = '.$timeleft.',
                              display = $("#time'.$pgh.'");
                              startTimer(fiveMinutes, display);
                          });</script> </td>';
                    }
            
            
        }
        $table .= '</tr>';

        // CALC FOR PROGRESS BAR   
        if ($values['status'] == 'DONE' OR $values['status'] == 'Ready') {
            $done++;
        }

        // END LOOP
		
    }
    if (count((array)$data) > 0) {
       
        $table .= '<tr class="tr_total"><td style="padding-left:20px;" >'.$numtab.'</td><td style="padding-left:20px;">'.number_format((float)$countNo, 0, '.', ',').'</td><td>&nbsp;</td><td>&nbsp;</td>';
        if ($currentuser->role == 'Manager') {
            $table .= '<td style="padding-left:20px;">' . number_format((float)$total_receivable, 2, '.', ',') . '</td>';
            $table .= '<td style="padding-left:20px;">' . number_format((float)$total_amount, 2, '.', ',') . '</td>';
            $table .= '<td style="padding-left:20px;">' . number_format((float)$total_profit, 2, '.', ',') . '</td>';
            $table .='<td>&nbsp;</td>';
        }else{
            $table .= '<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
        }
        $table .= '</tr>';
    }
 

    // SEARCH FOUND NO DATA
    if ($found == 0) {
     //   echo '<tr><td colspan="5"><h3 class="center grey-text text-darken-2">';
     //   echo $i18n['Nothing Found!'] . '</h3></td></tr>';
    } else {
        // ECHO TABLE
        echo $table . '</tbody></table>';
    }

// ENDIF no data
}
}

?>
        <div id="addNewTab" class="modal modal-fixed">
        <div class="modal-content">
            <h4>Add New Tabs</h4>
            <form method="post">
                <div class="input-field col s12">
                    <input id="tab" type="text" class="validate"  name="tab" required>
                    <label for="tab">Add Tab</label>
                </div>
                <div class="input-field col s2">
                    <button class="colortoptran btn waves-effect waves-light" style="display:block;margin:auto;right:0;left: 0;" type="submit" name="action">
                        Save Tabs
                    </button>
                </div>
            </form>
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
     <script type="text/javascript">
       $(function() {
           
           var id = '0';
           
    $(".cjndljnl").draggable({
        revert:  function(dropped) {
             var $draggable = $(this),
                 hasBeenDroppedBefore = $draggable.data('hasBeenDropped'),
                 wasJustDropped = dropped && dropped[0].id == "droppable";
             if(wasJustDropped) {
                 // don't revert, it's in the droppable
                 return false;
             } else {
                 if (hasBeenDroppedBefore) {
                     // don't rely on the built in revert, do it yourself
                     $draggable.animate({ top: 0, left: 0 }, 'slow');
                     return false;
                 } else {
                     // just let the built in revert work, although really, you could animate to 0,0 here as well
                     return true;
                 }
             }
        }, 
        start: function(event, ui) {
            id = $(this).attr('data-id');
              $(this).height(20).width(20);
        },
        stop: function() {
            $(this).removeAttr('style');
            $(this).css('padding-left','20px');
            $(this).css('position','relative');
        },
        cursor: "crosshair",
        
        
    });

    $(".tab-link").droppable({
        activeClass: 'ui-state-hover',
        hoverClass: 'ui-state-active',
        drop: function(event, ui) {
           // $(this).addClass('ui-state-highlight').find('p').html('Dropped!');
           // $(ui.draggable).data('hasBeenDropped', true);
           $("#idtab").val($(this).attr('data-id'));
           $("#iddoc").val(id);
           $("#adddoctotab").submit();
        }
    });



   
        $('.tab-link').each(function(){
            if ($('#'+$(this).attr('data-tab')).find('tbody > tr').length > 1){
             $(this).append(' ('+($('#'+$(this).attr('data-tab')).find('tbody > tr').length - 1 )+')');
            }
        });

    
    
    $('#tab-0').addClass('current');
    $('.tab-link:first-child').addClass('current');
    
    
});
    </script>
    
    
    <form method="post" style="display:none;" id="adddoctotab" >
        <input id="idtab" type="hidden"  name="idtab" value="" >
        <input id="iddoc" type="hidden"  name="iddoc" value="" >
        <input id="task" type="hidden"  name="adddoctotab" value="1" >
    </form>
    
    
<?php    
// FOOTER
include 'tpl/footer.php';
