<?php
    /**
     * @author Webfairy MediaT CMS - www.Webfairy.net
     */
    include dirname(__FILE__).'/lib/engine.php';
        $Webfairy = new Webfairy();
            $Webfairy->start();

    $Webfairy->require_auth();

    if (($row = $Webfairy->db->users[$Webfairy->Userid()]) == false) {
        $Webfairy->logout();
        $Webfairy->go_to();
    }

    $Webfairy->loadClass('formbuilder', 'tools');

    $Form = new FormBuilder('users', tr('update_account'), tr('my_account'), true);

    $Form->addField(array(
            'id' => 'email',
            'type' => 'textbox',
            'label' => tr('email'),
            'required' => true,
            'validationtype' => 'email',
            'defaultvalue' => $row['email'],
        )
    );

    $Form->addField(array(
            'id' => 'password',
            'type' => 'password',
            'label' => tr('password'),
            'maxlength' => 50,
            'headerinjectioncheck' => 'full',
        )
    );

    $Form->addField(array(
            'id' => 'confirm',
            'type' => 'password',
            'label' => tr('password_confirm'),
            'maxlength' => 50,
            'headerinjectioncheck' => 'full',
        )
    );

    if ($Form->formSuccess()) {
        $isvalid = true;

        $email = $Webfairy->plaintext($_POST['email']);

        $records = array(
            'email' => $email,
        );

        if ($Webfairy->db->users(
            "email = ? AND id != ?",
            $email,
            $Webfairy->Userid()
           )->fetch()) {
            $Form->forceErrorMessage('email', ftr('err_already_exists', array($email)));
            $isvalid = false;
        }

        if (isset($_POST['password']) == true && empty($_POST['password']) == false) {
            $password = $_POST['password'];
            $confirm = $_POST['confirm'];

            if ($password == $confirm) {
                $salt = $Webfairy->createSalt();
                $hash = hash('sha256', $password);

                $records['password'] = hash('sha256', $salt.$hash);
                $records['salt'] = $salt;
            } else {
                $isvalid = false;
                $Form->forceErrorMessage('confirm', tr('password_not_match'));
            }
        }

        if ($isvalid == true) {
            $row->update($records);
            $Form->renderThanks();
        }
    }

    $Webfairy->smarty->assign('renderForm', $Form->renderForm());

    $Webfairy->display('account.tpl', array(tr('my_account')));
