<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Load priorities
require_once(HESK_PATH . 'inc/priorities.inc.php');

/* Check permissions for this feature */
hesk_checkPermission('can_man_dept');

// Populate default values for creation
$department = array(
    'id' => 0,
    'name' => '',
    'priority' => $hesk_settings['priorities'][array_keys($hesk_settings['priorities'])[0]]['id'],
    'type' => 0,
);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (defined('HESK_DEMO')) {
        hesk_process_messages($hesklang['ddemo'], 'manage_departments.php', 'NOTICE');
    }

    // Attempt to save. If problematic, we'll get back the form data entered.
    $department = try_save_department();
} elseif (hesk_REQUEST('id')) {
    // Fetch department information
    $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."departments` WHERE `id` = ".intval(hesk_REQUEST('id')));
    if ($row = hesk_dbFetchAssoc($res)) {
        $department['id'] = $row['id'];
        $department['name'] = $row['name'];
        $department['priority'] = intval($row['priority']);
        $department['type'] = intval($row['type']);
    }

    // If we're still on ID 0, then the department ID passed in doesn't exist
    if ($department['id'] === 0) {
        hesk_process_messages($hesklang['dept_not_found'], 'manage_departments.php');
    }
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
if (hesk_SESSION('iserror')) {
    hesk_handle_messages();
}
?>
<div class="main__content categories category-create">
    <section class="categories__head">
        <h2>
            <?php echo $department['id'] !== 0 ? $hesklang['edit_department'] : $hesklang['create_department']; ?>
        </h2>
    </section>
    <div class="table-wrap">
        <form method="post" class="form <?php echo isset($_SESSION['iserror']) ? 'invalid' : ''; ?>" action="manage_department.php" name="create-form">
            <div class="form-group">
                <label for="name">
                    <?php echo $hesklang['dept_name']; ?>: <span class="important">*</span>
                </label>
                <input type="text" name="name" class="form-control" id="name" maxlength="100" value="<?php echo htmlspecialchars($department['name']); ?>">
            </div>

            <div class="category-create__select">
                <span><?php echo $hesklang['def_pri']; ?></span>
                <div class="dropdown-select center out-close priority select-priority">
                    <select name="priority">
                        <?php foreach ($hesk_settings['priorities'] as $id => $priority):
                            $data_style = 'border-top-color:'.$priority['color'].';border-left-color:'.$priority['color'].';border-bottom-color:'.$priority['color'].';';
                        ?>
                            <option value="<?php echo $priority['id']; ?>"
                                <?php if (intval($priority['id']) == intval($department['priority'])): ?>selected<?php endif; ?>
                                data-class="priority_img priority_dwn" data-style="<?php echo $data_style;?>">
                                <?php echo $priority['name']; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label><?php echo $hesklang['dept_type']; ?>:</label>
                <div class="radio-custom">
                    <input type="radio" name="type" id="type0" value="0" <?php echo $department['type'] == 0 ? 'checked' : ''; ?>>
                    <label for="type0"><?php echo $hesklang['dept_public']; ?></label>
                </div>
                <div class="radio-custom">
                    <input type="radio" name="type" id="type1" value="1" <?php echo $department['type'] == 1 ? 'checked' : ''; ?>>
                    <label for="type1"><?php echo $hesklang['dept_private']; ?></label>
                </div>
            </div>

            <input type="hidden" name="id" value="<?php echo intval($department['id']); ?>">
            <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">

            <button class="btn btn-full" type="submit" ripple="ripple">
                <?php echo $department['id'] !== 0 ? $hesklang['save'] : $hesklang['create_dept']; ?>
            </button>
        </form>
    </div>
</div>
<?php
hesk_cleanSessionVars('iserror');
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/

function try_save_department()
{
    global $hesk_settings, $hesklang;

    /* A security check */
    hesk_token_check('POST');

    $department = array();
    $department['id'] = intval(hesk_POST('id'));
    $department['name'] = hesk_input(hesk_POST('name'));
    $department['type'] = hesk_POST('type') === '1' ? 1 : 0;
    $department['priority'] = intval(hesk_POST('priority'));

    if ( ! isset($hesk_settings['priorities'][$department['priority']])) {
        $department['priority'] = $hesk_settings['priorities'][array_keys($hesk_settings['priorities'])[0]]['id'];
    }

    // Validate required fields
    if ($department['name'] === '') {
        $_SESSION['iserror'] = 1;
        hesk_process_messages($hesklang['enter_dept_name'], 'NOREDIRECT');
    }

    if ($department['id'] === 0) {
        /* Do we already have a department with this name? */
        $res = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."departments` WHERE `name` LIKE '".hesk_dbEscape( hesk_dbLike($department['name']) )."' LIMIT 1");
        if (hesk_dbNumRows($res) != 0) {
            $_SESSION['iserror'] = 1;
            hesk_process_messages($hesklang['dept_dupl'], 'NOREDIRECT');
        }
    }

    // Do we have errors? If so, return the department to the page.
    if (isset($_SESSION['iserror'])) {
        return $department;
    }

    if ($department['id'] === 0) {
        // Get next order
        $res = hesk_dbQuery("SELECT MAX(`dept_order`) AS `m` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."departments`");
        $tmp = hesk_dbFetchAssoc($res);
        $my_order = intval($tmp['m']) + 10;

        hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."departments` (`name`, `dept_order`, `type`, `priority`)
                      VALUES ('".hesk_dbEscape($department['name'])."',
                              '".intval($my_order)."',
                              '".intval($department['type'])."',
                              '".intval($department['priority'])."')");
        $_SESSION['seldept2'] = hesk_dbInsertID();
        $success_msg = sprintf($hesklang['dept_name_added'], stripslashes($department['name']));
    } else {
        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."departments`
                      SET `name` = '".hesk_dbEscape($department['name'])."',
                          `type` = '".intval($department['type'])."',
                          `priority` = '".intval($department['priority'])."'
                      WHERE `id` = ".intval($department['id']));
        $_SESSION['seldept2'] = $department['id'];
        $success_msg = sprintf($hesklang['dept_edited'], stripslashes($department['name']));
    }

    hesk_cleanSessionVars('iserror');

    hesk_process_messages($success_msg, 'manage_departments.php', 'SUCCESS');
    exit();
} // End try_save_department()
