<?php

declare(strict_types=1);

/**
ET-Chat Copyright by SEDesign | ET-Chat v3.x.x Lizenz: CCPL | Autor: Evgeni Tcherkasski (info@s-e-d.de)
ET-Chat_T-FISH-MOD Weiterentwicklungen, Optimierungen und Ergänzungen am Code sind das geistige Eigentum von Tommy (Thomas Kuhn) und Harlekin (Bernd Witte).

Die darauf folgende Optimierungen und Ergänzungen am Code sind das Geistige Eigentum von Powermen (Christian K.)
und wird unter der Namenserweiterung M.C.v.x.x.x. geführt. 
PHP 8/9 Ready, XML Parser, PDO Prepared Statements Get Set sicherheit usw.
 */

class AdminRegUserIndex extends DbConectionMaker
{
    public function __construct()
    {
        parent::__construct();

        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        header('Content-Type: text/html; charset=utf-8');

        $langObj = new LangXml();
        $lang = $langObj->getLang()->admin[0]->admin_reg_user[0];

        // ROLE CHECK
        $allowedRoles = ["admin", "co_admin", "chatwache", "grafik"];
        $userRole = $_SESSION['etchat_' . $this->_prefix . 'user_priv'] ?? '';

        if (!in_array($userRole, $allowedRoles, true)) {
            header("Location: ./");
            exit;
        }

        // COUNT
        $counted = $this->dbObj->sqlGet(
            "SELECT COUNT(etchat_user_id) AS cnt 
             FROM {$this->_prefix}etchat_user 
             WHERE etchat_userprivilegien='user'"
        );

        $total = (int)($counted[0]['cnt'] ?? 0);

        // PAGINATION
        $perPage = 10;
        $currentPage = max(1, (int)($_GET['site'] ?? 1));
        $offset = ($currentPage - 1) * $perPage;

        $limit = ($this->_usedDatabase === 'pgsql')
            ? "LIMIT $perPage OFFSET $offset"
            : "LIMIT $offset, $perPage";

        // SORT
        $allowedSorts = [
            'name'      => 'etchat_username ASC',
            'reg_new'   => 'etchat_reg_timestamp DESC',
            'reg_old'   => 'etchat_reg_timestamp ASC',
            'login_new' => 'etchat_logintime DESC',
            'login_old' => 'etchat_logintime ASC',
        ];

        $sortKey = $_GET['sort'] ?? 'login_new';
        $orderBy = $allowedSorts[$sortKey] ?? 'etchat_logintime DESC';

        // SEARCH
        $search = trim($_GET['search'] ?? '');
        $params = [];
        $searchSql = '';

        if ($search !== '') {
            $searchSql = "AND etchat_username LIKE :search";
            $params[':search'] = "%$search%";
        }

        // USERS
        $sql = "SELECT etchat_user_id, etchat_username, etchat_userprivilegien,
                       etchat_reg_timestamp, etchat_reg_ip,
                       etchat_logintime, etchat_avatar,
                       etchat_email, etchat_last_ip
                FROM {$this->_prefix}etchat_user
                WHERE etchat_userprivilegien='user'
                $searchSql
                ORDER BY $orderBy
                $limit";

        $users = $this->dbObj->sqlGet($sql, $params);
        $this->dbObj->close();

        // CSRF
        if (empty($_SESSION['etchat_' . $this->_prefix . 'csrf_token'])) {
            $_SESSION['etchat_' . $this->_prefix . 'csrf_token'] = bin2hex(random_bytes(16));
        }
        $csrfToken = $_SESSION['etchat_' . $this->_prefix . 'csrf_token'];

        // SORT FORM
        $currentSort = htmlspecialchars((string)$sortKey, ENT_QUOTES, 'UTF-8');
        $currentSearch = htmlspecialchars((string)$search, ENT_QUOTES, 'UTF-8');

        $print_sort_form = '
		<form method="get" action="./">
			<input type="hidden" name="AdminRegUserIndex" value="1">

			<label><b>Sortieren:</b>
			<select name="sort" onchange="this.form.submit()">
				<option value="name" '.($currentSort=="name"?"selected":"").'>Name</option>
				<option value="reg_new" '.($currentSort=="reg_new"?"selected":"").'>Registriert neu</option>
				<option value="reg_old" '.($currentSort=="reg_old"?"selected":"").'>Registriert alt</option>
				<option value="login_new" '.($currentSort=="login_new"?"selected":"").'>Login neu</option>
				<option value="login_old" '.($currentSort=="login_old"?"selected":"").'>Login alt</option>
			</select>

			<b>Suche:</b></label>
			<input type="text" name="search" value="'.$currentSearch.'">

			<input type="submit" value="🔍 Suchen">

			<button type="button"
				onclick="window.location.href=\'./?AdminRegUserIndex=1\'">
				🔄 Reset
			</button>
		</form>';

        // PAGINATION
		$sitemakerObj = new Sitemaker($perPage, $total);
		$sitemakerObj->href = true;

		$baseUrl = "./?AdminRegUserIndex";

		if ($sortKey !== '') {
			$baseUrl .= '&sort=' . urlencode($sortKey);
		}

		if ($search !== '') {
			$baseUrl .= '&search=' . urlencode($search);
		}

		$baseUrl .= '&site=#site#';

		$sitemakerObj->make(
			$currentPage,
			$baseUrl,
			$lang->site[0]->tagData,
			$lang->site_of[0]->tagData
		);

		$print_sitemaker = $sitemakerObj->get();

        // TABLE
        $print_user_table = '';

        if (is_array($users) && count($users) > 0) {

            $print_user_table .= '<form id="checkers" method="post" action="./?AdminRegUserEdit">
                <input type="hidden" name="csrf_token" value="'.$csrfToken.'">
                <input type="hidden" id="userids" name="userids">

                <table border="1" cellpadding="5" cellspacing="0">
				<tbody>
                <tr>
                    <th></th>
                    <th>Username</th>
                    <th>Reg. Datum</th>
                    <th>IP während Reg.</th>
                    <th>Letzter Login</th>
                    <th>Letzte IP</th>
                    <th>E-Mail</th>
                    <th>Avatar</th>
                </tr>';

            foreach ($users as $u) {

                $id = (int)$u['etchat_user_id'];
                $name = htmlspecialchars($u['etchat_username'], ENT_QUOTES, 'UTF-8');

                $reg = is_numeric($u['etchat_reg_timestamp'])
                    ? date("d.m.Y H:i:s", (int)$u['etchat_reg_timestamp'])
                    : (string)$u['etchat_reg_timestamp'];

                $login = is_numeric($u['etchat_logintime'])
                    ? date("d.m.Y H:i:s", (int)$u['etchat_logintime'])
                    : (string)$u['etchat_logintime'];

                $email = htmlspecialchars((string)$u['etchat_email'], ENT_QUOTES, 'UTF-8');
                $avatar = htmlspecialchars((string)$u['etchat_avatar'], ENT_QUOTES, 'UTF-8');

                $avatarDeleteLink =
					'<a href="./?AdminRegUserEdit&delavatar&csrf_token='.$csrfToken.'&id='.$id.'"
						onclick="return confirm(\'Avatar wirklich löschen?\')">
						Löschen
					</a>';

				$print_user_table .= "
				<tr>
					<td><input type='checkbox' class='chk_user' value='{$id}'></td>
					<td><b><a href='./?AdminEditUserUser&id={$id}&csrf_token={$csrfToken}'>{$name}</a></b></td>
					<td>{$reg}</td>
					<td>".htmlspecialchars((string)$u['etchat_reg_ip'])."</td>
					<td>{$login}</td>
					<td>".htmlspecialchars((string)$u['etchat_last_ip'])."</td>
					<td>{$email}</td>
					<td>{$avatarDeleteLink} <img class='avatar_list_admin' src='avatar/{$avatar}' width='16'></td>
				</tr>";
            }

            $print_user_table .= '</tbody></table></form><br>';
			
			$print_user_table .= '
			<input type="button"
				value="'.$lang->set_all[0]->tagData.'"
				id="mark_all_btn"">
			';
			
			$print_user_table .= '
			&nbsp;
			<input type="button"
				value="'.$lang->del[0]->tagData.'"
				 id="delete_selected_btn">
			';
        } else {
            $print_user_table = "<b>".$lang->nouser[0]->tagData."</b>";
        }

        // EXTRA
        $print_user_extra = '
        <form method="get" action="./">
            <input type="hidden" name="AdminRegUserEdit" value="1">
            <input type="hidden" name="deleteinactive" value="1">
			<input type="hidden" name="csrf_token" value="'.$csrfToken.'">
            <select name="inactive_months">
                <option value="3">3 Monate</option>
                <option value="6">6 Monate</option>
                <option value="12" selected>12 Monate</option>
                <option value="18">18 Monate</option>
                <option value="24">24 Monate</option>
            </select>
            <input type="submit" value="Löschen">
        </form>';

        $this->initTemplate(
            $lang,
            $print_sort_form,
            $print_sitemaker,
            $print_user_table,
            $print_user_extra,
			$total
        );
    }

    private function initTemplate($lang, $print_sort_form, $print_sitemaker, $print_user_table, $print_user_extra, $total): void
    {
        include "styles/admin_tpl/indexRegUser.tpl.html";
    }
}