<?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 */
$can_man_dept = hesk_checkPermission('can_man_dept', 0);

/* What should we do? */
if ( $action = hesk_REQUEST('a') ) {
	if ( defined('HESK_DEMO') )  {hesk_process_messages($hesklang['ddemo'], 'manage_departments.php', 'NOTICE');}
    elseif ( ! $can_man_dept)     {hesk_process_messages($hesklang['no_permission'], 'manage_departments.php', 'NOTICE');}
	elseif ($action == 'remove')  {remove();}
	elseif ($action == 'order')   {order_dept();}
	elseif ($action == 'type')    {toggle_type();}
	elseif ($action == 'priority'){change_priority();}
}

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

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

/* This will handle error, success and notice messages */
if (!hesk_SESSION('error')) {
    hesk_handle_messages();
}
?>
<div class="main__content categories">
    <section class="categories__head">
        <h2>
            <?php echo $hesklang['menu_dept']; ?>
            <div class="tooltype right out-close">
                <svg class="icon icon-info">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                </svg>
                <div class="tooltype__content">
                    <div class="tooltype__wrapper">
                        <?php echo $hesklang['dept_intro']; ?>
                    </div>
                </div>
            </div>
        </h2>
        <?php if ($can_man_dept): ?>
        <a href="manage_department.php" class="btn btn btn--blue-border" ripple="ripple">
            <?php echo $hesklang['add_dept']; ?>
        </a>
        <?php endif; ?>
    </section>
    <div class="table-wrap">
        <div class="table">
            <table id="default-table" class="table sindu-table">
                <thead>
                <tr>
                    <th><?php echo $hesklang['id']; ?></th>
                    <th><?php echo $hesklang['dept_name']; ?></th>
                    <th><?php echo $hesklang['priority']; ?></th>
                    <th><?php echo $hesklang['dept_type']; ?></th>
                    <th><?php echo $hesklang['menu_cat']; ?></th>
                    <?php if ($can_man_dept): ?>
                    <th></th>
                    <?php endif; ?>
                </tr>
                </thead>
                <tbody>
                <?php
                /* Count categories per department */
                $cat_counts = array();
                $res = hesk_dbQuery("SELECT COUNT(*) AS `cnt`, `department_id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` GROUP BY `department_id`");
                while ($tmp = hesk_dbFetchAssoc($res)) {
                    $cat_counts[$tmp['department_id']] = $tmp['cnt'];
                }

                /* Get list of departments */
                $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."departments` ORDER BY `dept_order` ASC");
                $keyed_depts = array();
                $num = hesk_dbNumRows($res);
                while ($mydept = hesk_dbFetchAssoc($res)) {
                    $keyed_depts[$mydept['id']] = $mydept;
                }

                $j = 0;
                foreach ($keyed_depts as $id => $mydept) {
                    $j++;
                    $table_row = '';
                    if (isset($_SESSION['seldept2']) && $mydept['id'] == $_SESSION['seldept2']) {
                        $table_row = 'class="ticket-new"';
                    }

                    $cat_count = isset($cat_counts[$mydept['id']]) ? $cat_counts[$mydept['id']] : 0;
                    $dept_type_label = ($mydept['type'] == '1') ? $hesklang['dept_private'] : $hesklang['dept_public'];
                    $priority_info = isset($hesk_settings['priorities'][$mydept['priority']]) ? $hesk_settings['priorities'][$mydept['priority']] : null;
                    ?>
                    <tr <?php echo $table_row; ?> data-department-id="<?php echo $mydept['id']; ?>">
                        <td><?php echo $mydept['id']; ?></td>
                        <td><span><?php echo htmlspecialchars($mydept['name']); ?></span></td>
                        <td>
                            <?php if ($priority_info): ?>
                                <span style="color: <?php echo htmlspecialchars($priority_info['color']); ?>;"><?php echo htmlspecialchars($priority_info['name']); ?></span>
                            <?php else: ?>
                                &mdash;
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($can_man_dept): ?>
                                <a class="tooltip" href="manage_departments.php?a=type&amp;deptid=<?php echo $mydept['id']; ?>&amp;token=<?php hesk_token_echo(); ?>" title="<?php echo $hesklang['click_to_change']; ?>">
                                    <?php echo $dept_type_label; ?>
                                </a>
                            <?php else: ?>
                                <?php echo $dept_type_label; ?>
                            <?php endif; ?>
                        </td>
                        <td>
                            <a href="manage_categories.php"><?php echo intval($cat_count); ?></a>
                        </td>
                        <?php if ($can_man_dept): ?>
                        <td class="nowrap generate">
                            <a class="tooltip" href="manage_department.php?id=<?php echo $mydept['id']; ?>" title="<?php echo $hesklang['edit']; ?>">
                                <svg class="icon icon-edit-ticket">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-edit-ticket"></use>
                                </svg>
                            </a>
                            <?php if ($j > 1): ?>
                            <a class="tooltip" href="manage_departments.php?a=order&amp;deptid=<?php echo $mydept['id']; ?>&amp;move=-15&amp;token=<?php hesk_token_echo(); ?>" title="<?php echo $hesklang['move_up']; ?>">
                                <svg class="icon icon-chevron-up">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-up"></use>
                                </svg>
                            </a>
                            <?php endif; ?>
                            <?php if ($j < $num): ?>
                            <a class="tooltip" href="manage_departments.php?a=order&amp;deptid=<?php echo $mydept['id']; ?>&amp;move=15&amp;token=<?php hesk_token_echo(); ?>" title="<?php echo $hesklang['move_down']; ?>">
                                <svg class="icon icon-chevron-down">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                </svg>
                            </a>
                            <?php endif; ?>
                            <?php if ($mydept['id'] != 1):
                                $modal_body = $hesklang['confirm_del_dept'];
                                if ($cat_count > 0) {
                                    $modal_body .= '<br><br><div><b>'.sprintf($hesklang['dept_in_use'], $cat_count).'</b></div>';
                                }
                                $delete_url = 'manage_departments.php?a=remove&deptid='.$mydept['id'].'&token='.hesk_token_echo(0);
                                $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'], $modal_body, $delete_url);
                            ?>
                            <a class="tooltip delete" title="<?php echo $hesklang['deldept']; ?>" href="javascript:" data-modal="[data-modal-id='<?php echo $modal_id; ?>']">
                                <svg class="icon icon-delete">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-delete"></use>
                                </svg>
                            </a>
                            <?php endif; ?>
                        </td>
                        <?php endif; ?>
                    </tr>
                    <?php
                }
                ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php
hesk_cleanSessionVars('error');
hesk_cleanSessionVars('seldept2');
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/

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

    /* A security check */
    hesk_token_check();

    $_SERVER['PHP_SELF'] = 'manage_departments.php';

    $mydept = intval( hesk_GET('deptid') ) or hesk_error($hesklang['no_dept_id']);

    if ($mydept == 1) {
        hesk_process_messages($hesklang['def_dept'], $_SERVER['PHP_SELF']);
    }

    // Block delete if any category is still assigned
    $res = hesk_dbQuery("SELECT COUNT(*) AS `cnt` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE `department_id`='".intval($mydept)."'");
    $row = hesk_dbFetchAssoc($res);
    if (intval($row['cnt']) > 0) {
        hesk_process_messages($hesklang['dept_in_use'], $_SERVER['PHP_SELF']);
    }

    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."departments` WHERE `id`='".intval($mydept)."'");
    if (hesk_dbAffectedRows() != 1) {
        hesk_error("$hesklang[int_error]: $hesklang[dept_not_found].");
    }

    hesk_process_messages($hesklang['dept_removed'], $_SERVER['PHP_SELF'], 'SUCCESS');
} // End remove()


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

    /* A security check */
    hesk_token_check();

    $deptid = intval( hesk_GET('deptid') ) or hesk_error($hesklang['no_dept_id']);
    $_SESSION['seldept2'] = $deptid;

    $dept_move = intval( hesk_GET('move') );

    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."departments` SET `dept_order`=`dept_order`+".intval($dept_move)." WHERE `id`='".intval($deptid)."'");
    if (hesk_dbAffectedRows() != 1) {
        hesk_error("$hesklang[int_error]: $hesklang[dept_not_found].");
    }

    /* Update all department fields with new order */
    $res = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."departments` ORDER BY `dept_order` ASC");

    $i = 10;
    while ($mydept = hesk_dbFetchAssoc($res)) {
        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."departments` SET `dept_order`=".intval($i)." WHERE `id`='".intval($mydept['id'])."'");
        $i += 10;
    }

    header('Location: manage_departments.php');
    exit();
} // End order_dept()


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

    /* A security check */
    hesk_token_check();

    $deptid = intval( hesk_GET('deptid') ) or hesk_error($hesklang['no_dept_id']);
    $_SESSION['seldept2'] = $deptid;

    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."departments` SET `type`=IF(`type`='0','1','0') WHERE `id`='".intval($deptid)."'");

    hesk_process_messages($hesklang['dept_edited'], 'manage_departments.php', 'SUCCESS');
} // End toggle_type()


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

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

    $deptid = intval( hesk_POST('deptid') ) or hesk_error($hesklang['no_dept_id']);
    $priority = intval( hesk_POST('priority') );

    if ( ! isset($hesk_settings['priorities'][$priority])) {
        hesk_process_messages($hesklang['invalid_action'], 'manage_departments.php');
    }

    $_SESSION['seldept2'] = $deptid;

    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."departments` SET `priority`='".intval($priority)."' WHERE `id`='".intval($deptid)."'");

    hesk_process_messages(sprintf($hesklang['dept_edited'], ''), 'manage_departments.php', 'SUCCESS');
} // End change_priority()
