<?php
/*
 * JohnCMS NEXT Mobile Content Management System (http://johncms.com)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://johncms.com JohnCMS Project
 * @copyright   Copyright (C) JohnCMS Community
 * @license     GPL-3
 */

define('_IN_JOHNCMS', 1);

require('../system/bootstrap.php');

$id = isset($_REQUEST['id']) ? abs(intval($_REQUEST['id'])) : 0;
$act = isset($_GET['act']) ? trim($_GET['act']) : '';

/** @var Psr\Container\ContainerInterface $container */
$container = App::getContainer();

/** @var PDO $db */
$db = $container->get(PDO::class);

/** @var Johncms\Api\UserInterface $systemUser */
$systemUser = $container->get(Johncms\Api\UserInterface::class);

/** @var Johncms\Api\ToolsInterface $tools */
$tools = $container->get(Johncms\Api\ToolsInterface::class);

/** @var Johncms\Api\ToolsInterface $bbcode */
$bbcode = $container->get(Johncms\Api\BbcodeInterface::class);

/** @var Johncms\Api\ConfigInterface $config */
$config = $container->get(Johncms\Api\ConfigInterface::class);

/** @var Johncms\Counters $counters */
$counters = App::getContainer()->get('counters');

/** @var Zend\I18n\Translator\Translator $translator */
$translator = $container->get(Zend\I18n\Translator\Translator::class);
$translator->addTranslationFilePattern('gettext', __DIR__ . '/locale', '/%s/default.mo');


$textl = _t('Apply to be a staff');
$headmod = 'apply_staff';
require('../system/head.php');

if (!$systemUser->isValid()) {
    echo 'You are not logged in';
    require ('../system/end.php');
    exit;
}


$maxapply = 500;
$adddate = 6;
$usersapply = 2;
switch ($act) {
case 'delete':

$req = $db->query("SELECT * FROM `apply_staff` WHERE id='$id' LIMIT 1");
if ($systemUser->rights >= 9 && $req->rowCount()) {
if (isset($_GET['yes'])) {
$db->exec("DELETE FROM `apply_staff`  WHERE `id`='$id' LIMIT 1");
header('location: ' . preg_replace('/(page|start)\=[0-9]+/', '', $_SESSION['prd']));
exit;
} else {
$_SESSION['prd'] = htmlspecialchars(getenv("HTTP_REFERER"));
echo '<div class="orange"><p>Are you sure want to delete staff crew from list..??!<br/><a href="apply_staff.php?act=delete&amp;id=' . $id . '&amp;yes">Yes</a> &bull; <a href="' . htmlspecialchars(getenv("HTTP_REFERER")) . '">No</a></p></div>';
}
}
break;

case 'edit':
$req = $db->query("SELECT * FROM `apply_staff` WHERE id='$id' LIMIT 1");
if ($systemUser->rights >= 9 && $req->rowCount()) {
if (isset($_POST['submit'])) {
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$opis = isset($_POST['opis']) ? mb_substr(trim($_POST['opis']), 0, 300) : '';
$count = isset($_POST['count']) ? abs(intval($_POST['count'])) : 0;
$soob = trim($_POST['message']);
$error = array();
if (empty($name) || empty($opis) || empty($soob))
$error[] = 'Field could not be empty..!!';
if($error) {
echo '<div class="orange">'.$tools->displayError($error, '<a href="apply_staff.php?act=edit&amp;id=' . $id . '">Try again..!!</a>').'</div>';
require_once("../system/end.php");
exit;
}
$db->exec("UPDATE `apply_staff` SET `name`='" . $db->quote($name) . "', `opis`='" . $db->quote($opis) . "', `count`='$count' WHERE `id`='$id' LIMIT 1");
$creq = $db->query("SELECT `apply_staff`.*, `users`.`name` AS `id` FROM `apply_staff` LEFT JOIN `users` ON `apply_staff`.`iduser` = `users`.`id` WHERE `apply_staff`.`type`='1' ORDER BY `apply_staff`.`count` DESC LIMIT 1");
while ($cres = $creq->fetch()) {
$usname = $cres['id'];
$theme = 'Staff Recruitment';
$admin = 'Staff Administrator';
if ($usname == $admin) {
continue;
} 
$db->prepare('
INSERT INTO `cms_mail` SET
`user_id` = ?,
`from_id` = ?,
`text` = ?,
`time` = ?,
`sys` = 1,
`them` = ?
')->execute([
$systemUser->id,
$usname,
$soob,
time(),
$theme,
]);
}
header('location: ' . preg_replace('/(page|start)\=[0-9]+/', '', $_SESSION['prd']));
exit;
} else {
$_SESSION['prd'] = htmlspecialchars(getenv("HTTP_REFERER"));
$res = mysql_fetch_array($req);
echo '<div class="mainblok"><div class="phdr"><img src="/images/subfldr.png" width="16" height="16" class="left"/>&nbsp;<b>Change applyed status</b></div>' .
'<div class="menu"><form action="apply_staff.php?act=edit&amp;id=' . $id . '" method="post"><font color="#3399ff"><b>' . $bbcode->tags($res['name']) . '</b></font><br/>' .
'Reason to become a staff:<br/><textarea cols="17" rows="2" name="opis">' . htmlentities($res['opis'], ENT_QUOTES, 'UTF-8') . '</textarea><br/>' .
'Change the status:<br/><select name="name" size="1"><option value="[red]Rejected[/red]"> Rejected </option>
<option value="[red]Staff position[/red] already exist..!!"> Staff position already exist </option>
<option value="[green]Accepted[/green] as Forum Moderator"> Forum Moderator </option>
<option value="[green]Accepted[/green] as Download Moderator"> Download Moderator </option>
<option value="[green]Accepted[/green] as Library Moderator"> Library Moderator </option>
<option value="[green]Accepted[/green] as Super Moderator"> Super Moderator </option>
<option value="[green]Accepted[/green] as Administrator"> Administrator </option>
</select><br/>' .
'Message to applyed staff:<br/><select name="message" size="1"><option value="We are sorry you are [red][b]Rejected[/b][/red], thanks for your contribution for applyng staff.."> Message for Rejected </option>
<option value="We are sorry [red][b]Staff position[/b][/red], you applyed already exist.. thanks for your contribution for applyng staff.."> Staff position already exist </option>
<option value="You are accepted as [green][b]Forum Moderator[/b][/green], thanks for applyng staff recruitment.. be wise for what your doing on your duty to manage the forum..!!"> Message for Forum Moderator </option>
<option value="You are accepted as [green][b]Download Moderator[/b][/green], thanks for applyng staff recruitment.. be wise for what your doing on your duty to manage the forum..!!"> Message for Download Moderator </option>
<option value="You are accepted as [green][b]Library Moderator[/b][/green], thanks for applyng staff recruitment.. be wise for what your doing on your duty to manage the forum..!!"> Message for Library Moderator </option>
<option value="You are accepted as [green][b]Super Moderator[/b][/green], thanks for applyng staff recruitment.. be wise for what your doing on your duty to manage the forum..!!"> Message for Super Moderator </option>
<option value="You are accepted as [green][b]Administrator[/b][/green], thanks for applyng staff recruitment.. be wise for what your doing on your duty to manage the forum..!!"> Message for Administrator </option>
</select><br/>' .
'<input name="submit" type="submit" title="click to apply" value="Proceed to apply"/></form>' .
'</div><div class="phdr"><a href="' . $_SESSION['prd'] . '">Back</a></div></div>';
}
}
break;

case 'redirect':
$req = $db->query("SELECT `name` FROM `apply_staff` WHERE `id`='$id' AND `type`='1'");
if($req->rowCount()) {
$res = $req->fetch();
if (!$_SESSION['fr_staff_' . $id]) {
$db->exec("UPDATE `apply_staff` SET `count` = (`count`+1) WHERE `id` = '$id' LIMIT 1");
$_SESSION['fr_staff_' . $id] = true;
}
header('location:' . $res['name']);
exit;
}
break;

case 'mass_del':
if ($systemUser->rights >= 9) {
if (isset($_GET['yes'])) {
foreach ($_SESSION['dc'] as $delid) {
$db->exec("DELETE FROM `apply_staff`  WHERE `id`='" . intval($delid) . "';");
}
header('location: ' . preg_replace('/(page|start)\=[0-9]+/', '', $_SESSION['prd']));
exit;
} else {
if (empty($_POST['delch'])) {
echo '<div class="orange">'.$tools->displayError('You not choose for deleting..<br/><a href="' . htmlspecialchars(getenv("HTTP_REFERER")) . '">Try again..!!</a>').'</div>';
require_once ("../incfiles/end.php");
exit;
}
foreach ($_POST['delch'] as $v) {
$dc[] = intval($v);
}
$_SESSION['dc'] = $dc;
$_SESSION['prd'] = htmlspecialchars(getenv("HTTP_REFERER"));
echo '<div class="orange"><p>Are you sure want delete this staff crew..??!<br/><a href="?act=mass_del&amp;yes">Yes</a> &bull; <a href="' . htmlspecialchars(getenv("HTTP_REFERER")) . '">No</a></p></div>';
}
}
break;

case 'mod_staff':
if ($systemUser->rights >= 9) {
if (isset($_GET['pr'])) {
$db->exec("UPDATE `apply_staff` SET `type` = '1' WHERE `id` = '$id' LIMIT 1");
$total = $db->query("SELECT COUNT(*) FROM `apply_staff` WHERE `type`='1'")->fetchColumn();
if ($total > $maxapply)
$db->exec("DELETE FROM `apply_staff` where `type`='1' ORDER BY `vr` ASC LIMIT 1");
header("location: apply_staff.php?act=mod_staff");
exit;
}
elseif (isset($_GET['vs'])) {
$total = $db->query("SELECT COUNT(*) FROM `apply_staff` WHERE `type`='1'")->fetchColumn();
if ($total > $maxapply) {
$total_mod = $db->query("SELECT COUNT(*) FROM `apply_staff` WHERE `type`='2'")->fetchColumn();
mysql_query("DELETE FROM `apply_staff` where `type`='1' ORDER BY `vr` ASC LIMIT $total_mod");
}
$db->exec("UPDATE `apply_staff` SET `type` = '1' WHERE `type` = '2'");
header("location: apply_staff.php?act=mod_staff");
exit;
} else {
echo '<div class="mainblok"><div class="phdr"><img src="/images/subfldr.png" width="16" height="16" class="left"/>&nbsp;<b><a href="apply_staff.php">Staff request pending</a></b></div>';
$req = $db->query("SELECT `apply_staff`.*, `users`.`name` AS `nick` FROM `apply_staff` LEFT JOIN `users` ON `apply_staff`.`iduser` = `users`.`id` WHERE `apply_staff`.`type`='2'");
if($req->rowCount()) {
echo '<form action="apply_staff.php?act=mass_del" method="post">';
while ($res = $req->fetch()) {
echo $i % 2 ? '<div class="list1">' : '<div class="list1">';
echo '<b>' . $bbcode->tags($res['name']) . '</b><br/><font color="maroon">' . $tools->checkout($res['opis'], 1, 1);
echo '</font><br/><small>Apply by <a href="../users/profile.php?user=' . $res['iduser'] . '"><font color="#3399ff">' . $res['nick'] . '</font></a>, ' . $tools->displayDate($res['vr']) . '</small>';
echo '<div class="sub"><input type="checkbox" name="delch[]" value="' . $res["id"] . '"/>&nbsp;<a href="apply_staff.php?act=delete&amp;id=' . $res["id"] . '"><span class="red">Delete</span></a> &bull; <a href="apply_staff.php?act=mod_staff&amp;id=' . $res["id"] . '&amp;pr">Confirm to list</a></div></div>';
++$i;
}
echo '<div class="list2"><input type="submit" value="delete check it"/></div></form>' .
'<div class="gmenu"><a href="apply_staff.php?act=mod_staff&amp;vs">Confirm all</a></div>';
}
else
echo '<div class="menu"><p>Empty pending request list..!!</p></div>';
echo '<div class="phdr"><a href="apply_staff.php?act=view_list">Go to view list</a></div></div>';
}
}
break;

case 'add_staff':
if ($systemUser->isValid()) {
$total_staff = $db->query("SELECT COUNT(*) FROM `apply_staff` WHERE `iduser`='$systemUser->id'")->fetchColumn();
$error = array();
if ($total_staff >= $usersapply && $systemUser->rights < 9)
$error[] = 'user only allowed add one ' . $usersapply . ' staff apply..!!';
$flood = $tools->antiflood();
if ($flood)
$error[] = 'antiflood..!! Please.. wait ' . $flood . ' second..!!';
if ($error) {
echo '<div class="orange">'.$tools->displayError($error, '<a href="apply_staff.php?act=add_staff">Please wait a minute..!!</a>').'</div>';
require_once("../system/end.php");
exit;
}
if (isset($_POST['submit'])) {
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$opis = isset($_POST['opis']) ? mb_substr(trim($_POST['opis']), 0, 300) : '';
$type = $rights >= 0 ? 2 : 2;
if (empty($name) || empty($opis))
$error[] = 'Field could not be empty..!!';
if (!$error) {
$total = $db->query("SELECT COUNT(*) FROM `apply_staff` WHERE `name`='" . $db->quote($name) . "' OR  `name`='" . $db->quote($name) . "'")->fetchColumn();
if ($total >= 1)
$error[] = 'This staff position already exist..!!';
}
if ($error) {
echo '<div class="orange">'.$tools->displayError($error, '<a href="apply_staff.php?act=add_staff">Try again..!!</a>').'</div>';
require_once("../system/end.php");
exit;
}
$db->exec("INSERT INTO `apply_staff` SET `vr`='" . time() . "', `iduser`='$systemUser->id', `type`='$type', `name`='" . $db->quote($name) . "', `opis`='" . $db->quote($opis) . "'");
$db->exec("UPDATE `users` SET `lastpost` = '" . time() . "' WHERE `id` = '$systemUser->id'");
echo '<div class="mainblok"><div class="phdr"><img src="/images/subfldr.png" width="16" height="16" class="left"/>&nbsp;<b>Confirmation Message</b></div><div class="gmenu"><b>Thank you for applying</b><br/>Your Application has been Submited.. ' . ($rights >= 9 ? '' : ' your Application is going to Moderate by Owner') . '<br/>You will shortly notify by pm from admin within 24 hour or you can check your status <a href="apply_staff.php?act=view_list"><b>Here</b></a></div>
<div class="phdr"><a href="../index.php">Back to Home</a></div></div>';
} else {
echo '<div class="mainblok"><div class="phdr"><img src="/images/subfldr.png" width="16" height="16" class="left"/>&nbsp;<b>Joint to be our staff</b></div><div class="gmenu">' .
'<p>We are continuously trying to find talented member for our staff and also to expand our community..<br/><b>What do we want..?! We want to make the forum better..</b><br/>
And you are invited to join us.. You dont know if you will fit in here..?! Well its very simple to answer that.. If you like any kind of programming we usually like you.. You must note that a staff member needs to have some level of knowledge about programming in order to help other users..
You also need to note that a staff member needs to be active here daily and usually reply to threads if you can help.. Do you think you can manage that..?! And most importantly do you think that by doing this you can help others..?! If the answer is yes then we invite you to become a part of our team..
To ancomplish all that, you have to do is to submit the form down below and if the current staff members agree that you can become a staff member you will be promoted in just a few hours.. Its also possible to receive pms from the staff if they want to get to know you better but its recommended to submit this form after you do some decent number of posts here and by doing that, we already know you..
We wish you good luck and we hope, staff member or not, that you have a good time here and enjoy your stay..</p> ' .
'<form action="apply_staff.php?act=add_staff" method="post">' .
'<b>Apply to be staff as:</b>' .
'<br/><select name="name" size="1"><option value="Apply as Forum Moderator"> Forum Moderator </option>
<option value="Apply as Download Moderator"> Download Moderator </option>
<option value="Apply as Library Moderator"> Library Moderator </option>
<option value="Apply as Super Moderator"> Super Moderator </option>
<option value="Apply as Administrator"> Administrator </option>
</select><br/> ' .
'<b>Reason to become a staff..??!</b>' .
'<br/><textarea cols="17" rows="2" name="opis"></textarea><br/>' .
'<input name="submit" type="submit" title="click to apply staff" value="Apply for staff"/></form>' .
'</div><div class="phdr">If you applyed you can view your status <a href="apply_staff.php?act=view_list"><span class="red"><b>Here</b></span></a><br/>';
echo '<a href="../index.php">Back To Home</a></div></div>';
}
} else {
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
}
break;

default:
echo '<div class="mainblok"><div class="phdr"><img src="/images/subfldr.png" width="16" height="16" class="left"/>&nbsp;<b>Staff request list</b></div>';
$total_staff = $db->query("SELECT COUNT(*) FROM `apply_staff` WHERE `iduser`='$systemUser->id'")->fetchColumn();
if ($systemUser->isValid() && ($total_staff < $usersapply || $systemUser->rights >= 0) && ((time()  - $systemUser['datereg']) > ($adddate * 86400) || $systemUser->rights >= 9))
echo '<div class="gmenu"><a href="apply_staff.php?act=add_staff">Apply for staff</a></div>';
if ($systemUser->rights >= 9) {
$total_mod = $db->query("SELECT COUNT(*) FROM `apply_staff` WHERE `type`='2'")->fetchColumn();
if($total_mod)
echo '<div class="orange"><a href="apply_staff.php?act=mod_staff">staff for moderation</a> ' . $total_mod . '</div>';
}
$total = $db->query("SELECT COUNT(*) FROM `apply_staff` WHERE `type`='1'")->fetchColumn();
if($total) {
$req = $db->query("SELECT `apply_staff`.*, `users`.`sex`, `users`.`datereg`, `users`.`name` AS `nick` FROM `apply_staff` LEFT JOIN `users` ON `apply_staff`.`iduser` = `users`.`id` WHERE `apply_staff`.`type`='1' ORDER BY `apply_staff`.`count` DESC LIMIT $start, $kmess");
if ($systemUser->rights >= 9)
echo '<form action="apply_staff.php?act=mass_del" method="post">';
while ($res = $req->fetch()) {
echo $i % 2 ? '<div class="list1">' : '<div class="list1">';
if ($res['sex'])
echo '<img src="../images/' . ($res['sex'] == 'm' ? 'm' : 'w') . ($res['datereg'] > time() - 86400 ? '_new' : '')
. '.png" width="16" height="16" align="left" alt="' . ($res['sex'] == 'm' ? 'es' : 'eu') . '" />&#160;';
else
echo '<img src="../images/del.png" width="12" height="12" alt=""/>&#160;';
echo '<a href="../users/profile.php?user=' . $res['iduser'] . '"><b>' . $res['nick'] . '</b></a><br/>';
echo '<font color="green">Reason to be staff</font>:<br/><font color="maroon">';
echo '' . $tools->checkout($res['opis'], 1, 1);
echo '</font><br/><b>' . $bbcode->tags($res['name']) . '</b><br/>';
if ($systemUser->rights >= 9)
echo '<div class="sub"><input type="checkbox" name="delch[]" value="' . $res["id"] . '"/>&nbsp;<a href="apply_staff.php?act=delete&amp;id=' . $res["id"] . '"><span class="red">Delete</span></a> &bull; <a href="apply_staff.php?act=edit&amp;id=' . $res["id"] . '">Change status</a> &bull; <a href="../users/profile.php?act=edit&amp;user=' . $res['iduser'] . '">Edit user rights</a></div>';
echo '</div>';
++$i;
}
if ($systemUser->rights >= 9)
echo '<div class="list2"><input type="submit" value="Delete check it list"/></form></div>';
}
else
echo '<div class="menu"><p>Empty list..!!</p></div>';
echo '<div class="phdr">Total staff:&nbsp;' . $total . '</div>';
if ($total > $kmess) {
echo '<div class="topmenu">' . $tools->displayPagination('apply_staff.php?', $start, $total, $kmess) . '<br/>';
echo '<form action="apply_staff.php" method="get"><input type="text" name="page" size="2"/><input type="submit" value="Go to page &gt;&gt;"/></form></div>';
}
echo '</div>';
}
require_once("../system/end.php");
?>