<?php /** @noinspection PhpUndefinedNamespaceInspection PhpUndefinedClassInspection PhpUndefinedMethodInspection */
namespace filtersearch;

use humhub\libs\Html;
use humhub\libs\Iso3166Codes;
use humhub\modules\user\models\Group;
use humhub\modules\user\models\User;
use Yii;
use yii\db\Query;

function base64_url_encode($input)
{
    return strtr(base64_encode($input), '+/=', '._-');
}

function base64_url_decode($input)
{
    return base64_decode(strtr($input, '._-', '+/='), TRUE);
}

function is_group_member($group_id)
{
    if (Yii::$app->user->isGuest) {
        return false;
    }
    $queried_group = Group::findOne($group_id);
    $current_user = Yii::$app->user->getIdentity();
    return $queried_group->isMember($current_user);
}

// security check
$csvexport_gid = 6;
$csv_export_allowed = is_group_member($csvexport_gid);

// list field config
$list_field_config = [
    "Country" => [
        "name" => "Land",
    ],
];

$field_value_mappers = [
    "country" => function($country_code) {
        if ($country_code == "Keine Angabe"){
            return $country_code;
        } else if ($country_code == "US"){
            return "USA";
        } else {
            return iso3166Codes::country($country_code);
        }
    },
];

// export field config name & status (unchecked/disabled/checked (default))
$export_field_config = [
    "id" => [
        "name" => "ID",
        "status" => "unchecked",
    ],
    "guid" => [
        "name" => "GUID",
        "status" => "disabled",
    ],
    "status" => [
        "name" => "Status",
        "status" => "checked",
    ],
    "username" => [
        "name" => "Username",
        "status" => "checked",
    ],
    "email" => [
        "name" => "Email",
        "status" => "disabled",
    ],
    "auth_mode" => [
        "status" => "disabled",
    ],
    "language" => [
        "status" => "disabled",
    ],
    "created_at" => [
        "status" => "disabled",
    ],
    "created_by" => [
        "status" => "disabled",
    ],
    "updated_at" => [
        "status" => "disabled",
    ],
    "updated_by" => [
        "status" => "disabled",
    ],
    "last_login" => [
        "status" => "disabled",
    ],
    "visibility" => [
        "status" => "disabled",
    ],
    "time_zone" => [
        "status" => "disabled",
    ],
    "contentcontainer_id" => [
        "status" => "disabled",
    ],
    "authclient_id" => [
        "status" => "disabled",
    ],
    "user_id" => [
        "status" => "disabled",
    ],
    "firstname" => [
        "name" => "Vorname",
        "status" => "checked",
    ],
    "lastname" => [
        "name" => "Nachname",
        "status" => "checked",
    ],
    "title" => [
        "name" => "Titel",
        "status" => "checked",
    ],
    "gender" => [
        "name" => "Geschlecht",
        "status" => "checked",
    ],
    "country" => [
        "name" => "Land",
        "status" => "checked",
    ],
    "street" => [
        "name" => "Straße",
        "status" => "checked",
    ],
    "zip" => [
        "name" => "PLZ",
        "status" => "checked",
    ],
    "city" => [
        "name" => "Stadt",
        "status" => "checked",
    ],
    "state" => [
        "name" => "Bundesland",
        "status" => "checked",
    ],
    "birthday_hide_year" => [
        "status" => "disabled",
    ],
    "birthday" => [
        "name" => "Geburtstag",
        "status" => "checked",
    ],
    "about" => [
        "status" => "unchecked",
    ],
    "phone_private" => [
        "name" => "Telefon, privat",
        "status" => "checked",
    ],
    "phone_work" => [
        "name" => "Telefon, berufl",
        "status" => "checked",
    ],
    "mobile" => [
        "name" => "Telefon, mobil",
        "status" => "checked",
    ],
    "fax" => [
        "name" => "Fax",
        "status" => "checked",
    ],
    "im_skype" => [
        "status" => "disabled",
    ],
    "im_msn" => [
        "status" => "disabled",
    ],
    "im_xmpp" => [
        "status" => "disabled",
    ],
    "url" => [
        "name" => "Webseite",
        "status" => "checked",
    ],
    "url_facebook" => [
        "name" => "Facebook",
        "status" => "unchecked",
    ],
    "url_linkedin" => [
        "name" => "LinkedIn",
        "status" => "unchecked",
    ],
    "url_xing" => [
        "name" => "Xing",
        "status" => "unchecked",
    ],
    "url_youtube" => [
        "status" => "disabled",
    ],
    "url_vimeo" => [
        "status" => "disabled",
    ],
    "url_flickr" => [
        "status" => "disabled",
    ],
    "url_myspace" => [
        "status" => "disabled",
    ],
    "url_googleplus" => [
        "status" => "disabled",
    ],
    "url_twitter" => [
        "status" => "disabled",
    ],
    "jobs" => [
        "name" => "Ehemalige Ämter",
        "status" => "unchecked",
    ],
    "prev_chargen" => [
        "name" => "Ehemalige Chargen",
        "status" => "unchecked",
    ],
    "generation" => [
        "name" => "Generation",
        "status" => "unchecked",
    ],
    "partien" => [
        "name" => "Partien",
        "status" => "unchecked",
    ],
    "gk_chargen" => [
        "name" => "Geklammerte Chargen",
        "status" => "unchecked",
    ],
    "honor" => [
        "name" => "Ehrungen",
        "status" => "unchecked",
    ],
    "couleur_other" => [
        "name" => "Andere Verbindungen",
        "status" => "unchecked",
    ],
    "frat_sons" => [
        "name" => "Leibsöhne",
        "status" => "unchecked",
    ],
    "frat_father" => [
        "name" => "Leibvater",
        "status" => "unchecked",
    ],
    "partner" => [
        "name" => "Partner",
        "status" => "unchecked",
    ],
    "languages" => [
        "name" => "Sprachen",
        "status" => "unchecked",
    ],
    "email_private" => [
        "name" => "Email, privat",
        "status" => "checked",
    ],
    "job_email" => [
        "name" => "Email, berufl",
        "status" => "checked",
    ],
    "job_mobile" => [
        "name" => "Telefon mobil, berufl",
        "status" => "checked",
    ],
    "career" => [
        "name" => "Lebenslauf",
        "status" => "unchecked",
    ],
    "current_company" => [
        "name" => "Aktuelle Firma",
        "status" => "checked",
    ],
    "current_industry" => [
        "name" => "Aktuelle Branche",
        "status" => "checked",
    ],
    "current_company_website" => [
        "name" => "Firmenwebseite",
        "status" => "unchecked",
    ],
    "univ_faculty" => [
        "name" => "Studienrichtung",
        "status" => "checked",
    ],
    "date_of_exit" => [
        "name" => "Austritts- / Todesdatum",
        "status" => "unchecked",
    ],
    "place_of_birth" => [
        "name" => "Geburtsort",
        "status" => "checked",
    ],
    "place_of_death" => [
        "name" => "Todesort",
        "status" => "unchecked",
    ],
    "acc_date" => [
        "name" => "Acceptionsjahr",
        "status" => "unchecked",
    ],
    "rec_date" => [
        "name" => "Receptionsjahr",
        "status" => "unchecked",
    ],
    "phil_date" => [
        "name" => "Philistrierungsjahr",
        "status" => "checked",
    ],
    "current_company_address" => [
        "name" => "Firmenadresse",
        "status" => "unchecked",
    ],
    "register_number" => [
        "name" => "Verzeichnisnummer",
        "status" => "unchecked",
    ],
    "idc" => [
        "name" => "Inh. d. Corpsschleife",
        "status" => "unchecked",
    ],
    "chargen_multi_other_selection" => [
        "status" => "disabled",
    ],
    "chargen_multi" => [
        "name" => "Aktuelle Ämter",
        "status" => "unchecked",
    ],
    "kid1givenname" => [
        "name" => "Vorname Kind 1",
        "status" => "unchecked",
    ],
    "kid2givenname" => [
        "name" => "Vorname Kind 2",
        "status" => "unchecked",
    ],
    "kid3givenname" => [
        "name" => "Vorname Kind 3",
        "status" => "unchecked",
    ],
    "kid4givenname" => [
        "name" => "Vorname Kind 4",
        "status" => "unchecked",
    ],
    "kid5givenname" => [
        "name" => "Vorname Kind 5",
        "status" => "unchecked",
    ],
    "kid1gender" => [
        "name" => "Geschlecht Kind 1",
        "status" => "unchecked",
    ],
    "kid2gender" => [
        "name" => "Geschlecht Kind 2",
        "status" => "unchecked",
    ],
    "kid3gender" => [
        "name" => "Geschlecht Kind 3",
        "status" => "unchecked",
    ],
    "kid4gender" => [
        "name" => "Geschlecht Kind 4",
        "status" => "unchecked",
    ],
    "kid5gender" => [
        "name" => "Geschlecht Kind 5",
        "status" => "unchecked",
    ],
    "kid1birthday" => [
        "name" => "Geburtsdatum Kind 1",
        "status" => "unchecked",
    ],
    "kid2birthday" => [
        "name" => "Geburtsdatum Kind 2",
        "status" => "unchecked",
    ],
    "kid3birthday" => [
        "name" => "Geburtsdatum Kind 3",
        "status" => "unchecked",
    ],
    "kid4birthday" => [
        "name" => "Geburtsdatum Kind 4",
        "status" => "unchecked",
    ],
    "kid5birthday" => [
        "name" => "Geburtsdatum Kind 5",
        "status" => "unchecked",
    ],
    "kids_markdown" => [
        "name" => "Kinder - Markdown",
        "status" => "disabled",
    ],
];

$is_disabled = function ($field_config) {
    return isset($field_config["status"]) && $field_config["status"] === "disabled";
};

$is_unchecked = function ($field_config) {
    return isset($field_config["status"]) && $field_config["status"] === "unchecked";
};

$get_display_name = function ($field_config, $field_name) {
    if (isset($field_config[$field_name])) {
        $this_field_config = $field_config[$field_name];
        if (isset($this_field_config["name"])) {
            return $this_field_config["name"];
        }
    }
    return $field_name;
};

// only one of these is true
$do_data_output = false;
$do_list_output = false;
$do_export_output = false;
if (isset($_GET["output"])) {
    if ($_GET["output"] == "data") {
        $do_data_output = true;
    } elseif ($_GET["output"] == "export") {
        $do_export_output = true;
    } elseif ($_GET["output"] == "default") {
        $do_list_output = true;
    }
} else {
    $do_list_output = true;
}

function remapFieldValueIfNeeded($field_internal_name, $internal_value, $field_value_mappers) {
    if (array_key_exists($field_internal_name, $field_value_mappers)){
        $value_mapper = $field_value_mappers[$field_internal_name];
        return call_user_func($value_mapper, $internal_value);
    } else {
        return $internal_value;
    }
}

function getDataSelect()
{
    $data_select_defaults = [
        "offset" => 0,
    ];
    $data_select = [];
    if (isset($_GET["dataselect"])) {
        $data_select = (array)json_decode(base64_url_decode($_GET["dataselect"]));
    }
    return array_merge($data_select_defaults, $data_select);
}

function queryWhere($data_select, $query)
{
    $field_null_selection = [];
    $field_selection = [];
    // key: column and value as json
    // item: checked true|false
    foreach ($data_select as $key => $item) {
        $kvjson = base64_url_decode($key);
        if ($kvjson !== FALSE && $item) {
            $kv = json_decode($kvjson);
            if (isset($kv)) {
                if ($kv->value === "Keine Angabe") {
                    $field_null_selection[$kv->field] = true;
                } elseif (isset($field_selection[$kv->field])) {
                    $field_selection[$kv->field][] = $kv->value;
                } else {
                    $field_selection[$kv->field] = [$kv->value];
                }
            }
        }
    }

    function translateLocation($field)
    {
        if ($field == "location") {
            return "CONCAT(COALESCE(profile.zip, '00000'), ' ', COALESCE(profile.city, 'Keine Angabe'))";
        } else {
            return "profile." . $field;
        }
    }

    $first = true;
    foreach ($field_null_selection as $field => &$may_be_null) {
        if (!isset($field_selection[$field]) && $may_be_null) {
            $where_array = [translateLocation($field) => null];
            if ($first) {
                $query->where($where_array);
                $first = false;
            } else {
                $query->andWhere($where_array);
            }
        }
    }
    foreach ($field_selection as $field => &$values) {
        $translated_field = translateLocation($field);

        $where_array = ['in', $translated_field, $values];
        if (isset($field_null_selection[$field]) && $field_null_selection[$field]) {
            $where_array = ['or', $where_array, [$translated_field => null]];
        }

        if ($first) {
            $query->where($where_array);
            $first = false;
        } else {
            $query->andWhere($where_array);
        }
    }
}

if ($do_data_output) {
    $data_select = getDataSelect();

    $limit = 100;
    $users_query = User::find()
        ->addSelect(["*", "profile.*"])
        ->joinWith("profile")
        ->active()
        ->orderBy("lastname")
        ->offset($data_select["offset"])
        ->limit($limit);

    queryWhere($data_select, $users_query);

    $count = $users_query->count();

    $users = [];
    foreach ($users_query->all() as &$user) {
        $users[] = [
            "userName" => $user->displayName,
            "profilePageURL" => $user->getUrl(),
            "profileImageURL" => $user->getProfileImage()->getUrl(),
        ];
    }

    echo base64_encode(json_encode([
        "limit" => $limit,
        "count" => (int)$count,
        "content" => $users,
    ]));
}

if ($do_list_output) {
    $profile_fields_to_filter = [
        "country",
        "status",
        "current_industry",
        "current_company",
        "univ_faculty",
    ];

    $profile_fields_query = new Query;
    $profile_fields_query->select("id, internal_name, title, field_type_config")
        ->from("profile_field")
        ->where(['in', 'internal_name', $profile_fields_to_filter]); // special yii query builder syntax

    $profile_fields = $profile_fields_query->all();

    foreach ($profile_fields as $id => $field) {
        $decoded = json_decode($field["field_type_config"]);
        if (isset($decoded->options)) {
            $splitted_options = preg_split("/[\r\n]+/", $decoded->options);
            $profile_fields[$id]["options"] = ["Keine Angabe"];
            foreach ($splitted_options as $option) {
                $out = preg_split("/=>/", $option);
                $profile_fields[$id]["options"][$out[0]] = $out[1];
            }
        } else {
            $profile_field_options_query = new Query;
            $profile_field_options_query->select("DISTINCT(" . $field["internal_name"] . ") as distinct_values")
                ->orderBy("distinct_values")
                ->from("profile");

            $profile_fields[$id]["options"] = ["Keine Angabe"];
            foreach ($profile_field_options_query->all() as $option) {
                if (!isset($option["distinct_values"])) {
                    continue;
                }
                $profile_fields[$id]["options"][] = $option["distinct_values"];
            }
        }
        unset($profile_fields[$id]["field_type_config"]);
    }

    $zip_city_query = new Query;
    $concat_query_string = "CONCAT(COALESCE(zip, '00000'), ' ', COALESCE(city, 'Keine Angabe'))";
    $zip_city_query->select([$concat_query_string . " AS location"])
        ->from("profile")
        ->groupBy([$concat_query_string]);

    foreach ($zip_city_query->all() as $zip_city_concat) {
        if (!isset($zip_city_concat["location"])) {
            continue;
        }
        $zip_city_list[] = $zip_city_concat["location"];
    }

    $zip_city_field = [
        "internal_name" => "location",
        "title" => "Ort",
        "options" => $zip_city_list,
    ];

    $profile_fields = array_merge([$zip_city_field], $profile_fields);
}

if ($do_export_output && $csv_export_allowed) {
    $data_select = getDataSelect();

    $users_query = User::find()
        ->addSelect(["*", "profile.*"])
        ->joinWith("profile")
        ->active()
        ->orderBy("firstname");

    queryWhere($data_select, $users_query);

    $users_query->asArray();
    $users = $users_query->all();

    foreach ($users as &$user) {
        foreach ($user as $field_name => $field_value) {
            $user[$field_name] = remapFieldValueIfNeeded($field_name, $field_value, $field_value_mappers);
        }
        unset($user["profile"]);
    }

    if (count($users) === 0) {
        unset($users);
    } else {
        $disabled_fields = array_filter($export_field_config, $is_disabled);
        $profile_fields = array_keys(array_diff_key($users[0], $disabled_fields));
    }
}

if ($do_list_output || $do_export_output) {
?>
    <style>
        .filter-select-wrapper {
            display: flex;
            flex-flow: row wrap;
            justify-content: space-evenly;
        }

        .filter-select-wrapper > div {
            margin: 0 12px;
        }

        .filter-select-wrapper form {
            width: 250px;
            max-width: 100%;
        }

        .export-select-wrapper form {
            max-width: 100%;
        }

        .export-select-wrapper label {
            min-width: 220px;
        }

        .select-box {
            position: relative;
        }

        .select-box label {
            width: 100%;
        }

        .select-box select {
            width: 100%;
            font-weight: bold;
        }

        .select-anchor {
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
        }

        .checkboxes {
            display: none;
            border: 1px #dadada solid;
        }

        .checkboxes label {
            display: block;

            margin: 0;
            padding: 3px;
            line-height: 18px;
        }

        .checkboxes label:hover {
            background-color: #90bbff;
        }

        .user-box {
            float: left;
            margin: 2px 2px 2px 2px;
            padding: 2px 10px 2px 2px;
            background: #EFEFEF;
            min-width: 250px;
        }

        #pagination {
            background-color: #efefef;
        }

        #export {
            background-color: #efefef;
            float: right;
        }

        #csv {
            background-color: #efefef;
            float: left;
        }

        #back {
            background-color: #efefef;
            float: left;
        }
    </style>
<div class="container">
    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-10">
            <div class="panel panel-default">
                <?php
                }

                if ($do_export_output) {
                    ?>

                    <div class="panel-heading"><strong>Mitglieder-</strong>Export</div>

                    <div class="panel-body">
                        <?php
                        if (isset($users) && $csv_export_allowed) {
                            ?>
                            <div id="profileFieldsConfig" style="display: none;">
                                <?= base64_encode(json_encode($export_field_config)) ?>
                            </div>
                            <div id="exportData" style="display: none;">
                                <?= base64_encode(json_encode($users)) ?>
                            </div>

                            <div class="export-select-wrapper">
                                <b>Exportfelder</b>
                                <form>
                                    <?php
                                    foreach ($profile_fields as $field) {
                                        ?>
                                        <label for="<?= $field ?>">
                                            <input type="checkbox"
                                                   id="<?= $field ?>"
                                                   onclick="updateData()"
                                                <?php if (isset($export_field_config[$field]) &&
                                                $is_unchecked($export_field_config[$field])) { ?>
                                            >
                                            <?php } else { ?>
                                                checked>
                                            <?php } ?>
                                            <?= $get_display_name($export_field_config, $field) ?>
                                        </label>
                                        <?php
                                    }
                                    ?>
                                </form>
                            </div>

                            <hr>

                            <div id="back">
                                <a class="btn">Back</a>
                            </div>

                            <div id="csv">
                                <a class="btn" download="deltanet_export.csv">Download</a>
                            </div>
                            <?php
                        } else {
                            ?>
                            <div class="alert alert-warning">Nichts zum Export selektiert.</div>
                            <?php
                        }
                        ?>
                    </div>
                    <?php
                }

                if ($do_list_output) {
                    ?>

                    <div class="panel-heading"><strong>Mitglieder-</strong>Suche</div>

                    <div class="panel-body">
                        <div class="filter-select-wrapper">
                            <?php foreach ($profile_fields as $field) { ?>
                                <div>
                                    <b><?= $get_display_name($list_field_config, $field["title"]) ?></b>
                                    <form>
                                        <div class="select-box" onclick="showCheckboxes(this)"
                                             checkboxes-hidden>
                                            <label>
                                                <select>
                                                    <option>Selektieren...</option>
                                                </select>
                                            </label>
                                            <div class="select-anchor"></div>
                                        </div>
                                        <div class="checkboxes">
                                            <?php
                                            if (isset($field["options"])) {
                                                foreach ($field["options"] as $key => $display_key) {
                                                    $id = base64_url_encode(json_encode([
                                                        "field" => $field["internal_name"],
                                                        "value" => is_numeric($key) ? $display_key : $key,
                                                    ])); ?>
                                                    <label for="<?= $id ?>">
                                                        <input type="checkbox"
                                                               id="<?= $id ?>"
                                                               onclick="filterByCheckbox(this)">
                                                        <?= substr(remapFieldValueIfNeeded($field["internal_name"], $display_key, $field_value_mappers),0,30) ?>
                                                    </label>
                                                    <?php
                                                }
                                            }
                                            ?>
                                        </div>
                                    </form>
                                </div>
                            <?php } ?>
                        </div>

                        <hr>

                        <div id="list-wrapper" class="media">
                        </div>
                        <div id="pagination" class="media" style="display: none">
                            <span class="btn" onclick="paginate('left')">&lt;</span>
                            <span id="pages"></span>
                            <span class="btn" onclick="paginate('right')">&gt;</span>
                        </div>
                        <?php if ($csv_export_allowed) { ?>
                            <div id="export">
                                <a class="btn">Export</a>
                            </div>
                        <?php } ?>
                    </div>
                    <?php
                }

                if ($do_list_output || $do_export_output) {
                ?>
            </div>
        </div>
    </div>
</div>
<?php
}

if ($do_export_output) {
    ?>
    <script <?= Html::nonce() ?>>
        <?= file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . "exportmod.js") ?>
        resetExport();
    </script>
    <?php
}

if ($do_list_output) {
    ?>
    <script <?= Html::nonce() ?>>
        <?= file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . "filtermod.js") ?>
        resetFilter();
    </script>
    <?php
}
?>
