<?php

require __dir__ . '/init.php';


$_POST = help::sanitize($_POST);


if(isset($_POST['delete'])){
	
	$SQL = "DELETE FROM messageadmin WHERE id='{$_POST['id']}'";
	$status = mysqli_query($link, $SQL);
	$msg = $status ? "Message deleted successfully!" : "Message not deleted! ";
	
}


  
if(isset($_POST['send'])){
	
	$SQL = sQuery::update( 'messageadmin', array(
		"reply" => $_POST['reply'],
		"astatus" => 1
	), "id='{$_POST['id']}'");

	$status = (mysqli_query($link, $SQL));
	
	$msg = $status ? "Message replied successfully!" : "Message not replied! ";
	
}




template::get_header();


    ?>

	<?php template::title( "MESSAGE MANAGEMENT" ); ?>
	
	<div class="card">
		<div class="card-body">
		
			<?php template::alert( $msg, $status ?? null ); ?>
			
			<div class="table-responsive">
				<table class="table text-break" data-table='simple'>
					<thead>
						<tr class="info">
							<th>Account</th>
							<th>Message</th>
							<th>Admin-Response</th>
							<th>Status</th>
							<th>Date</th>
							<th>Action</th>
						</tr>
					</thead>
					<tbody>
						<?php 
						
							$sql= "SELECT * FROM messageadmin ";
							$result = mysqli_query($link,$sql);
							
							if(mysqli_num_rows($result) > 0){
								while($row = mysqli_fetch_assoc($result)){  
								
									if(!empty($row['astatus'])) 
										$msg = '<i class="fas fa-check-circle text-success"></i> Message replied';
									else $msg = '<i class="fas fa-times text-danger"></i> Waiting for response!';
								
						?>
						<tr class="primary">
							<td><?php echo $row['account'];?></td>
							<td><?php echo $row['message'];?></td>
							<td> 
								<textarea cols="50" class='form-control form-control-sm' data-reflect="#_<?php echo $row['id']; ?>"><?php echo $row['reply'];?></textarea>
							</td>
							<td><?php echo $msg;?></td>
							<td><?php echo $row['date'];?></td>
							<td>
								<form action="sendm.php" method="post" onsubmit="return confirm('Please click OK to confirm');">
									<input type='hidden' name='id' value="<?php echo $row['id']; ?>">
									<input type='hidden' name='reply' value="<?php echo $row['reply']; ?>" id="<?php echo "_{$row['id']}"; ?>">
									<div class='btn-group'>
										<button type="submit" name="send" class="btn btn-success">
											<span class="fas fa-paper-plane"></span>
										</button>
										<button type="submit" name="delete" class="btn btn-danger">
											<span class="fas fa-trash"></span>
										</button>
									</div>
								</form>
							</td>
						</tr>
						<?php
								}
							}
						?>
					</tbody>
				</table>
			</div>
		</div>
	</div>

<?php template::get_footer(); ?>  