<?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();
}


// use in => all_users_get.php, myProfile.php, exportEmployees.php, payslip.php
$table = <<<EOT
(
    SELECT
        ROW_NUMBER() OVER (ORDER BY t1.id DESC) AS row_num,
        t1.*,
        t2.name AS l_name,
        t3.department_name,
        t4.designation_name
    FROM (
        SELECT 
            p1.*,
            (CASE
                WHEN COALESCE(p1.working_status,'')<>'' THEN p1.working_status
                ELSE 'Active'
            END) AS working_status_final,
            (CASE
            WHEN COALESCE(p2.promote_to,'')<>'' THEN p2.promote_to
            ELSE p1.designation
            END) AS new_designation
        FROM users p1
        LEFT JOIN (
            SELECT
                *
            FROM (
                SELECT 
                    id,
                    employee_id, 
                    promote_to, 
                    applicable_from, 
                    (CASE 
                    WHEN COALESCE(applicable_to,'')='' THEN DATE_FORMAT(CURRENT_DATE, '%Y-%m')
                    ELSE applicable_to
                    END) as applicable_to 
                FROM promotions
            ) final_promotions
            WHERE (DATE_FORMAT(CURRENT_DATE, '%Y-%m') BETWEEN applicable_from AND applicable_to)
        ) p2 ON p1.employee_id=p2.employee_id
    ) t1
    INNER JOIN users AS t2 ON t1.leader = t2.employee_id
    INNER JOIN departments AS t3 ON t3.id = t1.department
    LEFT JOIN designations AS t4 ON t4.id=t1.new_designation
) 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 = 'id';

// 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' => 'id',
        'dt' => 'id',
        'formatter' => function ($cell, $row) {
            $returnValue = '<input name="r_checked[]" class="checkboxes" value="'.$row['employee_id'].'" type="checkbox" />';
            return $returnValue;
        }
    ),
    array(
        'db' => 'image',
        'dt' => 'image',
        'formatter' => function ($cell, $row) {
            if(!empty($row['image'])){
                $returnValue = '<a href="'.$GLOBALS['cdn_url'].'content/employee/images/'.$row['image'].'" download="'.$row['image'].'"><img src="'.$GLOBALS['cdn_url'].'content/employee/images/'.$row['image'].'" width="60" height="60" class="rounded rounded-circle"><p class="d-none">'.$GLOBALS['cdn_url'].'content/employee/images/'.$row['image'].'</p></a>';
            }else{
                $returnValue = '<img src="'.$GLOBALS['cdn_url'].'content/employee/images/avatar.png" width="60" height="60" class="rounded rounded-circle">';
            }
            return $returnValue;
        }
    ),
    // array('db' => 'row_num', 'dt' => 'row_num'),
    array('db' => 'employee_id', 'dt' => 'employee_id'),

    array(
        'db' => 'name', 
        'dt' => 'name',
        'formatter' => function($cell, $row){
            $returnValue = '<div>
                <p class="mb-0"><strong>Name: </strong>'.$row['name'].'</p>
                <p class="mb-0"><strong>E-mail: </strong>'.$row['email'].'</p>
                <p class="mb-0"><strong>Phone: </strong>'.$row['phone'].'</p>
                <p class="mb-0"><strong>Gender: </strong>'.$row['gender'].'</p>
                <p class="mb-0"><strong>DOB: </strong>'.((!empty($row['dob'])) ? date('d M Y', strtotime($row['dob'])) : '').'</p>
            </div>';
            return $returnValue;
        }
    ),

    array(
        'db' => 'joining_date', 
        'dt' => 'joining_date',
        'formatter' => function($cell, $row){
            $returnValue = '<div>
                <p class="mb-0"><strong>Joining Date: </strong>'.((!empty($row['joining_date'])) ? date('d M Y', strtotime($row['joining_date'])) : '').'</p>
                <p class="mb-0"><strong>Notice Period: </strong>'.$row['notice_period'].' Days</p>
                <p class="mb-0"><strong>Department: </strong>'.$row['department_name'].'</p>
                <p class="mb-0"><strong>Designation: </strong>'.$row['designation_name'].'</p>
                <p class="mb-0"><strong>Role: </strong>';
                if ($row['role'] == 0 && $row['role'] != NULL) {
                    $returnValue .= 'Boss';
                } else if ($row['role'] == 1) {
                    $returnValue .= 'Manager';
                } else if ($row['role'] == 2) {
                    $returnValue .= 'Employee';
                } else {
                }
                $returnValue .= '</p>
                <p class="mb-0"><strong>Leader: </strong>'.$row['l_name'].'</p>
                <p class="mb-0"><strong>Consider As: </strong>'.$row['consider_as'].'</p>
            </div>';
            return $returnValue;
        }
    ),

    array(
        'db' => 'pan_no', 
        'dt' => 'pan_no',
        'formatter' => function($cell, $row){
            $returnValue = '<div>
                <p class="mb-0"><strong>PAN No: </strong>'.$row['pan_no'].'</p>
                <p class="mb-0"><strong>Account No: </strong>'.$row['account_no'].'</p>
                <p class="mb-0"><strong>IFSC Code: </strong>'.$row['ifsc_code'].'</p>
            </div>';
            return $returnValue;
        }
    ),
    array(
        'db' => 'esi_no', 
        'dt' => 'esi_no',
        'formatter' => function($cell, $row){
            $returnValue = '<div>
                <p class="mb-0"><strong>ESIC No: </strong>'.$row['esi_no'].'</p>
            </div>';
            return $returnValue;
        }
    ),
    array(
        'db' => 'uan_no', 
        'dt' => 'uan_no',
        'formatter' => function($cell,$row){
            $returnValue = '<div>
                <p class="mb-0"><strong>EPF No: </strong>'.$row['uan_no'].'</p>
                <p class="mb-0"><strong>EPF Applicable: </strong>'.$row['epf_applicable_status'].'</p>
            </div>';
            return $returnValue;
        }
    ),
    array(
        'db' => 'working_status', 
        'dt' => 'working_status',
        'formatter' => function($cell, $row){
            $returnValue = '<div style="width:200px;">
            <select name="workingStatus" class="form-control form-select mb-1" id="workingStatus'.$row['id'].'">
                <option value="">Select Status</option>
                <option '.(($row['working_status'] == 'Resigned') ? 'selected' : '').' value="Resigned">Resigned</option>
                <option '.(($row['working_status'] == 'Terminated') ? 'selected' : '').' value="Terminated">Terminated</option>
                <option '.(($row['working_status'] == 'Abscond') ? 'selected' : '').' value="Abscond">Abscond</option>
            </select>
            <input type="date" class="form-control mb-1" name="workingStatusDate" id="workingStatusDate'.$row['id'].'" value="'.$row['working_status_date'].'">';
            // if(!empty($row['working_status']) && !empty($row['working_status_date'])){
            //     $returnValue .= '<button class="btn btn-success w-100 btn-padding" disabled>Update</button>';
            // }else{
                $returnValue .= '<button class="btn btn-success w-100 btn-padding" id="statusButton'.$row['id'].'" onclick="workingStatus(\''.$row['id'].'\',\''.$row['name'].'\');">Update</button>';
            // }
            $returnValue .= '</div>';
            
            return $returnValue;
        }
    ),
    array(
        'db' => 'working_status_date', 
        'dt' => 'working_status_date',
        'formatter' => function($cell, $row){
            $returnValue = '<ul>
                <li><strong>Login Status:</strong> '.($row['remember_token']? '<span class="text-success">Logged In</span>': '<span class="text-danger">Logged Out</span>').'</li>
                <li><strong>Last Login:</strong> '.($row['last_login_time']?date('M d, Y - h:i A', strtotime($row['last_login_time'])):'').'</li>
            ';
            if($row['remember_token']){
                $returnValue .= '<li>
                    <a href="javascript:;" onclick="update_login_status(\''.$row['id'].'\',\''.$row['name'].'\');">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#FF0000" class="bi bi-door-closed" viewBox="0 0 16 16">
                            <path d="M3 2a1 1 0 0 1 1-1h8a1 1 0 0 1 1 1v13h1.5a.5.5 0 0 1 0 1h-13a.5.5 0 0 1 0-1H3zm1 13h8V2H4z"/>
                            <path d="M9 9a1 1 0 1 0 2 0 1 1 0 0 0-2 0"/>
                        </svg>
                    </a>        
                </li>';
            }
            $returnValue .= '</ul>';
            return $returnValue;
        }
    ),
 
    array(
        'db' => 'account_no', 
        'dt' => 'account_no',
        'formatter' => function($cell, $row){
            // <a href="javascript:;" class="text-info mr-1" id="time'.$row['id'].'" onclick="employee_time(\''.$row['id'].'\',\''.$row['name'].'\');" title="Set Working time"><i class="uil uil-clock-ten"></i></a>
            $returnValue = '

            <a href="attendance?emp_id='.$row['employee_id'].'" class="mr-1" title="Attendance"><i class="uil uil-briefcase-alt"></i></a>
            <div class="d-inline-block mr-1">
                <a href="javascript:;" onclick="resetPasswordSendMail('.htmlspecialchars(json_encode(array($row['name'], $row['email'], $row['employee_id']))).',\''.$row['id'].'\');" class="text-warning" title="Send Mail"><i class="uil uil-envelope-share" id="addTickSend'.$row['id'].'"></i></a>
            </div>
            <a href="add_users?edit='.$row['id'].'" class="text-success mr-1" title="Edit"><i class="uil uil-edit"></i></a>
            <a href="javascript:;" onclick="_delete_(\''.$row['id'].'\');" class="text-danger" title="Delete"><i class="uil uil-trash-alt"></i></a>
            <a href="javascript:;" onclick="viewEmployeeLifeCycle(\''.$row['employee_id'].'\');" class="text-secondary" title="View Employee Lifecycle"><i class="fas fa-route mr-1"></i></a>
            ';
            return $returnValue;
        }
    ),
    array('db' => 'ifsc_code', 'dt' => 'ifsc_code'),
    array('db' => 'epf_applicable_status', 'dt' => 'epf_applicable_status'),
    
    array('db' => 'email', 'dt' => 'email'),
    array('db' => 'phone', 'dt' => 'phone'),
    array('db' => 'gender', 'dt' => 'gender'),
    array('db' => 'dob', 'dt' => 'dob'),

    array('db' => 'notice_period', 'dt' => 'notice_period'),
    array('db' => 'department_name', 'dt' => 'department_name'),
    array('db' => 'designation_name', 'dt' => 'designation_name'),
    array('db' => 'role', 'dt' => 'role'),
    array('db' => 'l_name', 'dt' => 'l_name'),
    array('db' => 'consider_as', 'dt' => 'consider_as'),
    array('db' => 'remember_token', 'dt' => 'remember_token'),
    array('db' => 'last_login_time', 'dt' => 'last_login_time'),
    array('db' => 'working_status_final', 'dt' => 'working_status_final'),

);


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * 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)
);
