<?php
$res = 0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
    $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"] . "/main.inc.php";
}
// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME'];
$tmp2 = realpath(__FILE__);
$i = strlen($tmp) - 1;
$j = strlen($tmp2) - 1;
while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
    $i--;
    $j--;
}
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1)) . "/main.inc.php")) {
    $res = @include substr($tmp, 0, ($i + 1)) . "/main.inc.php";
}
if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1))) . "/main.inc.php")) {
    $res = @include dirname(substr($tmp, 0, ($i + 1))) . "/main.inc.php";
}
// Try main.inc.php using relative path
if (!$res && file_exists("../main.inc.php")) {
    $res = @include "../main.inc.php";
}
if (!$res && file_exists("../../main.inc.php")) {
    $res = @include "../../main.inc.php";
}
if (!$res && file_exists("../../../main.inc.php")) {
    $res = @include "../../../main.inc.php";
}
if (!$res) {
    die("Include of main fails");
}
require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/helper.class.php';

$helper = new Helper($db);

$oneselect = GETPOST('oneselect', 'int');

$search_title = GETPOST('search_title', 'aZ09');
$toselectnewtool = GETPOST('toselectnewtool', 'alpha');
$reduction = GETPOST('reduction', 'alpha');
$groupid = GETPOST('groupid', 'int');

$selectedArray = explode(',', $toselectnewtool);

if (isset($_SESSION['devices_array'])) {
    $devices_array = $_SESSION['devices_array'];
    if($search_title === ''){
        if ($reduction !== '') {
            $devices_array = explode(',', $reduction);
        }
        elseif($toselectnewtool !== ''){
            $devices_array = explode(',', $toselectnewtool);
        }else{
            $devices_array = [];
        }
    }else{
        if($toselectnewtool !== ''){
            $devices_array = array_unique(array_merge($devices_array, explode(',', $toselectnewtool)));
        }
        elseif ($reduction !== '') {
            $devices_array = array_unique(array_merge($devices_array, explode(',', $reduction)));
            $devices_array = array_intersect($devices_array, explode(',', $reduction));
        }else{
            $devices_array = [];
        }
        $selectedArray = array_filter($devices_array, 'strlen');
        
    }
    $_SESSION['devices_array'] = $devices_array;
    $selectedArray = $devices_array;
} else {
    $_SESSION['devices_array'] = $selectedArray;
}

function getFilteredTools($db, $string, $groupid)
{
    $helper = new Helper($db);
    $allTools = [];
    $entity_id = $helper->getEntityIdFromPackage($groupid);
    $sql = "SELECT i.rowid, i.ref, i.title, ie.device_type, ie2.fk_object, i.status
        FROM llx_inventory as i 
        INNER JOIN llx_inventory_extrafields as ie ON ie.fk_object = i.rowid
        LEFT JOIN llx_inventory_extrafields AS ie2 ON ie2.assigned_device::integer = i.rowid 
        WHERE i.rowid NOT IN (SELECT device_id FROM llx_settlements_packagetool) 
        AND ie.fk_entity = '{$entity_id}' AND ie.device_type::integer NOT IN (3,4) AND i.ref LIKE '%{$string}%' ORDER BY i.rowid";
    //print $sql;
    $data = $db->query($sql);
    if (!$data) {
        dol_syslog("No group found.", LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
        return $allTools;
    }
    while ($row = pg_fetch_assoc($data)) {
        $allTools['freeTools'][$row['rowid']] = $row;
        if (isset($row['fk_object'])) {
            $inventoryObj = new Inventory($db);
            $inventoryObj->fetch($row['fk_object']);
            $assigned_device_data = ['rowid' => $inventoryObj->id, 'title' => $inventoryObj->title, 'ref' => $inventoryObj->ref, 'device_type' => $inventoryObj->array_options['options_device_type'], 'status' => $inventoryObj->status];
            $allTools['freeTools'][$row['rowid']]['assigned_device_data'] = $assigned_device_data;
        }
    }
    $sql = "SELECT i.rowid, i.ref, i.title, ie.device_type, ie2.fk_object, i.status, (SELECT ref FROM llx_settlements_package as package WHERE package.rowid = pt.package_id) as package_ref, pt.package_id as packageid
        FROM llx_inventory as i 
        INNER JOIN llx_inventory_extrafields as ie ON ie.fk_object = i.rowid
        INNER JOIN llx_settlements_packagetool AS pt ON pt.device_id=i.rowid
        LEFT JOIN llx_inventory_extrafields AS ie2 ON ie2.assigned_device::integer = i.rowid 
        WHERE i.rowid IN (SELECT device_id FROM llx_settlements_packagetool) 
        AND ie.fk_entity = '{$entity_id}' AND ie.device_type::integer NOT IN (3,4) AND i.ref LIKE '%{$string}%' ORDER BY i.rowid";
    //print $sql;
    $data = $db->query($sql);
    if (!$data) {
        dol_syslog("No group found.", LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
        return $allTools;
    }
    while ($row = pg_fetch_assoc($data)) {
        $allTools['addedTools'][$row['packageid']][$row['rowid']] = $row;
        if (isset($row['fk_object'])) {
            $inventoryObj = new Inventory($db);
            $inventoryObj->fetch($row['fk_object']);
            $assigned_device_data = ['rowid' => $inventoryObj->id, 'title' => $inventoryObj->title, 'ref' => $inventoryObj->ref, 'device_type' => $inventoryObj->array_options['options_device_type'], 'status' => $inventoryObj->status];
            $allTools['addedTools'][$row['packageid']][$row['rowid']]['assigned_device_data'] = $assigned_device_data;
        }
        $allTools['addedPackages'][$row['packageid']] = $row['package_ref'];
    }
    return $allTools;
}

$allTools = $search_title != '' ? getFilteredTools($db, $search_title, $groupid) : $helper->getAllToolsFromSelectedEntity($db, $groupid);
$form = new Form($db);

print '<form method="POST" id="searchFormList" action="' . $url . '" onkeyup="submitFormAjaxTools()">' . "\n";
if (is_array($allTools['freeTools'])) {
    $searchedString = '<table style="width:100%;">';
    foreach ($allTools['freeTools'] as $freeTool) {
        $selected = in_array($freeTool['rowid'], $selectedArray) ? 'checked' : '';
        $disabled = !isset($freeTool['assigned_device_data']) ? 'disabled' : '';
        if ($freeTool['device_type'] == 1) {
            $searchedString .= '<tr style="height:30px; background-color: lightgrey;">
			<td class="nowrap center"><input id="id_3_' . $freeTool['rowid'] . '" class="flat checkforselectadd" type="checkbox" onclick="submitFormAjaxAddTool(event)" name="toselectnewtool[]" value="' . $freeTool['rowid'] . '" ' . $selected . ' ' . $disabled . '></td>
			<td><span class="fa fa-mobile pictofixedwidth"></span> ' . $freeTool['ref'] . ' - ' . $freeTool['title'] . '</td>
		</tr>';
            $searchedString .= '<tr style="height:30px; background-color: lightgrey;">';
            $searchedString .= '<td class="nowrap center"></td>';
            if (!isset($freeTool['assigned_device_data'])) {
                $searchedString .= '<td style="color: red;">&nbsp;&nbsp;&nbsp;&nbsp;<span class="fa fa-credit-card pictofixedwidth"></span>Nincs hozzárendelve kártyaolvasó</td>';
            } else {
                $searchedString .= '<td>&nbsp;&nbsp;&nbsp;&nbsp;<span class="fa fa-credit-card pictofixedwidth"></span> ' . $freeTool['assigned_device_data']['ref'] . ' - ' . $freeTool['assigned_device_data']['title'] . '</td>';
            }

            $searchedString .= '</tr>';
        } elseif ($freeTool['device_type'] == 0 || $freeTool['device_type'] == 3 || $freeTool['device_type'] == 4 || $freeTool['device_type'] == 5) {
            //} else {
            $searchedString .= '<tr style="height:30px;">
			<td class="nowrap center"><input id="id_3_' . $freeTool['rowid'] . '" class="flat checkforselectadd" type="checkbox" onclick="submitFormAjaxAddTool(event)" name="toselectnewtool[]" value="' . $freeTool['rowid'] . '" ' . $selected . '></td>
			<td><span class="fa fa-toolbox pictofixedwidth"></span> ' . $freeTool['ref'] . ' - ' . $freeTool['title'] . '</td>
		</tr>';
        }
    }
    $searchedString .= '</table>';
}
if (is_array($allTools['addedTools'])) {
    $searchedString .= $helper->addedToolsDiv($allTools);
}

print $searchedString;
?>
<script>
    function submitFormAjaxAddTool(event) {
        //alert('ajax');
        console.log('submit');
        var checkbox = event.target;
        var groupid = document.getElementById("groupid");
        var input = document.getElementById("name_search");
        var checkboxes = document.querySelectorAll('.checkforselectadd:checked');
        var values = Array.from(checkboxes).map(function (checkbox1) {
            return checkbox1.value;
        });
        if (checkbox.checked) {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", "ajaxtools.php?search_title=" + input.value + "&toselectnewtool=" + values + "&groupid=" + groupid.value, true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    $("#searchedToolsDiv").html(xhr.responseText);
                }
            };
            xhr.send();
        } else {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", "ajaxtools.php?search_title=" + input.value + "&reduction=" + values + "&groupid=" + groupid.value, true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    $("#searchedToolsDiv").html(xhr.responseText);
                }
            };
            xhr.send();
        }
    }

    $('.checkforselectadd').click(function () {
        if ($(this).is(':checked')) {
            $('#divAdd').css('display', 'inline-block');
            $('#massactionadd').css('display', 'inline-block');
            $('.massactionaddselect ').css('display', '');
            $('.massactionaddconfirmed ').css('display', '');
        } else {
            var checkboxes = document.querySelectorAll('.checkforselectadd:checked');
            var values = Array.from(checkboxes).map(function (checkbox) {
                return checkbox.value;
            });
            if (values.length === 0) {
                $('#divAdd').css('display', 'none');
                $('#massactionadd').css('display', 'none');
                $('.massactionaddselect ').css('display', 'none');
                $('.massactionaddconfirmed ').css('display', 'none');
            }
        }
    })
</script>