<?php

use Webuccino\Install\Core\App;
use Webuccino\Install\Core\Session;
use Webuccino\Install\Core\Database;
use Webuccino\Install\Http\Forms\ProfileForm;

$db      = App::resolve(Database::class);
$version = config_native('srm_config.installer.version_to_install', "v9.1.8");
$form    = ProfileForm::validate($attributes = [
    'email'             => $_POST['profile_email'],
    'username'          => $_POST['profile_username'],
    'password'          => $_POST['profile_password'],
    'confirmpassword'   => $_POST['confirmpassword'],
    'security_question' => $_POST['security_question'],
    'security_answer'   => $_POST['security_answer']
]);

$db->updateOrInsert(
    'Users',
    ['is_owner' => 1],
    [
        'Email'                   => $attributes['email'],
        'user_name'               => $attributes['username'],
        'password'                => password_hash($attributes['password'], PASSWORD_BCRYPT),
        'Security_question_index' => $attributes['security_question'],
        'Security_answer'         => $attributes['security_answer'],
        'status'                  => 'Active',
        'is_admin'                => 1,
        'email_verified_at'       => date('Y-m-d H:i:s'),
        'regestration_IP'         => $_SERVER['REMOTE_ADDR']
    ]
);

$db->updateOrInsert(
    'Settings',
    ['settings_key' => 'user_registeration_is_enabled'],
    ['settings_value' => true]
);

$db->updateOrInsert(
    'installed_versions',
    ['version' => $version],
    ['install_last_success_step' => "profile"]
);

Session::put('profile-created', true);

if (isset($_POST['finish'])) {

    finish_installer();

    Session::put("finish-on-profile", true);

    redirect_native(route_native('/finishInstallation'));
} else {
    redirect_native(route_native('/settings'));
}
