<?php

namespace ProjectManagement\prjProjectManagement;

// Page object
$VuserSearch = &$Page;
?>
<script>
var currentTable = <?= JsonEncode($Page->toClientVar()) ?>;
ew.deepAssign(ew.vars, { tables: { vuser: currentTable } });
var currentPageID = ew.PAGE_ID = "search";
var currentForm;
var fvusersearch, currentSearchForm, currentAdvancedSearchForm;
loadjs.ready(["wrapper", "head"], function () {
    let $ = jQuery,
        fields = currentTable.fields;

    // Form object for search
    let form = new ew.FormBuilder()
        .setId("fvusersearch")
        .setPageId("search")
<?php if ($Page->IsModal && $Page->UseAjaxActions) { ?>
        .setSubmitWithFetch(true)
<?php } ?>

        // Add fields
        .addFields([
            ["EmployeeID", [ew.Validators.integer], fields.EmployeeID.isInvalid],
            ["FirstName", [], fields.FirstName.isInvalid],
            ["LastName", [], fields.LastName.isInvalid],
            ["FullName", [], fields.FullName.isInvalid],
            ["_Email", [], fields._Email.isInvalid],
            ["WhatsAppNumber", [], fields.WhatsAppNumber.isInvalid],
            ["Department", [], fields.Department.isInvalid],
            ["Position", [], fields.Position.isInvalid],
            ["_Username", [], fields._Username.isInvalid]
        ])
        // Validate form
        .setValidate(
            async function () {
                if (!this.validateRequired)
                    return true; // Ignore validation
                let fobj = this.getForm();

                // Validate fields
                if (!this.validateFields())
                    return false;

                // Call Form_CustomValidate event
                if (!(await this.customValidate?.(fobj) ?? true)) {
                    this.focus();
                    return false;
                }
                return true;
            }
        )

        // Form_CustomValidate
        .setCustomValidate(
            function (fobj) { // DO NOT CHANGE THIS LINE! (except for adding "async" keyword)!
                    // Your custom validation code here, return false if invalid.
                    return true;
                }
        )

        // Use JavaScript validation or not
        .setValidateRequired(ew.CLIENT_VALIDATE)

        // Dynamic selection lists
        .setQueryBuilderLists({
        })
        .build();
    window[form.id] = form;
<?php if ($Page->IsModal) { ?>
    currentAdvancedSearchForm = form;
<?php } else { ?>
    currentForm = form;
<?php } ?>
    loadjs.done(form.id);
});
</script>
<script>
loadjs.ready("head", function () {
    // Write your table-specific client script here, no need to add script tags.
});
</script>
<?php $Page->showPageHeader(); ?>
<?php
$Page->showMessage();
?>
<form name="fvusersearch" id="fvusersearch" class="<?= $Page->FormClassName ?>" action="<?= HtmlEncode(GetUrl("vuserlist")) ?>" method="post" autocomplete="off">
<?php if (Config("CHECK_TOKEN")) { ?>
<input type="hidden" name="<?= $TokenNameKey ?>" value="<?= $TokenName ?>"><!-- CSRF token name -->
<input type="hidden" name="<?= $TokenValueKey ?>" value="<?= $TokenValue ?>"><!-- CSRF token value -->
<?php } ?>
<input type="hidden" name="t" value="vuser">
<input type="hidden" name="action" id="action" value="search">
<?php if ($Page->IsModal && $Page->UseAjaxActions) { ?>
<input type="hidden" name="modal" value="1">
<?php } ?>
<input type="hidden" name="rules" value="<?= HtmlEncode($Page->getSessionRules()) ?>">
<template id="tpx_vuser_EmployeeID" class="vusersearch"><span id="el_vuser_EmployeeID" class="ew-search-field ew-search-field-single">
<input type="<?= $Page->EmployeeID->getInputTextType() ?>" name="x_EmployeeID" id="x_EmployeeID" data-table="vuser" data-field="x_EmployeeID" value="<?= $Page->EmployeeID->EditValue ?>" placeholder="<?= HtmlEncode($Page->EmployeeID->getPlaceHolder()) ?>" data-format-pattern="<?= HtmlEncode($Page->EmployeeID->formatPattern()) ?>"<?= $Page->EmployeeID->editAttributes() ?>>
<div class="invalid-feedback"><?= $Page->EmployeeID->getErrorMessage(false) ?></div>
</span></template>
<template id="tpx_vuser_FirstName" class="vusersearch"><span id="el_vuser_FirstName" class="ew-search-field ew-search-field-single">
<input type="<?= $Page->FirstName->getInputTextType() ?>" name="x_FirstName" id="x_FirstName" data-table="vuser" data-field="x_FirstName" value="<?= $Page->FirstName->EditValue ?>" size="30" maxlength="100" placeholder="<?= HtmlEncode($Page->FirstName->getPlaceHolder()) ?>" data-format-pattern="<?= HtmlEncode($Page->FirstName->formatPattern()) ?>"<?= $Page->FirstName->editAttributes() ?>>
<div class="invalid-feedback"><?= $Page->FirstName->getErrorMessage(false) ?></div>
</span></template>
<template id="tpx_vuser_LastName" class="vusersearch"><span id="el_vuser_LastName" class="ew-search-field ew-search-field-single">
<input type="<?= $Page->LastName->getInputTextType() ?>" name="x_LastName" id="x_LastName" data-table="vuser" data-field="x_LastName" value="<?= $Page->LastName->EditValue ?>" size="30" maxlength="100" placeholder="<?= HtmlEncode($Page->LastName->getPlaceHolder()) ?>" data-format-pattern="<?= HtmlEncode($Page->LastName->formatPattern()) ?>"<?= $Page->LastName->editAttributes() ?>>
<div class="invalid-feedback"><?= $Page->LastName->getErrorMessage(false) ?></div>
</span></template>
<template id="tpx_vuser_FullName" class="vusersearch"><span id="el_vuser_FullName" class="ew-search-field ew-search-field-single">
<input type="<?= $Page->FullName->getInputTextType() ?>" name="x_FullName" id="x_FullName" data-table="vuser" data-field="x_FullName" value="<?= $Page->FullName->EditValue ?>" size="30" maxlength="201" placeholder="<?= HtmlEncode($Page->FullName->getPlaceHolder()) ?>" data-format-pattern="<?= HtmlEncode($Page->FullName->formatPattern()) ?>"<?= $Page->FullName->editAttributes() ?>>
<div class="invalid-feedback"><?= $Page->FullName->getErrorMessage(false) ?></div>
</span></template>
<template id="tpx_vuser__Email" class="vusersearch"><span id="el_vuser__Email" class="ew-search-field ew-search-field-single">
<input type="<?= $Page->_Email->getInputTextType() ?>" name="x__Email" id="x__Email" data-table="vuser" data-field="x__Email" value="<?= $Page->_Email->EditValue ?>" size="30" maxlength="100" placeholder="<?= HtmlEncode($Page->_Email->getPlaceHolder()) ?>" data-format-pattern="<?= HtmlEncode($Page->_Email->formatPattern()) ?>"<?= $Page->_Email->editAttributes() ?>>
<div class="invalid-feedback"><?= $Page->_Email->getErrorMessage(false) ?></div>
</span></template>
<template id="tpx_vuser_WhatsAppNumber" class="vusersearch"><span id="el_vuser_WhatsAppNumber" class="ew-search-field ew-search-field-single">
<input type="<?= $Page->WhatsAppNumber->getInputTextType() ?>" name="x_WhatsAppNumber" id="x_WhatsAppNumber" data-table="vuser" data-field="x_WhatsAppNumber" value="<?= $Page->WhatsAppNumber->EditValue ?>" size="30" maxlength="100" placeholder="<?= HtmlEncode($Page->WhatsAppNumber->getPlaceHolder()) ?>" data-format-pattern="<?= HtmlEncode($Page->WhatsAppNumber->formatPattern()) ?>"<?= $Page->WhatsAppNumber->editAttributes() ?>>
<div class="invalid-feedback"><?= $Page->WhatsAppNumber->getErrorMessage(false) ?></div>
</span></template>
<template id="tpx_vuser_Department" class="vusersearch"><span id="el_vuser_Department" class="ew-search-field ew-search-field-single">
<input type="<?= $Page->Department->getInputTextType() ?>" name="x_Department" id="x_Department" data-table="vuser" data-field="x_Department" value="<?= $Page->Department->EditValue ?>" size="30" maxlength="100" placeholder="<?= HtmlEncode($Page->Department->getPlaceHolder()) ?>" data-format-pattern="<?= HtmlEncode($Page->Department->formatPattern()) ?>"<?= $Page->Department->editAttributes() ?>>
<div class="invalid-feedback"><?= $Page->Department->getErrorMessage(false) ?></div>
</span></template>
<template id="tpx_vuser_Position" class="vusersearch"><span id="el_vuser_Position" class="ew-search-field ew-search-field-single">
<input type="<?= $Page->Position->getInputTextType() ?>" name="x_Position" id="x_Position" data-table="vuser" data-field="x_Position" value="<?= $Page->Position->EditValue ?>" size="30" maxlength="100" placeholder="<?= HtmlEncode($Page->Position->getPlaceHolder()) ?>" data-format-pattern="<?= HtmlEncode($Page->Position->formatPattern()) ?>"<?= $Page->Position->editAttributes() ?>>
<div class="invalid-feedback"><?= $Page->Position->getErrorMessage(false) ?></div>
</span></template>
<template id="tpx_vuser__Username" class="vusersearch"><span id="el_vuser__Username" class="ew-search-field ew-search-field-single">
<input type="<?= $Page->_Username->getInputTextType() ?>" name="x__Username" id="x__Username" data-table="vuser" data-field="x__Username" value="<?= $Page->_Username->EditValue ?>" size="30" maxlength="100" placeholder="<?= HtmlEncode($Page->_Username->getPlaceHolder()) ?>" data-format-pattern="<?= HtmlEncode($Page->_Username->formatPattern()) ?>"<?= $Page->_Username->editAttributes() ?>>
<div class="invalid-feedback"><?= $Page->_Username->getErrorMessage(false) ?></div>
</span></template>
<div id="vuser_query_builder" class="query-builder mb-3"></div>
<div class="btn-group mb-3 query-btn-group"></div>
<button type="button" id="btn-view-rules" class="btn btn-primary d-none disabled" title="<?= HtmlEncode($Language->phrase("View", true)) ?>"><i class="fa-solid fa-eye ew-icon"></i></button>
<button type="button" id="btn-clear-rules" class="btn btn-primary d-none disabled" title="<?= HtmlEncode($Language->phrase("Clear", true)) ?>"><i class="fa-solid fa-xmark ew-icon"></i></button>
<script>
// Filter builder
loadjs.ready(["wrapper", "head"], () => {
    let filters = [
            {
                id: "EmployeeID",
                type: "integer",
                label: currentTable.fields.EmployeeID.caption,
                operators: currentTable.fields.EmployeeID.clientSearchOperators,
                default_operator: "equal",
                input: ew.getQueryBuilderFilterInput(),
                validation: ew.getQueryBuilderFilterValidation(fvusersearch.fields.EmployeeID.validators),
                data: {
                    format: currentTable.fields.EmployeeID.clientFormatPattern
                }
            },
            {
                id: "FirstName",
                type: "string",
                label: currentTable.fields.FirstName.caption,
                operators: currentTable.fields.FirstName.clientSearchOperators,
                default_operator: "contains",
                input: ew.getQueryBuilderFilterInput(),
                value_separator: ew.IN_OPERATOR_VALUE_SEPARATOR,
                validation: ew.getQueryBuilderFilterValidation(fvusersearch.fields.FirstName.validators),
                data: {
                    format: currentTable.fields.FirstName.clientFormatPattern
                }
            },
            {
                id: "LastName",
                type: "string",
                label: currentTable.fields.LastName.caption,
                operators: currentTable.fields.LastName.clientSearchOperators,
                default_operator: "contains",
                input: ew.getQueryBuilderFilterInput(),
                value_separator: ew.IN_OPERATOR_VALUE_SEPARATOR,
                validation: ew.getQueryBuilderFilterValidation(fvusersearch.fields.LastName.validators),
                data: {
                    format: currentTable.fields.LastName.clientFormatPattern
                }
            },
            {
                id: "FullName",
                type: "string",
                label: currentTable.fields.FullName.caption,
                operators: currentTable.fields.FullName.clientSearchOperators,
                default_operator: "contains",
                input: ew.getQueryBuilderFilterInput(),
                value_separator: ew.IN_OPERATOR_VALUE_SEPARATOR,
                validation: ew.getQueryBuilderFilterValidation(fvusersearch.fields.FullName.validators),
                data: {
                    format: currentTable.fields.FullName.clientFormatPattern
                }
            },
            {
                id: "_Email",
                type: "string",
                label: currentTable.fields._Email.caption,
                operators: currentTable.fields._Email.clientSearchOperators,
                default_operator: "contains",
                input: ew.getQueryBuilderFilterInput(),
                value_separator: ew.IN_OPERATOR_VALUE_SEPARATOR,
                validation: ew.getQueryBuilderFilterValidation(fvusersearch.fields._Email.validators),
                data: {
                    format: currentTable.fields._Email.clientFormatPattern
                }
            },
            {
                id: "WhatsAppNumber",
                type: "string",
                label: currentTable.fields.WhatsAppNumber.caption,
                operators: currentTable.fields.WhatsAppNumber.clientSearchOperators,
                default_operator: "contains",
                input: ew.getQueryBuilderFilterInput(),
                value_separator: ew.IN_OPERATOR_VALUE_SEPARATOR,
                validation: ew.getQueryBuilderFilterValidation(fvusersearch.fields.WhatsAppNumber.validators),
                data: {
                    format: currentTable.fields.WhatsAppNumber.clientFormatPattern
                }
            },
            {
                id: "Department",
                type: "string",
                label: currentTable.fields.Department.caption,
                operators: currentTable.fields.Department.clientSearchOperators,
                default_operator: "contains",
                input: ew.getQueryBuilderFilterInput(),
                value_separator: ew.IN_OPERATOR_VALUE_SEPARATOR,
                validation: ew.getQueryBuilderFilterValidation(fvusersearch.fields.Department.validators),
                data: {
                    format: currentTable.fields.Department.clientFormatPattern
                }
            },
            {
                id: "Position",
                type: "string",
                label: currentTable.fields.Position.caption,
                operators: currentTable.fields.Position.clientSearchOperators,
                default_operator: "contains",
                input: ew.getQueryBuilderFilterInput(),
                value_separator: ew.IN_OPERATOR_VALUE_SEPARATOR,
                validation: ew.getQueryBuilderFilterValidation(fvusersearch.fields.Position.validators),
                data: {
                    format: currentTable.fields.Position.clientFormatPattern
                }
            },
            {
                id: "_Username",
                type: "string",
                label: currentTable.fields._Username.caption,
                operators: currentTable.fields._Username.clientSearchOperators,
                default_operator: "contains",
                input: ew.getQueryBuilderFilterInput(),
                value_separator: ew.IN_OPERATOR_VALUE_SEPARATOR,
                validation: ew.getQueryBuilderFilterValidation(fvusersearch.fields._Username.validators),
                data: {
                    format: currentTable.fields._Username.clientFormatPattern
                }
            },
        ],
        $ = jQuery,
        $qb = $("#vuser_query_builder"),
        args = {},
        rules = ew.parseJson($("#fvusersearch input[name=rules]").val()),
        queryBuilderOptions = Object.assign({}, ew.queryBuilderOptions),
        allowViewRules = queryBuilderOptions.allowViewRules,
        allowClearRules = queryBuilderOptions.allowClearRules,
        hasRules = group => Array.isArray(group?.rules) && group.rules.length > 0,
        getRules = () => $qb.queryBuilder("getRules", { skip_empty: true }),
        getSql = () => $qb.queryBuilder("getSQL", false, false, rules)?.sql;
    delete queryBuilderOptions.allowViewRules;
    delete queryBuilderOptions.allowClearRules;
    args.options = ew.deepAssign({
        plugins: Object.assign({}, ew.queryBuilderPlugins),
        lang: ew.language.phrase("querybuilderjs"),
        select_placeholder: ew.language.phrase("PleaseSelect"),
        inputs_separator: `<div class="d-inline-flex ms-2 me-2">${ew.language.phrase("AND")}</div>`, // For "between"
        filters,
        rules
    }, queryBuilderOptions);
    $qb.trigger("querybuilder", [args]);
    $qb.queryBuilder(args.options).on("rulesChanged.queryBuilder", () => {
        let rules = getRules();
        !ew.DEBUG || console.log(rules, getSql());
        $("#btn-reset, #btn-action, #btn-clear-rules, #btn-view-rules").toggleClass("disabled", !rules);
    }).on("afterCreateRuleInput.queryBuilder", function(e, rule) {
        let select = rule.$el.find(".rule-value-container").find("selection-list, select")[0];
        if (select) { // Selection list
            let id = select.dataset.field.replace("^x_", ""),
                form = ew.forms.get(select);
            form.updateList(select, undefined, undefined, true); // Update immediately
        }
    });
    $("#fvusersearch").on("beforesubmit", function () {
        this.rules.value = JSON.stringify(getRules());
    });
    $("#btn-reset").toggleClass("d-none", false).on("click", () => {
        hasRules(rules) ? $qb.queryBuilder("setRules", rules) : $qb.queryBuilder("reset");
        return false;
    });
    $("#btn-action").toggleClass("d-none", false);
    if (allowClearRules) {
        $("#btn-clear-rules").appendTo(".query-btn-group").removeClass("d-none").on("click", () => $qb.queryBuilder("reset"));
    }
    if (allowViewRules) {
        $("#btn-view-rules").appendTo(".query-btn-group").removeClass("d-none").on("click", () => {
            let rules = getRules();
            if (hasRules(rules)) {
                let sql = getSql();
                ew.alert(sql ? '<pre class="text-start fs-6">' + sql + '</pre>' : '', "dark");
                !ew.DEBUG || console.log(rules, sql);
            } else {
                ew.alert(ew.language.phrase("EmptyLabel"));
            }
        });
    }
    $(".query-btn-group").toggleClass(".mb-3", $(".query-btn-group").find(".btn:not(.d-none)").length);
    if (hasRules(rules)) { // Enable buttons if rules exist initially
        $("#btn-reset, #btn-action, #btn-clear-rules, #btn-view-rules").removeClass("disabled");
    }
});
</script>
<?= $Page->IsModal ? '<template class="ew-modal-buttons">' : '<div class="row ew-buttons">' ?><!-- buttons .row -->
    <div class="<?= $Page->OffsetColumnClass ?>"><!-- buttons offset -->
        <button class="btn btn-primary ew-btn d-none disabled" name="btn-action" id="btn-action" type="submit" form="fvusersearch" formaction="<?= HtmlEncode(GetUrl("vuserlist")) ?>" data-ajax="<?= $Page->UseAjaxActions ? "true" : "false" ?>"><?= $Language->phrase("Search") ?></button>
        <?php if ($Page->IsModal) { ?>
        <button class="btn btn-default ew-btn" name="btn-cancel" id="btn-cancel" type="button" form="fvusersearch"><?= $Language->phrase("Cancel") ?></button>
        <?php } else { ?>
        <button class="btn btn-default ew-btn d-none disabled" name="btn-reset" id="btn-reset" type="button" form="fvusersearch" data-ew-action="reload"><?= $Language->phrase("Reset") ?></button>
        <?php } ?>
    </div><!-- /buttons offset -->
<?= $Page->IsModal ? "</template>" : "</div>" ?><!-- /buttons .row -->
</form>
<?php
$Page->showPageFooter();
echo GetDebugMessage();
?>
<script>
// Field event handlers
loadjs.ready("head", function() {
    ew.addEventHandlers("vuser");
});
</script>
<script>
loadjs.ready("load", function () {
    // Write your table-specific startup script here, no need to add script tags.
});
</script>
