<?php
include 'renderer.php';

class Editmember extends Renderer {
    protected array $formFields = [
        ['label' => 'Nachname', 'type' => 'text', 'size' => 50, 'name' => 'lastname', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_STRING, 'dbfield' => 'last_name', 'optional' => false],
        ['label' => 'Vorname', 'type' => 'text', 'size' => 50, 'name' => 'firstname', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_STRING, 'dbfield' => 'first_name', 'optional' => false],
        ['label' => 'Straße', 'type' => 'text', 'size' => 50, 'name' => 'streetname', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_STRING, 'dbfield' => 'street', 'optional' => false],
        ['label' => 'Plz', 'type' => 'text', 'size' => 5, 'name' => 'zip', 'combine_with_next_line' => true, 'regex' => '/^([0-9]{5})$/', 'filter' => FILTER_SANITIZE_NUMBER_INT, 'dbfield' => 'zip', 'optional' => false],
        ['label' => 'Ort', 'type' => 'text', 'size' => 40, 'name' => 'town', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_STRING, 'dbfield' => 'town', 'optional' => false],
        ['label' => 'Birthday', 'type' => 'date', 'size' => 50, 'name' => 'birthdate', 'combine_with_next_line' => false, 'regex' => '/^((19|20)([0-9]){2}-[0-9]{2})-([0-9]{2})$/', 'filter' => FILTER_SANITIZE_STRING, 'dbfield' => 'birthdate', 'optional' => false],
        ['label' => 'Phone', 'type' => 'text', 'size' => 50, 'name' => 'phone', 'combine_with_next_line' => false, '/^0([0-9]{2,6})([ ]{0,1})([-\/]{0,1})([ ]{0,1})([0-9 ]{4,25})$/', 'filter' => FILTER_SANITIZE_STRING, 'dbfield' => 'phone', 'optional' => false],
        ['label' => 'Email', 'type' => 'email', 'size' => 50, 'name' => 'email', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_EMAIL, 'dbfield' => 'email', 'optional' => true],
        ['label' => 'Name des Kindes', 'type' => 'text', 'size' => 50, 'name' => 'childname', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_STRING, 'dbfield' => 'child_name', 'optional' => true],
        ['label' => 'Straße des Kindes', 'type' => 'text', 'size' => 50, 'name' => 'childstreet', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_STRING, 'dbfield' => 'child_street', 'optional' => true],
        ['label' => 'Gewählter Beitrag', 'type' => 'number', 'size' => 50, 'name' => 'subscription', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_STRING, 'dbfield' => 'subscription', 'optional' => false],
        ['label' => 'Geldinstitut', 'type' => 'text', 'size' => 50, 'name' => 'bankname', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_STRING, 'dbfield' => 'bank_name', 'optional' => true],
        ['label' => 'IBAN', 'type' => 'text', 'size' => 50, 'name' => 'iban', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_STRING, 'dbfield' => 'iban', 'optional' => true],
        ['label' => 'BIC', 'type' => 'text', 'size' => 50, 'name' => 'bic', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_STRING, 'dbfield' => 'bic', 'optional' => true],
        ['label' => 'Kontoinhaber', 'type' => 'text', 'size' => 50, 'name' => 'accountmember', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_STRING, 'dbfield' => 'account_member_name', 'optional' => true],
        ['label' => 'Mitgliedsstatus', 'type' => 'dbselect', 'size' => 0, 'name' => 'status', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_NUMBER_INT, 'dbfield' => 'membership_status',
            'sourcedb' => 'clubmember_status', 'optionfield' => 'status_text', 'encryption' => false],
        ['label' => 'Position im Verein', 'type' => 'dbselect', 'size' => 0, 'name' => 'position', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_NUMBER_INT, 'dbfield' => 'position_id',
            'sourcedb' => 'clubmember_position', 'optionfield' => 'description', 'encryption' => false, 'with_null_field' => true],
        ['label' => 'Online-Account', 'type' => 'dbselect', 'size' => 0, 'name' => 'user_id', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_NUMBER_INT, 'dbfield' => 'user_id',
            'sourcedb' => 'user', 'optionfield' => 'username', 'encryption' => false, 'with_null_field' => true],
    ];
    protected string $dbTable = 'clubmember';
    protected bool $dbGenerateSaltField = true;
    protected bool $dbUpdate = true;
    protected string $formSendButtonLabel = 'Änderungen speichern';
    protected bool $saveAllFields = true;
    
    public function __construct(?string $templateName = null) {
        parent::__construct($templateName);
        $id = $this->getUriParams()['id'];
        $this->loadUserData($id);
    }
    
    protected function loadUserData(string $id): void {
        $query = sprintf("SELECT c.first_name as firstname, c.last_name as lastname, c.street as streetname, c.zip, c.town, c.birthdate, c.phone, c.email, "
                        . "       c.child_name as childname, c.child_street as childstreet, c.subscription, c.bank_name as bankname, c.iban , c.bic , "
                        . "       c.account_member_name as accountmember, c.membership_status as status, c.position_id as position, c.user_id as user_id, c.salt "
                        . "FROM clubmember c  "
                        . "WHERE c.id = %d", $id);
        $dbResult = mysqli_query($this->dbConnection, $query);
        if (mysqli_num_rows($dbResult) === 0) {
            $this->templateName = 'notfound_error';
            return;
        }
        $line = mysqli_fetch_assoc($dbResult);
        $salt = $line['salt'];
        array_walk($line, function(&$item, $key) use ($salt) {
            if (!isset($item)) {
                return;
            } elseif ($this->fieldHasToBeEncrypted($key)) {
                $item = $this->decode($item, $salt);
            }
        });
        $this->predefines = $line;
    }
    
    protected function formAction(): void {
        if (!$this->formCheckFields()) {
            return;
        }
        $saltQuery = "SELECT id, membership_status, salt FROM clubmember c WHERE id=" . $this->getUriParams()['id'];
        $dbResult = mysqli_query($this->dbConnection, $saltQuery);
        if (!$dbResult) {
            return;
        }
        $oldDataRow = mysqli_fetch_assoc($dbResult);
        $this->salt = $oldDataRow['salt'];
        $this->saveToDb();
        if (filter_input(INPUT_POST, 'status', FILTER_SANITIZE_NUMBER_INT) != $oldDataRow['membership_status']) {
            $this->saveMembershipStatusChangeHistory($oldDataRow['id'], $oldDataRow['membership_status'], 
                    filter_input(INPUT_POST, 'status', FILTER_SANITIZE_NUMBER_INT));
        }
        $this->cleanFields = false;
        $this->messages[] = 'Mitglied erfolgreich bearbeitet.';
    }
    
    protected function saveMembershipStatusChangeHistory(string $clubmemberId, string $oldStatus, string $newStatus): void {
        $query = sprintf("INSERT INTO ffajs.clubmember_status_history (clubmember_id, changer_id, old_status_id, new_status_id, change_timestamp) "
                         . "VALUES(%d, %d, %d, %d, now()); ",
                        $clubmemberId, $_SESSION['userid'], $oldStatus, $newStatus);
        mysqli_query($this->dbConnection, $query);
    }
}
