<?php
/**
 * WebEngine CMS
 * https://webenginecms.org/
 * 
 * @version 1.2.6
 * @author Lautaro Angelico <http://lautaroangelico.com/>
 * @copyright (c) 2013-2025 Lautaro Angelico, All Rights Reserved
 * 
 * Licensed under the MIT license
 * http://opensource.org/licenses/MIT
 */
?>
<h1 class="page-header">Staff Management</h1>
<?php
	$database = Connection::Database('Platform');
	$realmDatabase = Connection::Database('MuOnline');
	$staffRealm = NexoraRealm::active();
	
	// Crear tabla si no existe
	if(!tableExists(WEBENGINE_STAFF, $database)) {
		$createTable = "CREATE TABLE ".WEBENGINE_STAFF." (
			staff_id INT IDENTITY(1,1) PRIMARY KEY,
			character_name VARCHAR(10) NOT NULL,
			account_username VARCHAR(10) NOT NULL,
			staff_rank VARCHAR(10) NOT NULL,
			added_by VARCHAR(10),
			added_date BIGINT,
			realm VARCHAR(32) NOT NULL,
			UNIQUE(realm, character_name)
		)";
		if(!$database->query($createTable)) {
			message('error', 'Could not create staff table. Error: ' . $database->error);
		} else {
			message('success', 'Staff table created successfully.');
		}
	}
	
	// Procesar agregar staff
	if(isset($_POST['submit_add_staff'])) {
		try {
			if(!isset($_POST['staff_account']) || empty($_POST['staff_account'])) throw new Exception("Please select an account.");
			if(!isset($_POST['staff_character']) || empty($_POST['staff_character'])) throw new Exception("Please select a character.");
			if(!isset($_POST['staff_rank']) || empty($_POST['staff_rank'])) throw new Exception("Please select a rank.");
			if(!in_array($_POST['staff_rank'], array('ADMIN', 'GM', 'MOD'))) throw new Exception("Invalid rank selected.");
			
			$characterName = $_POST['staff_character'];
			$accountUsername = $_POST['staff_account'];
			$staffRank = $_POST['staff_rank'];
			
			// Verificar que el personaje existe
			$Character = new Character();
			if(!$Character->CharacterExists($characterName)) throw new Exception("Character does not exist.");
			
			// Verificar que el personaje pertenece a la cuenta
			if(!$Character->CharacterBelongsToAccount($characterName, $accountUsername)) throw new Exception("Character does not belong to the selected account.");
			
			// Verificar que no está ya en el staff
			$existingStaff = $database->query_fetch_single("SELECT * FROM ".WEBENGINE_STAFF." WHERE character_name = ? AND realm = ?", array($characterName, $staffRealm));
			if(is_array($existingStaff)) throw new Exception("This character is already in the staff list.");
			
			// Insertar en la base de datos
			$staffData = array(
				'character' => $characterName,
				'account' => $accountUsername,
				'rank' => $staffRank,
				'by' => $_SESSION['username'],
				'date' => time(),
				'realm' => $staffRealm
			);
			
			$addStaff = $database->query("INSERT INTO ".WEBENGINE_STAFF." (character_name, account_username, staff_rank, added_by, added_date, realm) VALUES (:character, :account, :rank, :by, :date, :realm)", $staffData);
			if(!$addStaff) throw new Exception("Could not add staff member. Error: " . $database->error);
			
			NexoraAudit::log('admin.staff_added', 'character', $characterName, null, array('account'=>$accountUsername,'rank'=>$staffRank,'realm'=>$staffRealm));
			message('success', 'Staff member added successfully.');
		} catch(Exception $ex) {
			message('error', $ex->getMessage());
		}
	}
	
	// Procesar eliminar staff
	if(isset($_POST['delete_staff']) && isset($_POST['staff_id'])) {
		try {
			$staffId = (int)$_POST['staff_id'];
			if($staffId <= 0) throw new Exception("Invalid staff ID.");
			
			$deleteStaff = $database->query("DELETE FROM ".WEBENGINE_STAFF." WHERE staff_id = ? AND realm = ?", array($staffId, $staffRealm));
			if(!$deleteStaff) throw new Exception("Could not delete staff member. Error: " . $database->error);
			
			NexoraAudit::log('admin.staff_removed', 'staff', $staffId, null, array('removed'=>true,'realm'=>$staffRealm));
			message('success', 'Staff member removed successfully.');
			redirect(1, admincp_base('staff'));
		} catch(Exception $ex) {
			message('error', $ex->getMessage());
		}
	}
	
	// Obtener lista de cuentas para el dropdown
	$accountsList = $realmDatabase->query_fetch("SELECT TOP 1000 "._CLMN_USERNM_." FROM "._TBL_MI_." ORDER BY "._CLMN_USERNM_." ASC");
	$accounts = array();
	if(is_array($accountsList)) {
		foreach($accountsList as $account) {
			if(check_value($account[_CLMN_USERNM_])) {
				$accounts[] = $account[_CLMN_USERNM_];
			}
		}
	}
	
	// Obtener personajes si se seleccionó una cuenta
	$charactersList = array();
	if(isset($_POST['staff_account']) && !empty($_POST['staff_account'])) {
		$Character = new Character();
		$charactersList = $Character->AccountCharacter($_POST['staff_account']);
		if(!is_array($charactersList)) $charactersList = array();
	}
	
	// Obtener lista de staff actual
	$currentStaff = $database->query_fetch("SELECT * FROM ".WEBENGINE_STAFF." WHERE realm = ? ORDER BY staff_rank ASC, character_name ASC", array($staffRealm));
?>
<div class="row">
	<div class="col-md-6">
		<div class="panel panel-primary">
			<div class="panel-heading">Add Staff Member</div>
			<div class="panel-body">
				<form action="" method="post" role="form">
					<div class="form-group">
						<label for="staff_account">Account</label>
						<select name="staff_account" id="staff_account" class="form-control" required onchange="this.form.submit()">
							<option value="">-- Select Account --</option>
							<?php
							foreach($accounts as $account) {
								$selected = (isset($_POST['staff_account']) && $_POST['staff_account'] == $account) ? ' selected' : '';
								echo '<option value="'.htmlspecialchars($account).'"'.$selected.'>'.htmlspecialchars($account).'</option>';
							}
							?>
						</select>
					</div>
					
					<div class="form-group">
						<label for="staff_character">Character</label>
						<select name="staff_character" id="staff_character" class="form-control" required>
							<option value="">-- Select Character --</option>
							<?php
							if(is_array($charactersList) && count($charactersList) > 0) {
								foreach($charactersList as $characterName) {
									echo '<option value="'.htmlspecialchars($characterName).'">'.htmlspecialchars($characterName).'</option>';
								}
							}
							?>
						</select>
					</div>
					
					<div class="form-group">
						<label for="staff_rank">Rank</label>
						<select name="staff_rank" id="staff_rank" class="form-control" required>
							<option value="">-- Select Rank --</option>
							<option value="ADMIN">ADMIN</option>
							<option value="GM">GM</option>
							<option value="MOD">MOD</option>
						</select>
					</div>
					
					<input type="submit" name="submit_add_staff" class="btn btn-primary" value="Add Staff Member"/>
				</form>
			</div>
		</div>
	</div>
	
	<div class="col-md-6">
		<div class="panel panel-default">
			<div class="panel-heading">Current Staff Members</div>
			<div class="panel-body">
				<?php if(is_array($currentStaff) && count($currentStaff) > 0) { ?>
					<table class="table table-striped table-condensed table-hover">
						<thead>
							<tr>
								<th>Character</th>
								<th>Account</th>
								<th>Rank</th>
								<th>Action</th>
							</tr>
						</thead>
						<tbody>
							<?php
							foreach($currentStaff as $staff) {
								$rankClass = '';
								switch($staff['staff_rank']) {
									case 'ADMIN':
										$rankClass = 'label-danger';
										break;
									case 'GM':
										$rankClass = 'label-warning';
										break;
									case 'MOD':
										$rankClass = 'label-info';
										break;
								}
								echo '<tr>';
									echo '<td>'.htmlspecialchars($staff['character_name']).'</td>';
									echo '<td>'.htmlspecialchars($staff['account_username']).'</td>';
									echo '<td><span class="label '.$rankClass.'">'.$staff['staff_rank'].'</span></td>';
									echo '<td><form method="post" action="'.admincp_base('staff').'" style="display:inline" onsubmit="return confirm(\'Are you sure you want to remove this staff member?\')"><input type="hidden" name="delete_staff" value="1"><input type="hidden" name="staff_id" value="'.(int)$staff['staff_id'].'"><button type="submit" class="btn btn-xs btn-danger">Remove</button></form></td>';
								echo '</tr>';
							}
							?>
						</tbody>
					</table>
				<?php } else { ?>
					<p class="text-muted">No staff members added yet.</p>
				<?php } ?>
			</div>
		</div>
	</div>
</div>
