<?php include "top.php"; ?>
<!DOCTYPE html>
<html>
<head>
	<?php include('include/head.php'); ?>
	<title>Sender IDs Management</title>
	<link rel="stylesheet" type="text/css" href="src/plugins/datatables/media/css/jquery.dataTables.css">
	<link rel="stylesheet" type="text/css" href="src/plugins/datatables/media/css/dataTables.bootstrap4.css">
	<link rel="stylesheet" type="text/css" href="src/plugins/datatables/media/css/responsive.dataTables.css">
	<style>
		.status-active {
			color: #28a745;
			font-weight: bold;
		}
		.status-inactive {
			color: #6c757d;
		}
		.active-toggle {
			cursor: pointer;
		}
	</style>
</head>
<body>
	<?php include('include/header.php'); ?>
	<?php include('include/sidebar.php'); 

	$action = $_REQUEST['action'] ?? '';
	$id = $_REQUEST['id'] ?? '';
	
	// Handle form actions
	if($action == 'save') {
		if($psave == 1) {
			$sender_id = $_POST['sender_id'];
			$username = $_POST['username'];
			$password = $_POST['password'];
			$is_active = isset($_POST['is_active']) ? 1 : 0;
			
			// If setting as active, deactivate all others first
			if($is_active == 1) {
				mysqli_query($con, "UPDATE sender_ids SET is_active = 0");
			}
			
			$res = mysqli_query($con, "INSERT INTO sender_ids (sender_id, username, password, is_active) 
									 VALUES ('$sender_id', '$username', '$password', '$is_active')");
			if($res) {
				echo "<script>alert('Sender ID added successfully');</script>";
			} else {
				echo "<script>alert('Error adding Sender ID');</script>";
			}
		} else {
			echo "<script>alert('You are not Authorized to Save');</script>";
		}
	} elseif($action == 'update') {
		if($pupdate == 1) {
			$sender_id = $_POST['sender_id'];
			$username = $_POST['username'];
			$password = $_POST['password'];
			$is_active = isset($_POST['is_active']) ? 1 : 0;
			
			// If setting as active, deactivate all others first
			if($is_active == 1) {
				mysqli_query($con, "UPDATE sender_ids SET is_active = 0");
			}
			
			$res = mysqli_query($con, "UPDATE sender_ids SET 
									 sender_id='$sender_id', 
									 username='$username', 
									 password='$password',
									 is_active='$is_active'
									 WHERE id='$id'");
			if($res) {
				echo "<script>alert('Sender ID updated successfully');</script>";
			} else {
				echo "<script>alert('Error updating Sender ID');</script>";
			}
		} else {
			echo "<script>alert('You are not Authorized to Update');</script>";
		}
	} elseif($action == 'delete') {
		if($pdelete == 1) {
			$res = mysqli_query($con, "DELETE FROM sender_ids WHERE id='$id'");
			if($res) {
				echo "<script>alert('Sender ID deleted successfully');</script>";
			} else {
				echo "<script>alert('Error deleting Sender ID');</script>";
			}
		} else {
			echo "<script>alert('You are not Authorized to Delete');</script>";
		}
	} elseif($action == 'edit') {
		$edit = f(q("SELECT * FROM sender_ids WHERE id='$id'"));
	} elseif($action == 'toggle_active') {
		if($pupdate == 1) {
			// First deactivate all sender IDs
			mysqli_query($con, "UPDATE sender_ids SET is_active = 0");
			
			// Then activate the selected one
			$res = mysqli_query($con, "UPDATE sender_ids SET is_active = 1 WHERE id='$id'");
			if($res) {
				echo "<script>alert('Sender ID activated successfully');</script>";
			} else {
				echo "<script>alert('Error activating Sender ID');</script>";
			}
		} else {
			echo "<script>alert('You are not Authorized to Update');</script>";
		}
	}
	?>

	<div class="main-container">
		<div class="pd-ltr-20 customscroll customscroll-10-p height-100-p xs-pd-20-10">
			<div class="min-height-200px">
				<div class="page-header">
					<div class="row">
						<div class="col-md-6 col-sm-12">
							<div class="title">
								<h4>Sender IDs Management</h4>
							</div>
							<nav aria-label="breadcrumb" role="navigation">
								<ol class="breadcrumb">
									<li class="breadcrumb-item"><a href="index.php">Home</a></li>
									<li class="breadcrumb-item active" aria-current="page">Sender IDs</li>
								</ol>
							</nav>
						</div>
						<div class="col-md-6 col-sm-12 text-right">
							<!-- Optional right side content -->
						</div>
					</div>
				</div>
				
				<!-- Form Section -->
				<div class="pd-20 bg-white border-radius-4 box-shadow mb-30">
					<form action="<?=$_SERVER['PHP_SELF']?>?action=<?php if($action=='edit'){?>update&id=<?php echo $id?><?php }else{?>save<?php } ?>" method="POST">
						<div class="clearfix" style="min-height: 30px;"></div>
						
						<div class="form-group row">
							<label class="col-sm-12 col-md-2 col-form-label">Sender ID</label>
							<div class="col-sm-12 col-md-10">
								<input class="form-control" type="text" name="sender_id" placeholder="e.g., 9836212825" value="<?=$edit['sender_id']??''?>" required>
							</div>
						</div>
						<div class="form-group row">
							<label class="col-sm-12 col-md-2 col-form-label">Username</label>
							<div class="col-sm-12 col-md-10">
								<input class="form-control" type="text" name="username" placeholder="Username" value="<?=$edit['username']??''?>" required>
							</div>
						</div>
						<div class="form-group row">
							<label class="col-sm-12 col-md-2 col-form-label">Password</label>
							<div class="col-sm-12 col-md-10">
								<input class="form-control" type="password" name="password" placeholder="Password" value="<?=$edit['password']??''?>" required>
							</div>
						</div>
						<div class="form-group row">
							<label class="col-sm-12 col-md-2 col-form-label">Set as Active</label>
							<div class="col-sm-12 col-md-10">
								<div class="custom-control custom-checkbox">
									<input type="checkbox" class="custom-control-input" id="is_active" name="is_active" value="1" 
										<?php if(($edit['is_active']??0) == 1) echo 'checked'; ?> 
										<?php if(!isset($edit) && mysqli_num_rows(mysqli_query($con, "SELECT * FROM sender_ids")) == 0) echo 'checked'; ?>>
									<label class="custom-control-label" for="is_active">Make this the active sender ID</label>
									<small class="form-text text-muted">Only one sender ID can be active at a time. Checking this will deactivate all others.</small>
								</div>
							</div>
						</div>
						
						<div class="clearfix">
							<div class="pull-right">
								<button type="submit" class="btn btn-primary btn-sm"><i class="fa fa-save"></i> <?php echo ($action=='edit') ? 'Update' : 'Save'; ?></button>
								<?php if($action=='edit'): ?>
									<a href="<?=$_SERVER['PHP_SELF']?>" class="btn btn-secondary btn-sm">Cancel</a>
								<?php endif; ?>
							</div>
						</div>
					</form>
				</div>
				
				<!-- Data Table Section -->
				<div class="pd-20 bg-white border-radius-4 box-shadow mb-30">
					<div class="clearfix mb-20">
						<div class="pull-left">
							<h5 class="text-blue">Sender IDs List</h5>
						</div>
					</div>
					<div class="row">
						<table class="stripe hover multiple-select-row data-table-export nowrap">
							<thead>
								<tr>
									<th class="table-plus datatable-nosort">Sender ID</th>
									<th>Username</th>
									<th>Status</th>
									<th>SMS Count</th>
									<th>Last Reset</th>
									<th>Action</th>	
								</tr>
							</thead>
							<tbody>
								<?php
									$get_senders = mysqli_query($con, "SELECT * FROM sender_ids ORDER BY is_active DESC, sender_id");
									while($row = mysqli_fetch_array($get_senders)) {
										$status_class = $row['is_active'] == 1 ? 'status-active' : 'status-inactive';
										$status_text = $row['is_active'] == 1 ? 'Active' : 'Inactive';
								?>
								<tr>
									<td class="table-plus"><?=$row['sender_id']?></td>
									<td><?=$row['username']?></td>
									<td class="<?=$status_class?>">
										<?php if($row['is_active'] == 1): ?>
											<i class="fa fa-check-circle"></i> <?=$status_text?>
										<?php else: ?>
											<a href="<?=$_SERVER['PHP_SELF']?>?action=toggle_active&id=<?=$row['id']?>" class="active-toggle">
												<i class="fa fa-circle"></i> Set as Active
											</a>
										<?php endif; ?>
									</td>
									<td><?=$row['sms_count']?></td>
									<td><?=$row['last_reset']?></td>
									<td>
										<a href="<?=$_SERVER['PHP_SELF']?>?action=edit&id=<?=$row['id']?>">EDIT</a> | 
										<a href="<?=$_SERVER['PHP_SELF']?>?action=delete&id=<?=$row['id']?>" onclick="return confirm('Are you sure you want to delete this sender ID?');">DELETE</a>
									</td>
								</tr>
								<?php } ?>	
							</tbody>
						</table>
					</div>
				</div>
			</div>
			<?php include('include/footer.php'); ?>
		</div>
	</div>
	
	<?php include('include/script.php'); ?>
	<script src="src/plugins/datatables/media/js/jquery.dataTables.min.js"></script>
	<script src="src/plugins/datatables/media/js/dataTables.bootstrap4.js"></script>
	<script src="src/plugins/datatables/media/js/dataTables.responsive.js"></script>
	<script src="src/plugins/datatables/media/js/responsive.bootstrap4.js"></script>
	<script src="src/plugins/datatables/media/js/button/dataTables.buttons.js"></script>
	<script src="src/plugins/datatables/media/js/button/buttons.bootstrap4.js"></script>
	<script src="src/plugins/datatables/media/js/button/buttons.print.js"></script>
	<script src="src/plugins/datatables/media/js/button/buttons.html5.js"></script>
	<script src="src/plugins/datatables/media/js/button/buttons.flash.js"></script>
	<script src="src/plugins/datatables/media/js/button/pdfmake.min.js"></script>
	<script src="src/plugins/datatables/media/js/button/vfs_fonts.js"></script>
	<script>
		$('document').ready(function(){
			$('.data-table-export').DataTable({
				scrollCollapse: true,
				autoWidth: false,
				responsive: true,
				columnDefs: [{
					targets: "datatable-nosort",
					orderable: false,
				}],
				"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
				"language": {
					"info": "_START_-_END_ of _TOTAL_ entries",
					searchPlaceholder: "Search"
				},
				dom: 'Bfrtip',
				buttons: [
					'copy', 'csv', 'pdf', 'print'
				]
			});
			
			// Confirm before setting a sender ID as active
			$('.active-toggle').on('click', function(e) {
				return confirm('Setting this as active will deactivate the current active sender ID. Continue?');
			});
		});
	</script>
</body>
</html>