<?php $stmt = $GLOBALS['con']->prepare("SELECT * FROM `address_book` WHERE `clientnumber`=? ")or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i',$_REQUEST['clientnumber']);$stmt->execute();$cr=$stmt->get_result();$stmt->close();
$count=mysqli_num_rows($cr);


?>
<div class="row">
    <div class="col-12 col-md-6">
        <div class="note note-light mb-3">
            This list will be auto populated by your main client profile. Add to this list for quick access to client contacts.<br /><small>Select "auto" for all contacts you wish to add to any outgoing emails for certification</small>
        </div>
    </div>
    <div class="col-12 col-md-6">
        <span class="float-end">
            <a class="btn btn-secondary" onclick="importAddress('client')" data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" totitle="hover" title="Import Client Contacts">Import Client Contacts</a>
            <a class="btn btn-secondary" onclick="importAddress('agent')" data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" totitle="hover" title="Import Agent Contacts">Import Agent Contacts</a>
            <a class="btn btn-secondary" onclick="importAddress('broker')" data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" totitle="hover" title="Import Broker Contacts">Import Broker Contacts</a>
        </span>

    </div>
</div>
<p class="lead">New Entry</p>
<div id="addrow" class="row mb-5 alert-info p-3">
    <div class="col-12 col-md-2"><label class="control-label" for="firstName">First Name</label><input id='firstName' class='form-control' type="text" /></div>
    <div class="col-12 col-md-2"><label class="control-label" for="lastName">Last Name</label><input id='lastName' class='form-control' type="text" /></div>
    <div class="col-12 col-md-2"><label class="control-label" for="phone1">Phone 1</label><input id='phone1' class='form-control' type="text" /></div>
    <div class="col-12 col-md-2"><label class="control-label" for="phone2">Phone 2</label><input id='phone2' class='form-control' type="text" /></div>
    <div class="col-12 col-md-2"><label class="control-label" for="email">Email</label><input id='email' class='form-control' type="text" /></div>
    <div class="col-12 col-md-2 text-center"><label class="control-label" for="add"></label><br><button id="add" class="btn btn-success text-light"><i class="fad fa-plus text-light"></i></button></div>
</div>


<table id='table2' class="table table-bordered table-sm">
    <thead class="table-dark">
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Phone 1</th>
            <th>Phone 2</th>
            <th>Email</th>
            <th>Auto</th>
            <th>Assigned As</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>



<script>
function updateAssignment(select, id) {
    const assignment = select.value;
    const params = `fcn=updateAssignment&id=${id}&assignment=${assignment}&clientnumber=${encodeURIComponent(<?= json_encode($_REQUEST['clientnumber']) ?>)}&tenant=${TENANT_URL}`;

    $.post(ROOT_URL + '/includes/client/client_addressbook_functions.php?' + params, function(ret) {
        if ($.trim(ret) === "1") {
            select.classList.add("border-success");
            setTimeout(() => select.classList.remove("border-success"), 1000);
            showResponse('success', 'Contact assignment successful');
        } else {
            showResponse('danger', 'Failed to update assignment type');
        }
    });
}

function importAddress(type) {
    dest = ROOT_URL + '/includes/client/client_addressbook_functions.php?fcn=import&type=' + type + '&clientnumber=<?= $_REQUEST['clientnumber']?>&tenant=' + TENANT_URL;
    loadModalContent(dest, "addressBox", "modal-xl", 1060, "true", 'Import ' + type + ' contacts');


}

var addressBook = (function() {
    var people = [
        <?php $c=1;while($cd=mysqli_fetch_array($cr)){
if($cd['auto']=="1"){$auto="checked";}
else{$auto="";}
?> {
            firstName: '<?= $cd['firstName']?>',
            lastName: '<?= $cd['lastName']?>',
            phone1: '<?= $cd['phone1']?>',
            phone2: '<?= $cd['phone2']?>',
            email: '<?= $cd['email']?>',
            auto: '<?= $auto?>',
            id: '<?= $cd['id']?>'
        }
        <?php if($c!=$count){?>, <?php $c++;}?>
        <?php }?>
    ];

    var table = $('#addrow');
    var table2 = $('#table2');
    var tbody = table.find('tbody');
    var tbody2 = table2.find('tbody');
    var $firstName = table.find('#firstName');
    var $lastName = table.find('#lastName');
    var $phone1 = table.find('#phone1');
    var $phone2 = table.find('#phone2');
    var $email = table.find('#email');
    var $auto = table.find('#auto');
    var $button = table.find('#add');
    var $btnRemove = table2.find('#remove');


    $button.on('click', addPerson);
    table2.on('click', '#remove', deletePerson);
    table2.on('click', '#update', savePerson);
    _render();

    function _render() {
        tbody2.html('');
        tbody2.load(ROOT_URL + '/includes/client/client_addressbook_data.php', {
            clientnumber: '<?= $_REQUEST['clientnumber']?>',
            tenant: TENANT_URL
        })
    }


    function addPerson() {
        var person = {
            firstName: $firstName.val(),
            lastName: $lastName.val(),
            phone1: $phone1.val(),
            phone2: $phone2.val(),
            email: $email.val()
        };
        var str = ''
        $.each(person, function(key, element) {
            str = str + key + '=' + element + '&';
        });
        str = str + 'clientnumber=<?= $_REQUEST['clientnumber']?>&';
        str = str + 'fcn=add';
        $.post(ROOT_URL + '/includes/client/client_addressbook_functions.php?' + str + '&tenant=' + TENANT_URL, function(ret) { //alert(ret)
            var rtn = ret.split('|')
            if (rtn[0] == 1) {
                $firstName.val('');
                $lastName.val('');
                $phone1.val('');
                $phone2.val('');
                $email.val('');
                tbody2.prepend(rtn[1])
                tbody2.load(ROOT_URL + '/includes/client/client_addressbook_data.php', {
                    clientnumber: '<?= $_REQUEST['clientnumber']?>',
                    tenant: TENANT_URL

                })
            }
            if (rtn[0] == 0) {
                showResponse('danger', 'USER EXISTS IN THIS ADDRESS BOOK');

            }
        })

    }


    function addImport(f, l, p1, p2, em, ty) {
        alert()
        var person = {
            firstName: f,
            lastName: l,
            phone1: p1,
            phone2: p2,
            email: e,
            type: ty
        };
        var str = ''
        $.each(person, function(key, element) {
            str = str + key + '=' + element;
        });
        str = str + '&clientnumber=<?= $_REQUEST['clientnumber']?>';
        str = str + '&fcn=addImport';
        str = str + '&tenant=' + TENANT_URL;
        $.post(ROOT_URL + '/includes/client/client_addressbook_functions.php?' + str, function(ret) {
            alert(ret)
            var rtn = ret.split('|')
            if (rtn[0] == 1) {

                tbody2.prepend(rtn[1])
                tbody2.load(ROOT_URL + '/includes/client/client_addressbook_data.php', {
                    clientnumber: '<?= $_REQUEST['clientnumber']?>',
                    tenant: TENANT_URL
                })
            }
            if (rtn[0] == 0) {
                showResponse('danger', 'USER EXISTS IN THIS ADDRESS BOOK');

            }
        })

    }


    function deletePerson(event) {
        var str = ''
        var element = event.target.closest('tr');
        var id = $(this).data('id');
        str = str + 'clientnumber=<?= $_REQUEST['clientnumber']?>&';
        str = str + 'id=' + id + '&';
        str = str + 'fcn=remove';
        $.post(ROOT_URL + '/includes/client/client_addressbook_functions.php?' + str + '&tenant=' + TENANT_URL, function(ret) {
            if ($.trim(ret) === "1") {
                $('#R' + id).addClass('table-danger')
                $('#R' + id).fadeOut(2500);

            }
        })
    }

    function savePerson(event) {
        var str = ''
        var element = event.target.closest('tr');
        var id = $(this).data('id');
        var fn = $('#table2').find('#FN_' + id).val();
        var ln = $('#table2').find('#LN_' + id).val();
        var p1 = $('#table2').find('#P_' + id).val();
        var p2 = $('#table2').find('#M_' + id).val();
        var em = $('#table2').find('#E_' + id).val();

        str = str + 'clientnumber=<?= $_REQUEST['clientnumber']?>&';
        str = str + 'id=' + id + '&firstName=' + fn + '&lastName=' + ln + '&phone1=' + p1 + '&phone2=' + p2 + '&email=' + em + '&fcn=update';

        $.post(ROOT_URL + '/includes/client/client_addressbook_functions.php?' + str + '&tenant=' + TENANT_URL, function(ret) {
            if ($.trim(ret) === "1") {

                element.animate({
                    backgroundColor: "#c3e6cb",
                    borderColor: "#8fd19e",

                }, 1000).animate({
                    backgroundColor: "#ffffff",
                    borderColor: "#dee2e6",
                }, 1000);


            }
        })
    }

    return {
        addPerson: addPerson,
        deletePerson: deletePerson
    };
})();

function checker(i) {
    setTimeout(function() {
        var id = i
        if ($('#V_' + id).is(':checked')) {
            var str = ''
            str = str + 'clientnumber=<?= $_REQUEST['clientnumber']?>&';
            str = str + 'id=' + id + '&';
            str = str + 'set=1&';
            str = str + 'fcn=check';
            $.post(ROOT_URL + '/includes/client/client_addressbook_functions.php?' + str + '&tenant=' + TENANT_URL, function(ret) {
                if ($.trim(ret) === "1") {}
            })
        }

        if (!$('#V_' + id).is(':checked')) {
            var str = ''
            str = str + 'id=' + id + '&';
            str = str + 'set=0&';
            str = str + 'fcn=check';
            $.post(ROOT_URL + '/includes/client/client_addressbook_functions.php?' + str + '&tenant=' + TENANT_URL, function(ret) {
                if ($.trim(ret) === "1") {}
            })
        }
    }, 500);
}

$('#navBox').html(
    '<li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&view=list">Client List</a><i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb_item"><a class="text-light" href="index.php?t=includes/master&p=client.php&clientnumber=<?= $_REQUEST['clientnumber']?>&view=asset"><?= addslashes(getClientName($_REQUEST['clientnumber']))?></a><i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb-item active">Address Book</li>'
)
</script>