<?php
require_once('../config.php');
$user_id = $_SESSION['user_id'];
$emp_id = $_SESSION['emp_id'];
$user_role = $_SESSION['user_role'];


// SQL server connection information
// $sql_details = $search_db;
$sql_details = $search_db;

if(!isset($_GET['isset'])){
    exit();
}


$extra_where = $_GET['extra_where'];


$table = <<<EOT
(
    SELECT 
        ROW_NUMBER() OVER(ORDER BY u.name asc) row_num,
        u.employee_id, 
        u.name, 
        u.working_status_date,
        u.leader,
        d.work_date, 
        d.work 
    FROM users as u 
    LEFT JOIN dailyWork as d on u.employee_id=d.employee_id  and $extra_where
) join_table
EOT;



$whereResult = null;
$whereAll = null;
if (isset($_GET['where_condition']) && !empty($_GET['where_condition'])) {
    $whereAll = $_GET['where_condition'];
}

// Table's primary key
$primaryKey = 'row_num';

// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
    array('db' => 'row_num', 'dt' => 'row_num'),
    array('db' => 'employee_id', 'dt' => 'employee_id'),
    array('db' => 'name', 'dt' => 'name'),
    array(
        'db' => 'work_date', 
        'dt' => 'work_date',
        'formatter'=>function($cell, $row){
            $returnValue = $row['work_date'];
            if(empty($row['work_date'])){
                $returnValue = str_replace("'","",explode(' and ',$GLOBALS['extra_where'])[1]);
            }
            return $returnValue;
        }
    ),
    array(
        'db' => 'work', 
        'dt' => 'work',
        'formatter' => function($cell, $row){
            $returnValue = '<div style="max-width:400px;">';
            if (!empty($row['work'])) {
                $json_data = json_decode($row['work'], true);
                foreach ($json_data as $key => $data) {
                    $returnValue .= '<strong class="text-danger">' . $data['time'] . '- </strong>' . $data['text'] . '<br>';
                }
            } else {
                $returnValue .= '<div class="text-danger">No Entry</div>';
            }
            $returnValue .= '</div>';
            return $returnValue;
        }
    ),
);


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP
 * server-side, there is no need to edit below this line.
 */
require('ssp.class.php');

echo json_encode(
    // SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns)
    SSP::complex($_GET, $sql_details, $table, $primaryKey, $columns, $whereResult, $whereAll)
);
