<div class="col-lg-4 <?php echo in_array(AFFILIATE_CONTROLLER_ID, $access_controller) ? '':'' ?>" id="affiliate-list">
    <div class="row">
        <div class="col-md-12 permissionBox" style="background: #d2d6de">
            <div class="checkbox">
                <label style="font-weight: bold">
                    <input id="aff-all-check" name="aff-all-check" onclick="checkAllAffiliate(this)"  value="" type="checkbox" <?php echo (($user['auto_assign_affiliate'])?'checked':'');?>>
                    Affiliates
                </label>
            </div>
        </div>
    </div>
    <div class="row">
    <div class="col-md-12 permissionBox" style="border: 1px solid #ccc;">
        <?php
        foreach ($affiliates as $affiliate){
            $checked = '';
            if(in_array($affiliate->id,$db_affiliate_id_list)){
                $checked = 'checked';
            }
            ?>
            <div class="checkbox">
                <label>
                    <input value="<?= $affiliate->id?>" type="checkbox" name="affliliate_id[]" <?php echo $checked;?>>
                    <?= h($affiliate->first_name." ".$affiliate->last_name)?>
                </label>
            </div>
            <?php

        }
        ?>
    </div>
    </div>
</div>

<script>
    $(document).ready(function() {
        let a = $(`input[name="affliliate_id[]"]`);
        if(a.length == a.filter(":checked").length){
            $(`#aff-all-check`).prop('checked',true)
        }
    });
    function showHideAffiliateList(elem){
        var selector = $('#affiliate-list input[type=checkbox]');

        if(!$('#affiliate-list').hasClass('hide')) {
            $('#affiliate-list').addClass('hide')
        }
        selector.prop('checked',false);
        if($(elem).prop('checked')){
            selector.prop('checked',true);
            $('#affiliate-list').removeClass('hide')
        }
    }

    function oncheckOfAffiliate(elem){
        $(`input[name="controller_id[]"][value=14]`).prop('checked',true)
        if($(`input[name="affliliate_id[]"]:checked`).length == 0){
            $(`input[name="controller_id[]"][value=14]`).prop('checked',false)
        }
        var all_checkbox = $(`input[name="affliliate_id[]"]`)
        var all_checked_checkbox = $(`input[name="affliliate_id[]"]:checked`)

        $('#aff-all-check').prop('checked', false)
        if(all_checkbox.length == all_checked_checkbox.length) {
            $('#aff-all-check').prop('checked', true);
        }
    }

    function checkAllAffiliate(elem){
        $(`input[name="affliliate_id[]"]`).prop('checked',false);
        $(`#aff-all-check`).val(false);
        if($(elem).prop('checked')){
            $(`input[name="affliliate_id[]"]`).prop('checked',true);
            $(`#aff-all-check`).val(true);
        }
        oncheckOfAffiliate($(`input[name="controller_id[]"][value=14]`));
    }

</script>