<?php

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';


use MTC\Core\Setting;

//initialize variables
if (!isset($_REQUEST['action'])) {
    $_REQUEST['action'] = null;
}
if (!isset($_REQUEST['environment'])) {
    $_REQUEST['environment'] = '';
}
$errors = null;

$table = 'example';
if ($_REQUEST['environment'] == 'staging') {
    $page_meta['title'] = 'Manage Staging Settings';
} else {
    $page_meta['title'] = 'Manage Settings';
}

$errors = [];

// Reset a key back to it's default for an environment
if ($_REQUEST['action'] == 'delete') {
    Setting::where('environment', '!=', '')
           ->where('environment', '=', $_REQUEST['environment'])
           ->where('key', '=', $_REQUEST['key'])
           ->delete();

    Setting::export();

    // Redirect back to the same env
    $params = ['environment' => $_REQUEST['environment']];
    header('Location: ./?' . http_build_query($params));
    exit();

}

if (filter_input(INPUT_POST, 'action') === 'add_new' && config('app.env') === 'staging') {
    $data = [
        'module' => filter_input(INPUT_POST, 'module'),
        'key' => filter_input(INPUT_POST, 'key'),
        'value' => filter_input(INPUT_POST, 'value'),
        'type' => filter_input(INPUT_POST, 'type'),
        'description' => filter_input(INPUT_POST, 'description'),
    ];

    // Check if we haven't forgotten something
    foreach ($data as $key => $value) {
        if (empty($value)) {
            $errors[$key] = ucfirst($key) . ' is missing';
        }
    }

    // Check if key is not already defined
    if (Setting::where('key', $data['key'])->count() > 0) {
        $errors['key'] = 'This setting is already defined';
    }

    if (empty($errors)) {
        Setting::create($data);
        unset($_POST);
        $message = 'Setting Added';
    }
}

// Store keys which shouldn't be updated in the case of an import.
$exclude_update_keys = ['created_at', 'updated_at'];

// Leave a note
if (config('app.env') == 'production') {
    $errors[] = "Settings cannot be changed from the live site. Please paste changes from staging if changes are required.";
} elseif (isset($_POST['settings']) && is_array($_POST['settings'])) {

    $is_changed = false;

    foreach ($_POST['settings'] as $id => $data) {

        $data['environment'] = $_REQUEST['environment'];

        $default = Setting::where('key', '=', $data['key'])
                          ->where('environment', '=', '')
                          ->first();

        $setting = Setting::where('key', '=', $data['key'])
                          ->where('environment', '=', $data['environment'])
                          ->first();

        // If setting isn't created yet (new env, then start a new one)
        if ($setting === null) {
            $setting = new Setting();
        }

        $setting->fill($data);

        if ($default->value != $setting->value && $setting->isDirty()) {
            $setting->save();
            $is_changed = true;
        }
    }

    // Export the settings json if the file has changed
    if ($is_changed) {
        Setting::export();
    }
}

$data = Setting::allByModule($_REQUEST['environment']);
$environments = setting::distinct('environment')->pluck('environment')->toArray();

$environment = config('app.env');
if ($environment !== 'production' && !in_array($environment, $environments)) {
    $environments[] = $environment;
}

require_once $path.'core/admin/templates/adminheader.html.php';
require_once 'templates/index.tpl.php';
require_once $path.'core/admin/templates/adminfooter.html.php';
