<?php 
require_once __DIR__ . '/../../functions/logging.php';
$tenant = $_REQUEST['tenant'];
if(file_exists('../../../'.$tenant.'/config.php')){require_once('../../../'.$tenant.'/config.php');}
if(file_exists('/config.php')){require_once('/config.php');}
if(!$lm){
$linkedFunction = (string)($_REQUEST['FUNCTION'] ?? '');
enrep_log_request_completion('linked_chains', 'FUNCTION', [
    'update' => ['action' => 'updated', 'message' => 'Updated linked asset chain', 'entity_type' => 'itemdetails'],
]);
switch($linkedFunction){
default:break;

case "list":
$stmt1 = $GLOBALS['con']->prepare("SELECT `itemnumber`,`desc`,`serialnumber`,`plantnumber`,`locnumber` FROM `itemdetails` WHERE `itemnumber`=?")or die(mysqli_error($GLOBALS['con']));$stmt1->bind_param('i',$_REQUEST['item']);$stmt1->execute();$idata=$stmt1->get_result();$stmt1->close();
$idx=mysqli_fetch_array($idata);

$stmt = $GLOBALS['con']->prepare("SELECT `itemnumber`,`desc`,`serialnumber`,`plantnumber`,`linked`,`locnumber`  FROM `itemdetails` WHERE `clientnumber`=? and `statuslive`='1'")or die(mysqli_error($GLOBALS['con']));$stmt->bind_param('i',$_REQUEST['clientnumber']);$stmt->execute();$ic=$stmt->get_result();$stmt->close();
$ir=json_decode($_REQUEST['linked']);?>
<style>
#itemList>tbody>tr>td,
#itemList>tbody>tr>th {
    vertical-align: middle
}

filterButtons,
.dt-buttons {
    display: none
}

#select_all:checked+label:before {
    border-right: 2px solid #ffffff;
    border-bottom: 2px solid #ffffff;
}
</style>
<div id="start">
    <div class="row mb-2 border-bottom bg-info">
        <div class="col-12">
            <div class="row mb-2">
                <div class="col-1"><label for="desc" class="text-light mt-3">Description:</label></div>
                <div class="col-6"><input class="form-control mt-2" type="text" id="descriptor" placeholder="Add something to describe this set"></div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-12">
            <table id="itemList" class="table table-striped table-responsive table-sm mt-3" width="100%">
                <thead>
                    <tr>
                        <th>
                            <div class="form-check" style="display: inline-block;"><input type="checkbox" class="form-check-input" id="select_all"><label data-toggle="tooltip" data-placement="right"
                                       title="Select all 'visible' items for mass linking" class="form-check-label" for="select_all"></label></div>
                        </th>
                        <th>Item</th>
                        <th>Location</th>
                        <th>Serial</th>
                        <th>Plant Number</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $lc=1;
                    while($id=mysqli_fetch_array($ic)){$hide='';$sel='';
                    if(!empty($id['linked'])){
                    $isLinked=explode(':',$id['linked']);
                    if($isLinked[0]!=$_REQUEST['set']){$hide=1;}
                    }
                    else{$isLinked="";$link="";$hide=0;}
                    if($id['itemnumber']==$_REQUEST['item']){}
                    else{
                    if($hide!=1){
                    if(!empty($isLinked[2])){$descriptor=$isLinked[2];}

                    if(in_array($id['itemnumber'],$ir)){$sel="selected";}
                    ?>
                    <tr id="N<?= $id['itemnumber']?>" valign="middle">
                        <td>
                            <div class="form-check <?= $sel?>"><input type="checkbox" class="selectableItem form-check-input" id="F<?= $id['itemnumber']?>" value="<?= $id['itemnumber']?>" onclick="addSelection()"><label
                                       class="form-check-label" for="F<?= $id['itemnumber']?>"></label></div>
                        </td>
                        <td><strong><?= $id['desc']?></strong></td>
                        <td><?= getLocation($id['locnumber'])?></td>
                        <td><?= $id['serialnumber']?></td>
                        <td><span style="display:none"><?= $sel?></span><?= $id['plantnumber']?></td>
                    </tr>
                    <?php }}$lc++;}?>
                </tbody>
            </table>
        </div>
    </div>
</div>


<div id="process" style="display: none">
    <div class="col-12 text-center">
        <h1>
            <i class="fad fa-link fa-spin fa-3x fa-fw" style="--fa-primary-color: #0055A6; --fa-secondary-color: gray;"></i><br>Processing Linkages<br><small>Please wait</small>
        </h1>
    </div>
</div>
<input type="hidden" class="form-control" id="originalLinked" value='' />
<input type="hidden" class="form-control" id="currentLinked" value='' />
<script>
setTimeout(function() {
    $('#descriptor').val('<?= $descriptor?>');

}, 1000);
$('#popupBox .modal-header').html(
    '<a href="javascript:void(0)" class="sa">Link Items</a><div id="filterBtn" style="z-index:1;position:absolute; top:5px; right:10px"><a class="btn btn-secondary" onClick="filter()">Show only currently linked</a></div>');

$('#popupBox .modal-footer').html(
    '<div class="col-12 text-center"><a href="javascript:void(0)" class="btn btn-info m-0 px-3 py-2 z-depth-0 waves-effect" onClick="linkSelected()">Link Selected <i class="fad fa-plus"></i> <i class="fad fa-link"></i></a></div>');

$('#originalLinked').val('<?= $_REQUEST['linked']?>');
$('#currentLinked').val('<?= $_REQUEST['linked']?>');

$('document').ready(function() {

    $('#itemList_filter input').val('');
    $("#itemList_filter input").keyup()

})

function filter() {
    $('#itemList_filter input').val('selected');
    $("#itemList_filter input").keyup()
}

var obj = jQuery.parseJSON('<?= $_REQUEST['linked']?>');
$.each(obj, function(key, value) {
    $('#F' + value).prop('checked', true)
})

function linkSelected() {
    $('#filterBtn').css('display', 'none');
    $('#start').css('display', 'none');
    $('#process').css('display', 'block');
    var newItems =
        '<div class="col-6 col-md-3 mb-3 float-left"><div id="I<?= $_REQUEST['item']?>" class="btn-group w-100"><a href="javascript:void(0)" class="btn btn-info btn-block waves-effect waves-light"><?= $idx['desc']?><br><b>SN:</b><?= $idx['serialnumber']?>  <b>PN:</b><?= $idx['plantnumber']?></a></div></div>';


    var o = $('#originalLinked').val();
    var n = $('#currentLinked').val();
    var t = $('#descriptor').val();
    $.post('includes/master/linked_functions.php', {
        set: '<?= $_REQUEST['set']?>',
        clientnumber: '<?= $_REQUEST['clientnumber']?>',
        FUNCTION: 'update',
        original: o,
        new: n,
        descriptor: t
    }, function(ret) {
        var d = ret.split('|')
        $('#originalLinked').val($('#currentLinked').val())
        $('#popupBox').modal('hide');
        $('#popupBox .modal-body').html('');
        showResponse('success', 'Linkage process complete')
        $('#LinkNumber').html(d[1])
    })

    //$('#linkedArray').html(newItems)
}

function select_all() {
    var count = 0;
    var current = '';
    var newAr = '["<?= $_REQUEST['item']?>"]';
    newAr = JSON.parse(newAr)
    newAr = JSON.stringify(newAr)
    $('#currentLinked').val(newAr)
    $('#linked').val(newAr)

    $("#itemList").dataTable().$('tr', {
        "filter": "applied"
    }).each(function() {
        var input = $(this).find('input')

        if ($(input).is(':checked')) {
            var i = input.val();

            if ($('#currentLinked').val() === "[]") {
                current = JSON.parse($('#currentLinked').val());
                var newAr = current += i
            } else {
                current = JSON.parse($('#currentLinked').val());
                var newAr = current += "," + i
            }
            newAr = newAr.split(',');
            newAr = JSON.stringify(newAr)
            $('#currentLinked').val(newAr)
            $('#linked').val(newAr)

            count++;
        }
    });

    //alert(count)
};

$('#select_all').change(function() {
    if (!$(this).is(':checked')) {
        var a = 0;
        var b = 0;
        $("#itemList").dataTable().$('tr', {
            "filter": "applied"
        }).each(function() {
            a++
        })

        $("#itemList").dataTable().$('tr', {
            "filter": "applied"
        }).each(function() {
            $(this).find('input').each(function() {
                $(this).prop("checked", false)
            })
            b++
        })
        if (a === b) {
            select_all()
        }
    }
    if ($(this).is(':checked')) {
        var a = 0;
        var b = 0;
        $("#itemList").dataTable().$('tr', {
            "filter": "applied"
        }).each(function() {
            a++
        })

        $("#itemList").dataTable().$('tr', {
            "filter": "applied"
        }).each(function() {
            $(this).find('input').each(function() {
                $(this).prop("checked", true)
            })
            b++
        })
        if (a === b) {
            select_all()
        }
    }
})

function addSelection() {
    var newAr = []
    newAr.push("<?= $_REQUEST['item']?>")
    var table = $('#itemList').dataTable()
    $("input:checked", table.fnGetNodes()).each(function() {
        newAr.push($(this).val());
    });
    newAr = JSON.stringify(newAr)

    $('#currentLinked').val(newAr)
    $('#linked').val(newAr)

}
</script>
<?php 
$table="itemList";
$scroll="'300px'";
require_once('../light_table.engine');
break;

case "update":
$stmt = $GLOBALS['con']->prepare("SELECT DISTINCT `linked` FROM `itemdetails` WHERE `clientnumber`='".$_REQUEST['clientnumber']."'")or die(mysqli_error($GLOBALS['con']));$stmt->execute();$ic=$stmt->get_result();$stmt->close();$num=mysqli_num_rows($ic);
$list=[];
if(mysqli_num_rows($ic)==0){if($_REQUEST['set']==""){$_REQUEST['set']=1;}}
else{
while($li=mysqli_fetch_array($ic)){
$linked=explode(':',$li['linked']);
$list[]=$linked[0];
}
if(empty($list)){$_REQUEST['set']=1;}
else{
    if($_REQUEST['set']==""){$_REQUEST['set']=max($list)+1;}
}
}

echo "SET=".$_REQUEST['set']."<br>".print_r($list);
$original=json_decode($_REQUEST['original']);
$new=json_decode($_REQUEST['new']);


foreach($original as $reset){
$stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `linked`='' WHERE `itemnumber`='".$reset."'")or die(mysqli_error($GLOBALS['con']));
$stmt->execute();$stmt->close();
}
if(count($new)>1){
$itemcount=0;
foreach($new as $add){
$entry=$_REQUEST['set'].":".$_REQUEST['new'].":".$_REQUEST['descriptor'];
$stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `linked`='".$entry."' WHERE `itemnumber`='".$add."'")or die(mysqli_error($GLOBALS['con']));
$stmt->execute();$stmt->close();	
$itemcount++;
}
}

//genSchedule($_REQUEST['clientnumber']);
echo "success|".$itemcount; 
break;

}

}
else{
?>
<div id="linkedArray" class="col-12">
    <div class="row">
        <?php if(!empty($cd['linked'])){
$linked=explode(":",$cd['linked']);
if(!$linked[1]){$ir=json_decode($linked[0]);}
else{$ir=json_decode($linked[1]);}
$c=0;
foreach($ir as $l){
$c++;
}
}?>
    </div>
</div>
<input type="hidden" id="linkCount" value="<?= $c?>">
<script>
$('#LinkNumber').html($('#linkCount').val())
</script>

<?php }?>
