<?php 
include ('includes/header.php');

// Verificar que el usuario es admin
if (!isAdmin($db)) {
	header("Location: main.php");
	exit;
}

$table_name = "user";
$page = "resellers.php";

// Obtener solo revendedores
$res = $db->select($table_name, '*', 'role = :role', '', [':role' => 'reseller']);

// Actualizar revendedor
@$resU = $db->select($table_name, '*', 'id = :id', '', [':id' => $_GET['update']]);

if(isset($_POST['submitU'])){
	unset($_POST['submitU']);
	$updateData = $_POST;
	$oldData = $resU[0];
	
	$db->update($table_name, $updateData, 'id = :id',[':id' => $_GET['update']]);
	
	$changes = [];
	if ($oldData['username'] !== $updateData['username']) {
		$changes[] = "Usuario: {$oldData['username']} → {$updateData['username']}";
	}
	if ($oldData['credits'] !== $updateData['credits']) {
		$creditDiff = $updateData['credits'] - $oldData['credits'];
		$changes[] = "Créditos: {$oldData['credits']} → {$updateData['credits']} (" . ($creditDiff > 0 ? "+$creditDiff" : $creditDiff) . ")";
	}
	
	logActivity($db, $currentUser['id'], 'update', 'reseller', $_GET['update'], $updateData['username'], json_encode(['changes' => $changes]));
	
	echo "<script>window.location.href='".$page."?status=1'</script>";
}

// Crear nuevo revendedor
if (isset($_POST['submit'])){
	unset($_POST['submit']);
	$_POST['role'] = 'reseller';
	$_POST['owner_id'] = $currentUser['id'];
	$initialCredits = $_POST['credits'];
	
	$db->insert($table_name, $_POST);
	$newResellerId = $db->getLastInsertId();
	
	logResellerCreated($db, $currentUser['id'], $newResellerId, $_POST['username'], $initialCredits);
	
	$db->close();
	echo "<script>window.location.href='".$page."?status=1'</script>";
}

// Eliminar revendedor
if(isset($_GET['delete'])){
	$resellerData = $db->select($table_name, '*', 'id = :id', '', [':id' => $_GET['delete']]);
	
	$db->delete($table_name, 'id = :id',[':id' => $_GET['delete']]);
	
	if (!empty($resellerData)) {
		logResellerDeleted($db, $currentUser['id'], $_GET['delete'], $resellerData[0]['username']);
	}
	
	echo "<script>window.location.href='".$page."?status=2'</script>";
}

// Agregar créditos
if(isset($_POST['add_credits'])){
	$reseller_id = $_POST['reseller_id'];
	$credits_amount = $_POST['credits_amount'];
	$description = "Créditos agregados por admin";
	
	$resellerData = $db->select($table_name, '*', 'id = :id', '', [':id' => $reseller_id]);
	
	addCredits($db, $reseller_id, $credits_amount, $description, $currentUser['id']);
	
	if (!empty($resellerData)) {
		$newBalance = $resellerData[0]['credits'] + $credits_amount;
		logCreditsAssigned($db, $currentUser['id'], $reseller_id, $resellerData[0]['username'], $credits_amount, $newBalance);
	}
	
	echo "<script>window.location.href='".$page."?status=3'</script>";
}

?>

<!-- Modal Confirmar Eliminación -->
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content bg-dark text-white">
			<div class="modal-header border-secondary">
				<h5 class="modal-title">Confirmar Eliminación</h5>
			</div>
			<div class="modal-body">
				¿Realmente deseas eliminar este revendedor?
			</div>
			<div class="modal-footer border-secondary">
				<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
				<a class="btn btn-danger btn-ok">Eliminar</a>
			</div>
		</div>
	</div>
</div>

<!-- Modal Agregar Créditos -->
<div class="modal fade" id="add-credits-modal" tabindex="-1" role="dialog" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content bg-dark text-white">
			<div class="modal-header border-secondary">
				<h5 class="modal-title">Agregar Créditos</h5>
				<button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<form method="post">
				<div class="modal-body">
					<div class="form-group">
						<label>Revendedor</label>
						<select class="form-control" name="reseller_id" required>
							<option value="">Seleccionar</option>
							<?php foreach ($res as $row): ?>
								<option value="<?=$row['id']?>"><?=$row['username']?> (<?=$row['credits']?> créditos)</option>
							<?php endforeach; ?>
						</select>
					</div>
					<div class="form-group">
						<label>Cantidad de Créditos</label>
						<input type="number" class="form-control" name="credits_amount" placeholder="Cantidad" required min="1">
					</div>
				</div>
				<div class="modal-footer border-secondary">
					<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
					<button type="submit" name="add_credits" class="btn btn-success">Agregar</button>
				</div>
			</form>
		</div>
	</div>
</div>

<?php if (isset($_GET['create'])): ?>
<!-- Formulario Crear Revendedor -->
<div class="col-12 col-md-8 mx-auto">
	<div class="card">
		<div class="card-header">
			<h4 class="m-0 text-white"><i class="fa fa-user-plus"></i> Crear Revendedor</h4>
		</div>
		<div class="card-body">
			<form method="post">
				<div class="form-group">
					<label>Usuario</label>
					<input class="form-control" name="username" placeholder="Usuario" type="text" required/>
				</div>
				<div class="form-group">
					<label>Contraseña</label>
					<input class="form-control" name="password" placeholder="Contraseña" type="password" required/>
				</div>
				<div class="form-group">
					<label>Créditos Iniciales</label>
					<input class="form-control" name="credits" placeholder="0" type="number" value="0" required/>
				</div>
				<div class="mt-4">
					<button class="btn btn-info btn-lg btn-block" name="submit" type="submit">
						<i class="fa fa-check"></i> Crear Revendedor
					</button>
					<a href="resellers.php" class="btn btn-secondary btn-block mt-2">Volver</a>
				</div>
			</form>
		</div>
	</div>
</div>

<?php elseif (isset($_GET['update'])): ?>
<!-- Formulario Editar Revendedor -->
<div class="col-12 col-md-8 mx-auto">
	<div class="card">
		<div class="card-header">
			<h4 class="m-0 text-white"><i class="fa fa-edit"></i> Editar Revendedor</h4>
		</div>
		<div class="card-body">
			<form method="post">
				<input type="hidden" name="id" value="<?=$_GET['update']?>">
				<div class="form-group">
					<label>Usuario</label>
					<input class="form-control" name="username" value="<?=$resU[0]['username']?>" type="text" required/>
				</div>
				<div class="form-group">
					<label>Contraseña</label>
					<input class="form-control" name="password" value="<?=$resU[0]['password']?>" type="text" required/>
				</div>
				<div class="form-group">
					<label>Créditos</label>
					<input class="form-control" name="credits" type="number" value="<?=$resU[0]['credits']?>" required/>
				</div>
				<div class="mt-4">
					<button class="btn btn-info btn-lg btn-block" name="submitU" type="submit">
						<i class="fa fa-check"></i> Actualizar
					</button>
					<a href="resellers.php" class="btn btn-secondary btn-block mt-2">Volver</a>
				</div>
			</form>
		</div>
	</div>
</div>

<?php else: ?>
<!-- Lista de Revendedores -->
<div class="card">
	<div class="card-header d-flex justify-content-between align-items-center flex-wrap">
		<h4 class="m-0 text-white"><i class="fa fa-users"></i> Revendedores</h4>
		<div class="mt-2 mt-md-0">
			<a href="<?=$page?>?create" class="btn btn-sm btn-info mr-1">
				<i class="fa fa-plus"></i> Nuevo
			</a>
			<button class="btn btn-sm btn-success" data-toggle="modal" data-target="#add-credits-modal">
				<i class="fa fa-credit-card"></i> Créditos
			</button>
		</div>
	</div>
	<div class="card-body">
		<?php if (!empty($res)): ?>
		<div class="table-responsive">
			<table class="table table-hover">
				<thead>
					<tr>
						<th>Usuario</th>
						<th>Créditos</th>
						<th>Acciones</th>
					</tr>
				</thead>
				<tbody>
					<?php foreach ($res as $row): ?>
					<tr>
						<td><strong><?=$row['username']?></strong></td>
						<td><span class="badge badge-info"><?=$row['credits']?></span></td>
						<td>
							<a class="btn btn-info btn-sm" href="<?=$page?>?update=<?=$row['id']?>"><i class="fa fa-edit"></i></a>
							<a class="btn btn-danger btn-sm" href="#" data-href="<?=$page?>?delete=<?=$row['id']?>" data-toggle="modal" data-target="#confirm-delete"><i class="fa fa-trash"></i></a>
						</td>
					</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
		</div>
		<?php else: ?>
		<p class="text-center text-muted mb-0">No hay revendedores. <a href="<?=$page?>?create">Crear uno</a></p>
		<?php endif; ?>
	</div>
</div>
<?php endif; ?>

<?php include ('includes/footer.php');?>
