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


$users = mysqli_fetch_all(mysqli_query($db,"SELECT * FROM users"), MYSQLI_ASSOC);
$table = <<<EOT
(
    SELECT 
        ROW_NUMBER() OVER(ORDER BY t1.id DESC) row_num,
        t1.*,
        t1.id as action_id,
        t1.asset_status as remove_asset_status,
        t2.type,
        t3.name as add_by,
        t4.name as assign_to
    FROM asset_management t1
    INNER JOIN asset_types t2 ON t2.id=t1.asset_type
    INNER JOIN users t3 ON t3.employee_id=t1.added_by
    INNER JOIN users t4 ON t4.employee_id=t1.assigned_to
) 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' => 'row_num', 'dt' => 'row_num'),
    array('db' => 'type', 'dt' => 'type'),
    array('db' => 'add_by', 'dt' => 'add_by'),
    array('db' => 'assign_to', 'dt' => 'assign_to'),
    array(
        'db' => 'asset_details', 
        'dt' => 'asset_details',
        'formatter' => function($cell, $row){
            $returnValue = '';
            if(!empty($cell)){
                $returnValue = '<p class="text-primary show_hide_assets" style="cursor:pointer;">Show Assets <i class="uil uil-angle-right"></i></p>
                <div style="display:none;">';
                $status = json_decode($row['asset_status'],true) ?? [];
                foreach (json_decode($cell, true) as $key => $value) {
                    $returnValue .= '<h6 class="m-0 d-flex justify-content-between"><strong>Asset. '.($key+1).'</strong>';
                    if(array_key_exists($key, $status)){
                        $returnValue .= '<span class="text-danger">'.$status[$key].'</span>';
                    }
                    $returnValue .= '</h6>
                    ';
                    foreach($value as $k => $v){
                        $returnValue .= '<p class="mb-0 ml-2"><strong>'.ucwords(str_replace("_"," ",$k)).': </strong>'.$v.'</p>
                        ';
                    }
                }
                $returnValue .= '</div>';
            }
            return $returnValue;
        }
    ),
    array('db' => 'holding_period', 'dt' => 'holding_period'),
    array('db' => 'assigned_date', 'dt' => 'assigned_date'),
    array(
        'db' => 'asset_desc', 
        'dt' => 'asset_desc',
        'formatter' => function($cell, $row){
            $returnValue = '
                <div style="min-width:300px;">'.$cell.'</div>
            ';
            return $returnValue;
        }
    ),
    array(
        'db' => 'asset_status', 
        'dt' => 'asset_status',
        'formatter' => function($cell, $row){
            $asset_details_keys = array_keys(json_decode($row['asset_details'], true)??[]);
            $asset_status_keys = array_keys(json_decode($row['asset_status'],true)??[]);
            $intersect = array_intersect($asset_details_keys, $asset_status_keys);
            if(empty($intersect)){
                $returnValue = '<div style="width:200px;">
                    <select class="form-control mb-1" name="asset_name'.$row['id'].'" id="asset_name'.$row['id'].'" onchange="check_asset_name(this.value,\''.$row['id'].'\');">
                        <option selected value="">Select Asset</option>
                ';

                foreach (json_decode($row['asset_details'], true) as $key => $value) {
                    if(!array_key_exists($key, json_decode($row['asset_status'],true)??[])){
                        $returnValue .= '<option value="'.$key.'">'.$value['name'].'</option>';
                    }
                }
                $returnValue .= '</select>
                    <select class="form-control mb-1" name="asset_status'.$row['id'].'" id="asset_status'.$row['id'].'" style="display:none;" onchange="check_asset_status(this.value,\''.$row['id'].'\');">
                        <option selected value="">Select Asset Status</option>
                        <option value="Transfer">Transfer</option>
                        <option value="Return">Return</option>
                        <option value="Discarded">Discarded</option>
                    </select>
                    <select class="form-control mb-1" name="transfer_to'.$row['id'].'" id="transfer_to'.$row['id'].'" style="display:none;">
                        <option selected value="">Select Employee</option>
                ';
                $users = $GLOBALS['users'];
                foreach($users as $user){
                    $returnValue .= '<option value="'.$user['employee_id'].'">'.$user['name'].'</option>';
                }
                $returnValue .= '</select>
                <button type="button" class="btn btn-primary btn-padding w-100" onclick="set_asset_status(\''.$row['id'].'\');" id="set_status_button'.$row['id'].'">Set Status</button>
                </div>';
            }else{
                $returnValue = '<div style="width:200px;">
                    <select class="form-control mb-1" disabled>
                        <option>Select Asset</option>
                    </select>
                    </div>';
            }
           
            return $returnValue;
        }
    ),
    array(
        'db' => 'remove_asset_status', 
        'dt' => 'remove_asset_status',
        'formatter' => function($cell, $row){
            $asset_details_keys = array_keys(json_decode($row['asset_details'], true)??[]);
            $asset_status_keys = array_keys(json_decode($row['asset_status'],true)??[]);
            $intersect = array_intersect($asset_details_keys, $asset_status_keys);
            if(!empty($intersect)){
                $returnValue = '<div style="width:200px;">
                    <select class="form-control mb-1" name="r_asset_name'.$row['id'].'" id="r_asset_name'.$row['id'].'">
                        <option selected value="">Select Asset</option>
                ';
                $remove_status_json = json_decode($row['asset_details'], true)??[];
                foreach ($remove_status_json as $key => $value) {
                    if(array_key_exists($key, json_decode($row['asset_status'],true)??[])){
                        $returnValue .= '<option value="'.$key.'">'.$value['name'].'</option>';
                    }
                }
                $returnValue .= '</select>
                <button type="button" class="btn btn-danger btn-padding w-100" onclick="remove_asset_status(\''.$row['id'].'\');" id="remove_status_button'.$row['id'].'">Remove Status</button>
                </div>';
            }else{
                $returnValue = '<div style="width:200px;">
                    <select class="form-control mb-1" disabled>
                        <option>Select Asset</option>
                    </select>
                    </div>';

            }
           
            return $returnValue;
        }
    ),
    array(
        'db' => 'action_id', 
        'dt' => 'action_id',
        'formatter' => function($cell, $row){
            $returnValue = '
                <a href="add_assets?edit='.$row['id'].'" class="mr-1 text-success" 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>';
            return $returnValue;
        }
    ),
    array('db' => 'id', 'dt' => 'id'),
);


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