<?php
use Orchard\Feature\Feature;

$conflict_manager_ff = Feature::isEnabled('alw_conflict_manager', 'enabled', $this->featureVendorContext);

?>

<div id="content">
<div id="loading_image" style="display: none;">
    <div class="modalLoading"><b><?=$this->translate('LOADING...')?></b><br /><img src="/images/loading.gif" /></div>
</div>

<div id="bread">
    <a href="/account/admin"><?=$this->translate('Admin')?></a>
</div>

<h1 id="pageheader"><?=($this->vc_id ? $this->translate('Edit User') : $this->translate('Create New User'))?></h1>
<form id="editlabelcontact_form" autocomplete="off">
    <?php
    /** Show Label Assignment for D3 users (only for create new user) -- START */
    if (!$this->vc_id && Zend_Registry :: get('UserObj')->isAllowed('', '', 'managelabels')) { ?>
    <div class="panel panel-default">
        <div class="panel-heading">
            <h3 class="panel-title"><?=$this->translate('Subaccount Assignment')?></h3>
        </div>
        <div class="panel-body">
            <?php
                $this->form->label_assignment->setValue(array('Y'))
                    ->setRequired(false);
                echo $this->form->label_assignment->render();
            ?>
            <br>
            <div class="col-md-6">
                <?php
                $this->form->subaccount_id->setAttrib('class', 'formTextSelect form-control');
                echo $this->form->subaccount_id->renderViewHelper();?>
            </div>
            <div class="validation_message"></div>
        </div>
    </div>
    <?php
    }
    /** Show Label Assignment for D3 users -- ENDS */
    ?>

    <!-- ---------------- User Info STARTS ---------------------- -->
    <div class="panel panel-default">
       <div class="panel-heading">
           <h3 class="panel-title"><?=$this->translate('User Info')?></h3>
       </div>
        <div class="panel-body">
            <div class="col-md-6">
                <div class="form-group">
                    <label for="login"><?=$this->translate('Login Email')?><span class="required">*</span></label>
                    <?php
                    if ($this->vc_id) {
                        echo $this->form->login->setAttrib('readonly', 'readonly')->setAttrib('class', 'form-control disabled')->renderViewHelper();
                    } else {
                        echo $this->form->login->setAttrib('class', 'form-control')->renderViewHelper();
                    } ?>
                    <div class="validation_message"></div>
                </div>
                <div class="form-group">
                    <label for="contact_email"><?=$this->translate('Communication Email Address')?><span class="required">*</span></label>
                    <?=$this->form->contact_email->setAttrib('class', 'form-control')->renderViewHelper();?>
                    <div class="validation_message"></div>
                </div>
                <div class="form-group">
                    <label for="contact_first_name"><?=$this->translate('First Name')?><span class="required">*</span></label>
                    <?=$this->form->contact_first_name->setAttrib('class', 'form-control')->renderViewHelper();?>
                    <div class="validation_message"></div>
                </div>
                <div class="form-group">
                    <label for="contact_last_name"><?=$this->translate('Last Name')?><span class="required">*</span></label>
                    <?=$this->form->contact_last_name->setAttrib('class', 'form-control')->renderViewHelper();?>
                    <div class="validation_message"></div>
                </div>
                <div class="form-group">
                    <label><?=$this->translate('Phone Numbers')?></label>
                    <?=$this->form->contact_phone->setAttrib('class', 'form-control')->renderViewHelper();?>
                    <div class="validation_message"></div>
                    <p for="contact_phone" class="smalltext"><?=$this->translate('Main')?><span class="required">*</span></p>
                </div>
                <div class="form-group">
                    <?=$this->form->contact_cell->setAttrib('class', 'form-control')->renderViewHelper();?>
                    <div class="validation_message"></div>
                    <p for="contact_cell" class="smalltext"><?=$this->translate('Mobile')?></p>
                </div>
                <div class="form-group">
                    <?=$this->form->contact_fax->setAttrib('class', 'form-control')->renderViewHelper();?>
                    <div class="validation_message"></div>
                    <p for="contact_fax" class="smalltext"><?=$this->translate('Fax')?></p>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label for="company"><?=$this->translate('Company')?></label>
                    <?=$this->form->company->setAttrib('class', 'form-control')->renderViewHelper();?>
                    <div class="validation_message"></div>
                </div>
                <div class="form-group">
                    <label for="contact_title"><?=$this->translate('Position/Title')?></label>
                    <?=$this->form->contact_title->setAttrib('class', 'form-control')->renderViewHelper();?>
                    <div class="validation_message"></div>
                </div>
                <div class="form-group">
                    <label><?=$this->translate('Address')?></label>
                    <?=$this->form->address_street->setAttrib('class', 'form-control')->renderViewHelper();?>
                    <div class="validation_message"></div>
                    <span for="address_street" class="smalltext"><?=$this->translate('Street Address 1')?></span>
                </div>
                <div class="form-group">
                    <?=$this->form->address2->setAttrib('class', 'form-control')->renderViewHelper();?>
                    <div class="validation_message"></div>
                    <span for="address2" class="smalltext"><?=$this->translate('Street Address 2')?></span>
                </div>
                <div class="form-group">
                    <?=$this->form->address_city->setAttrib('class', 'form-control')->renderViewHelper();?>
                    <div class="validation_message"></div>
                    <span for="address_city" class="smalltext"><?=$this->translate('City')?></span>
                </div>
                <div class="form-group">
                    <?=$this->form->address_state->setAttrib('class', 'form-control')->renderViewHelper()?>
                    <div class="validation_message"></div>
                    <span for="address_state" class="smalltext"><?=$this->translate('State')?></span>
                </div>
                <div class="form-group">
                    <?= $this->form->address_zip->setAttrib('class', 'form-control')->renderViewHelper();?>
                    <div class="validation_message"></div>
                    <span for="address_zip" class="smalltext"><?=$this->translate('Zip/Postal Code')?></span>
                </div>
                <div class="form-group">
                    <?=$this->form->orchard_country->setAttrib('class', 'form-control')->renderViewHelper()?>
                    <div class="validation_message"></div>
                    <span for="orchard_country" class="smalltext"><?=$this->translate('Country')?></span>
                </div>
            </div>
        </div>
    </div>
    </div>
    <!-- ---------------- User Permissions STARTS ---------------------- -->
    <div class="panel panel-default">
        <div class="panel-heading">
            <h3 class="panel-title"><?=$this->translate('User Permissions')?></h3>
        </div>
        <div class="panel-body">
            <div class="well well-emphasised">
                <div class="checkbox">
                    <?=$this->form->{$this->vendor_roles['Administrator']}->renderViewHelper();?>
                    <label for="role_id_4">
                        <strong><?=$this->translate('Administrator')?></strong> &ndash;
                        <?=$this->translate('Has access to all sections, can create new users, set permissions and edit account settings')?>
                    </label>
                </div>
            </div>
            <hr>
            <h6><?=$this->translate('OR select the sections that this user has access to:')?></h6>
            <div class="well checkbox">
                <?php
                /** loop to display all other non-administrator roles to page as check boxes with translation */
                foreach ($this->vendor_roles as $vendor_role_name => $vendor_role_checkbox_id) {
                    if ($vendor_role_name != "Administrator") {
                        if ($vendor_role_name == 'Marketing') {
                            //@todo (OrCharles): can we just change the text in the database instead of this.. here?
                            $vendor_role_name = 'Marketplace';
                        }
                ?>

                <?=$this->form->{$vendor_role_checkbox_id}->renderViewHelper();?>
                <label for="<?=$vendor_role_checkbox_id?>" id="label_<?=$vendor_role_checkbox_id?>">
                    <?php
                    if ($vendor_role_name == 'Accounting') {
                        echo $this->translate('<strong>Accounting</strong> – view everything under the accounting tab, including all financial information and your Travelex account');
                    } elseif ($vendor_role_name == 'Catalog') {
                        echo $this->translate('<strong>Catalog</strong> – view and manage your catalog at The Orchard');
                    } elseif ($vendor_role_name == 'Analytics') {
                        echo $this->translate('<strong>Analytics</strong> – view everything under the analytics tab, including sales data for any release in your catalogue');
                    } elseif ($vendor_role_name == 'Manage Rights') {
                        if ($conflict_manager_ff) {
                            echo $this->translate('<strong>Manage Rights</strong> – edit track metadata required to collect performance (neighbouring) rights royalties and mediate rights conflicts');
                        } else {
                            echo $this->translate('<strong>Manage Rights</strong> – view and update track metadata required to collect performance (neighboring) rights royalties');
                        }
                    } elseif ($vendor_role_name == 'Marketplace') {
                        echo $this->translate('<strong>Marketing</strong> – permission to view, install, and use Apps in the Orchard Marketing');
                    } elseif ($vendor_role_name == 'Advertising') {
                            echo $this->translate('<strong>Advertising</strong> – permission to view, setup and submit Ad Campaigns for approval');
                    } ?>
                </label>
                <hr id="line_<?=$vendor_role_checkbox_id?>">
                <?php
                    }
                }
                ?>
            </div>
        </div>
    </div>
    <?php if ($this->vc_id && $this->auth0_user_id) { ?>
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title"><?=$this->translate('Change Password')?></h3>
            </div>
            <div id="reset-password-success-msg" class="top-space notDisplay">
                <?=$this->translate('Please follow the instructions we\'ve sent to your email.')?>
            </div>
            <div id="reset-password-error-msg" class="top-space notDisplay">
                <?=$this->translate('An error occurred, please contact your label manager.')?>
            </div>
            <div class="panel-body">
                <div class="form-group">
                        <button type="button" class="btn btn-default" id="reset-auth0-password">
                            <?=$this->translate('Reset Password')?>
                        </button>
                    <div class="validation_message" id="reset-password-msg"></div>
                </div>
            </div>
        </div>
    <?php } elseif ($this->vc_id) { ?>
    <?php /* ability to reset password for a non-migrated auth0 user */ ?>
        <!-- ---------------- Password Panel STARTS ---------------------- -->
        <div class="panel panel-default">
            <div class="panel-heading">
            <h3 class="panel-title"><?=$this->translate('Password')?></h3>
            </div>
            <div class="panel-body">
                <div class="form-group">
                    <label for="login">
                        <?=$this->translate('Password');
                        if (!$this->vc_id) {
                        ?>
                            <span class="required">*</span>
                        <?php
                        }
                        ?>
                    </label>
                    <?=$this->form->passwords->setAttrib('class', 'form-control')->renderViewHelper()?>
                    <div class="validation_message"></div>
                </div>
                <div class="form-group">
                    <label for="contact_email">
                        <?=$this->translate('Confirm Password');
                        if (!$this->vc_id) {
                        ?>
                            <span class="required">*</span>
                        <?php
                        }
                        ?>
                    </label>
                    <?=$this->form->verify_password->setAttrib('class', 'form-control')->renderViewHelper()?>
                    <div id="verify_password_validation_message"></div>
                </div>
            </div>
        </div>
    <?php }?>
    <input name="vc_id" id="vc_id" type="hidden" value="<?=$this->vc_id?>">
    <div class="clear"></div>
<!-- ---------------- Create/Edit button ---------------------- -->
    <?php
    if ($this->vc_id) {
        $saveButton = $this->translate('Save User');
    } else {
        $saveButton = $this->translate('Create User');
    }
    ?>
    <button type="button" class="btn btn-primary" id="submit_labelcontact_form" onclick="$('#editlabelcontact_form').submit();"><?=$saveButton?></button>

    <div id="editlabelcontact_error_message"  class="submitMessage" style="color:red"></div>
    <div id="editlabelcontact_success_message"  class="submitMessage" style="color:green"></div>
</form>

<!-- ---------------- Page content ENDS ---------------------- -->

<script language="javascript" type="text/javascript">
$(document).ready(function () {
    $('#reset-auth0-password').click(
        function (){
            $.ajax({
                type: 'POST',
                url: '/account/changeauth0password',
                data: { vc_id: $('#vc_id').val() },
                dataType: 'json',
                success: function(response, textStatus, XMLHttpRequest){
                    $('#reset-password-success-msg').fadeIn();
                },
                error: function(xhr, textStatus, errorThrown){
                    $('#reset-password-error-msg').fadeIn();
                }
             });
            return false;
    });

    $("#editlabelcontact_form").validate({
            rules: {
                <?php if (!$this->vc_id) { ?>
                login: {
                  required: true,
                  minlength: 2,
                    remote: {
                        url: "/account/checklogin/",
                        type: "post",
                        data: {
                              login: function() {
                                return $("#login").val();
                              },
                              vc_id: function() {
                                return $("#vc_id").val();
                              },
                              subaccount_id: function() {
                                return $('#subaccount_id').val() || '';
                              }
                        }
                     },
                    email: true,
                },
                <?php } ?>
                contact_email: {
                  required: true,
                  email: true
                },
                contact_first_name: {
                      required: true
                    },
                contact_last_name: {
                      required: true
                    },
                contact_phone: {
                      required: true
                    },
                passwords: {
                    <?php if (!$this->vc_id) { ?>
                    required: true,
                    <?php } ?>
                    minlength: 6,
                    maxlength: 12,
                      mypassword: true
                },
                verify_password: {
                    <?php if (!$this->vc_id) { ?>
                    required: true,
                    <?php } ?>
                    equalTo: "#passwords"
                },
                subaccount_id:{
                    validateLabelAssignment: true
                },
                address_street: {maxlength: 30},
                address2: {maxlength: 30}
            },
            messages: {
                login: {
                  required: "<?=$this->escapejs($this->translate('This field is required.'))?>",
                  minlength: "<?=$this->escapejs($this->translate('Your user name must consist of at least 2 characters'))?>",
                  remote: "<?=$this->escapejs($this->translate('Email already exists on this label (including deactivated users) or is invalid'))?>",
                },
                contact_email: {
                    required: "<?=$this->escapejs($this->translate('This field is required.'))?>",
                    email: "<?=$this->escapejs($this->translate('Invalid Email'))?>",
                },
                contact_first_name: {required:"<?=$this->escapejs($this->translate('This field is required.'))?>"},
            contact_last_name: {required:"<?=$this->escapejs($this->translate('This field is required.'))?>"},
            contact_phone: {required:"<?=$this->escapejs($this->translate('This field is required.'))?>"},
            passwords: {
                required: '<?=$this->escapejs($this->translate('This field is required.'))?>',
                minlength: '<?=$this->escapejs($this->translate('Your password must be at least 6 characters long.'))?>',
                maxlength: '<?=$this->escapejs($this->translate('Your password max 12 characters long.'))?>'
            },
            verifyPassword: {
                required: "<?=$this->escapejs($this->translate('This field is required.'))?>",
                  equalTo: "<?=$this->escapejs($this->translate('New Password and Verify Password should be same.'))?>",
            },
            address_street: {maxlength:"<?php echo $this->escapejs($this->translate('should not be more than 30 characters')); ?>"},
            address2: {maxlength:"<?php echo $this->escapejs($this->translate('should not be more than 30 characters')); ?>"}
            },
            submitHandler: function(form) {
                //Check is at least one checkbox is checked
                var num_of_checkbox_checked = 0;
                $("input:checkbox").each(function(i,s){
                    if(s.checked) num_of_checkbox_checked++;
                });
                var password = $.trim($("#passwords").val());
                if(num_of_checkbox_checked==0){
                    $('#editlabelcontact_success_message').hide();
                    $('#editlabelcontact_error_message').fadeOut();
                    $('#editlabelcontact_error_message').html("<?=$this->escapejs($this->translate('Permission is Required'))?>");
                    $('#editlabelcontact_error_message').fadeIn();
                }else{
                    var labelcontact_values = $('#editlabelcontact_form').serialize();
                    $('#submit_labelcontact_form').html('<span><?=$this->escapejs($this->translate('Saving...'))?></span>');
                    $.post("/account/savelabelcontact/", labelcontact_values,
                        function(response){
                        if (response && !response.error) {
                            $("#submit_labelcontact_form").html("<span><?=($this->vc_id ? $this->escapejs($this->translate('Save User')) : $this->escapejs($this->translate('Add User')))?></span>");
                            $('#editlabelcontact_error_message').hide();
                            $('#editlabelcontact_success_message').fadeOut();
                            $('#editlabelcontact_success_message').html("<?=$this->escapejs($this->translate('User Data Saved Successfully.'))?>");
                            $('#editlabelcontact_success_message').fadeIn();
                            window.location.href = "/account/admin/";
                        }
                        else if (response.error != undefined && response.type != undefined && response.type == 'auth0') {
                            var error = response.message;
                            $('#editlabelcontact_success_message').hide();
                            $('#editlabelcontact_error_message').html("<?=$this->escapejs($this->translate('User Data Could not be Saved, '))?>" + error);
                            $('#editlabelcontact_error_message').fadeIn();
                            $("#verify_password_validation_message").fadeOut();
                            $("#submit_labelcontact_form").html("<span><?=$this->escapejs($this->translate('Save User'))?></span>");
                        }
                        else if (response.trace.verify_password != undefined && response.trace.verify_password.notSame != undefined) {
                            var error = response.trace.verify_password.notSame;
                            $('#editlabelcontact_success_message').hide();
                            $('#editlabelcontact_error_message').fadeOut();
                            $('#editlabelcontact_error_message').html("<?=$this->escapejs($this->translate('User Data Could not be Saved...'))?>");
                            $('#editlabelcontact_error_message').fadeIn();
                            if(error)
                                $("#verify_password_validation_message").html("<label class=missingForm for=verify_password>"+error+"<label>");
                            $("#submit_labelcontact_form").html("<span><?php echo ($this->vc_id ? $this->escapejs($this->translate('Save User')) : $this->escapejs($this->translate('Add User'))); ?></span>");
                        } else{
                            // default error handler.
                            $('#editlabelcontact_success_message').hide();
                            $('#editlabelcontact_error_message').fadeOut();
                            $('#editlabelcontact_error_message').html("<?=$this->escapejs($this->translate('User data could not be saved due to some error. Please try again.'))?>");
                            $('#editlabelcontact_error_message').fadeIn();
                            $("#submit_labelcontact_form").html("<span><?php echo ($this->vc_id ? $this->escapejs($this->translate('Save User')) : $this->escapejs($this->translate('Add User'))); ?></span>");
                        }
                    }, "json");
                }
                return false;
            },
            onkeyup: false,
        errorClass: "missingForm",
        errorElement: "label",
        errorPlacement: function(error, element) {
            error.appendTo(element.next("div"));
        },
        highlight: function(element, errorClass) {
            $(element).removeClass(errorClass);
        }
        });

    $.validator.addMethod('validateLabelAssignment', function(value, element) {
        //If creating a DA allow without label Assignment
        if($("input[@name=label_assignment]:checked").val() == "N")
            return true;
        //If selected to do label assignment then one one of the dropdown option must be selected
        if(value != undefined && value != "")
            return true;

        return false;
    },'Subaccount not selected.');

    $.validator.addMethod('mypassword', function(value, element) {
        return this.optional(element) || /^(?=.*\d)(?=.*[a-z]).{6,12}$/i.test(value);

    },
    'Password must be at least six (6) characters with at least one (1) digit.');

    <?php if (!$this->vc_id && Zend_Registry :: get('UserObj')->isAllowed('', '', 'managelabels')) { ?>
        hideMarketingPermission();
        hideAdvertisingPermission();
        $('#label_assignment-Y').change( function() {
            hideMarketingPermission();
            hideAdvertisingPermission();
        });

        $('#label_assignment-N').change( function() {
            showMarketingPermission();
            showAdvertisingPermission();
            $('#subaccount_id').val(''); // reset subaccount dropdown.
        });
    <?php } ?>

    // Ensure that Advertising won't appear when Marketing is disabled
    var marketingRoleId = $('#label_role_id_2');
    if (!marketingRoleId.length) {
        hideAdvertisingPermission();
    }

});

function hideMarketingPermission() {
    $('#role_id_2').hide();
    $('#label_role_id_2').hide();
    $('#line_role_id_2').hide();
    $('input[name=role_id_2]').hide();
}

function hideAdvertisingPermission() {
    $('#role_id_7').hide();
    $('#label_role_id_7').hide();
    $('#line_role_id_7').hide();
    $('input[name=role_id_7]').hide();
}

function showMarketingPermission() {
    $('#role_id_2').show();
    $('#label_role_id_2').show();
    $('#line_role_id_2').show();
    $('input[name=role_id_2]').show();
}

function showAdvertisingPermission() {
    $('#role_id_7').show();
    $('#label_role_id_7').show();
    $('#line_role_id_7').show();
    $('input[name=role_id_7]').show();
}

/** pre-color and pre-check the checkboxes on page load */
function loadCheckboxes(){
    <?php if (!$this->vc_id) { ?>
        $("#<?=$this->vendor_roles['Administrator']?>").attr("checked","checked");
        $("#<?=$this->vendor_roles['Administrator']?>_list_item").addClass("selected");
    <?php } ?>

    if ($('#<?=$this->vendor_roles['Administrator']?>').is(':checked')){
        $("#<?=$this->vendor_roles['Administrator']?>_list_item").attr("class","selected");
        processCheckBoxes();
    } else {
        $("input:checkbox").each(function() {
            var checkbox_id = $(this).attr('id');
            if (checkbox_id != "<?=$this->vendor_roles['Administrator']?>") {
                if ($(this).is(':checked')){
                    $("#"+checkbox_id+"_list_item").attr("class","selected");
                }
            }
        });
    }
}

function processCheckBoxes(){
    if ($('#<?=$this->vendor_roles['Administrator']?>').is(':checked')){
        $("input:checkbox").each(function() {
            var checkbox_id = $(this).attr('id');
            if (checkbox_id != "<?=$this->vendor_roles['Administrator']?>") {
                $("#"+checkbox_id+"_list_item").attr("class","disabled");
                $("#"+checkbox_id).attr("checked",false);
                $("#"+checkbox_id).attr("disabled","true");
                $('div.well.checkbox').addClass('disabled');
            }
        });
    } else {
        $("input:checkbox").each(function() {
            var checkbox_id = $(this).attr('id');
            if (checkbox_id != "<?=$this->vendor_roles['Administrator']?>" && $("label:[for="+checkbox_id+"]").css("display") != "none") {
                $("#"+checkbox_id+"_list_item").attr("class","selected");
                $("#"+checkbox_id).attr("disabled","");
                $("#"+checkbox_id).attr("checked",true);
                $('div.checkbox').removeClass('disabled');
            }
        });
    }
}

/** capture checkbox click for UI updates  */
$("input:checkbox").click(function(){
    if("#<?=$this->vendor_roles['Administrator']?>_list_item" == "#"+$(this).attr('id')+"_list_item"){
        processCheckBoxes();
    }
    var selectedClass = "";
    if ($("#"+$(this).attr('id')+"_list_item").attr('class') !='selected'){
        selectedClass = "selected";
    }
    $("#"+$(this).attr('id')+"_list_item").attr('class', selectedClass);
});

/** on load process checkboxes*/
loadCheckboxes();
</script>
