<?php
session_start();
$title = 'Clientes';
require_once __DIR__ . '/../templates/header.php';
require_role(['admin', 'superadmin']);
csrf_check();

$user_role = $_SESSION['user_role'] ?? '';
$user_id = $_SESSION['uid'] ?? 0;

$error = null;

// Mostrar mensaje de éxito y luego eliminarlo de sesión
$success_message = $_SESSION['success_message'] ?? null;
unset($_SESSION['success_message']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = $_POST['action'] ?? '';

  if ($action === 'create') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $pin = trim($_POST['pin'] ?? '');

    if ($name === '' || $email === '') {
      $error = "Nombre y correo son obligatorios.";
    } else {
      $checkEmail = pdo()->prepare('SELECT COUNT(*) FROM users WHERE email = ?');
      $checkEmail->execute([$email]);
      if ($checkEmail->fetchColumn() > 0) {
        $error = "El correo ya está registrado en otro cliente.";
      } else {
        $password_hash = $password !== '' ? password_hash($password, PASSWORD_DEFAULT) : null;
        $pin_hash = $pin !== '' ? password_hash($pin, PASSWORD_DEFAULT) : null;

        $st = pdo()->prepare('INSERT INTO users (name, email, password_hash, pin_hash, role, admin_id, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())');
        $st->execute([$name, $email, $password_hash, $pin_hash, 'client', $user_id]);

        $_SESSION['success_message'] = "Cliente creado correctamente.";
        header('Location: clients.php');
        exit;
      }
    }
  } elseif ($action === 'update') {
    $id = (int)($_POST['id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $pin = trim($_POST['pin'] ?? '');

    if ($id <= 0 || $name === '' || $email === '') {
      $error = "Datos inválidos para actualizar cliente.";
    } else {
      $checkOwner = pdo()->prepare('SELECT COUNT(*) FROM users WHERE id = ? AND admin_id = ?');
      $checkOwner->execute([$id, $user_id]);
      if ($checkOwner->fetchColumn() == 0) {
        $error = "No tienes permiso para modificar este cliente.";
      }

      $checkEmail = pdo()->prepare('SELECT COUNT(*) FROM users WHERE email = ? AND id <> ?');
      $checkEmail->execute([$email, $id]);
      if ($checkEmail->fetchColumn() > 0) {
        $error = "El correo ya está registrado en otro cliente.";
      }

      if (!$error) {
        $params = [];
        $sql = 'UPDATE users SET name = ?, email = ?';
        $params[] = $name;
        $params[] = $email;

        if ($password !== '') {
          $sql .= ', password_hash = ?';
          $params[] = password_hash($password, PASSWORD_DEFAULT);
        }
        if ($pin !== '') {
          $sql .= ', pin_hash = ?';
          $params[] = password_hash($pin, PASSWORD_DEFAULT);
        }

        $sql .= ' WHERE id = ? AND admin_id = ?';
        $params[] = $id;
        $params[] = $user_id;

        $st = pdo()->prepare($sql);
        $st->execute($params);

        $_SESSION['success_message'] = "Cliente actualizado correctamente.";
        header('Location: clients.php');
        exit;
      }
    }
  } elseif ($action === 'delete') {
    $id = (int)($_POST['id'] ?? 0);

    if ($id <= 0) {
      $error = "ID inválido para eliminar cliente.";
    } else {
      $checkOwner = pdo()->prepare('SELECT COUNT(*) FROM users WHERE id = ? AND admin_id = ?');
      $checkOwner->execute([$id, $user_id]);
      if ($checkOwner->fetchColumn() == 0) {
        $error = "No tienes permiso para eliminar este cliente.";
      }

      if (!$error) {
        $st = pdo()->prepare('DELETE FROM users WHERE id = ? AND admin_id = ?');
        $st->execute([$id, $user_id]);

        $_SESSION['success_message'] = "Cliente eliminado correctamente.";
        header('Location: clients.php');
        exit;
      }
    }
  }
}

$search = trim($_GET['search'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 5;
$offset = ($page - 1) * $perPage;

// Consulta que siempre filtra por admin_id igual al usuario en sesión
$countSql = 'SELECT COUNT(*) FROM users WHERE role = :role AND admin_id = :admin_id AND (name LIKE :search OR email LIKE :search)';
$countParams = ['role' => 'client', 'admin_id' => $user_id, 'search' => "%$search%"];

$selectSql = 'SELECT * FROM users WHERE role = :role AND admin_id = :admin_id AND (name LIKE :search OR email LIKE :search) ORDER BY id DESC LIMIT :limit OFFSET :offset';
$selectParams = ['role' => 'client', 'admin_id' => $user_id, 'search' => "%$search%", 'limit' => $perPage, 'offset' => $offset];

$countSt = pdo()->prepare($countSql);
$countSt->execute($countParams);
$totalClients = $countSt->fetchColumn();
$totalPages = ceil($totalClients / $perPage);

$st = pdo()->prepare($selectSql);
$st->bindValue(':role', $selectParams['role']);
$st->bindValue(':admin_id', $selectParams['admin_id'], PDO::PARAM_INT);
$st->bindValue(':search', $selectParams['search'], PDO::PARAM_STR);
$st->bindValue(':limit', $selectParams['limit'], PDO::PARAM_INT);
$st->bindValue(':offset', $selectParams['offset'], PDO::PARAM_INT);
$st->execute();
$clients = $st->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
  <h3>Listado de clientes</h3>
  <button class="btn btn-success" data-bs-toggle="collapse" data-bs-target="#frmNew">+ Agregar cliente</button>
</div>

<?php if ($error): ?>
  <div class="alert alert-danger"><?= e($error) ?></div>
<?php endif; ?>

<?php if ($success_message): ?>
  <div class="alert alert-success"><?= e($success_message) ?></div>
<?php endif; ?>

<form method="get" class="mb-3">
  <div class="input-group" style="max-width: 400px;">
    <input type="text" name="search" class="form-control" placeholder="Buscar cliente por nombre o correo" value="<?= e($search) ?>">
    <button class="btn btn-outline-primary" type="submit">Buscar</button>
  </div>
</form>

<div id="frmNew" class="collapse mb-3">
  <div class="card card-body">
    <form method="post" class="row g-2">
      <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
      <input type="hidden" name="action" value="create">
      <div class="col-md-4">
        <label class="form-label">Nombre</label>
        <input class="form-control" name="name" required>
      </div>
      <div class="col-md-4">
        <label class="form-label">Correo</label>
        <input class="form-control" name="email" type="email" required>
      </div>
      <div class="col-md-2">
        <label class="form-label">Contraseña</label>
        <input class="form-control" name="password" placeholder="Minimo 6 caracteres">
      </div>
      <div class="col-md-2">
        <label class="form-label">PIN (para resumen)</label>
        <input class="form-control" name="pin" placeholder="Opcional">
      </div>
      <div class="col-12">
        <button class="btn btn-primary">Guardar</button>
      </div>
    </form>
  </div>
</div>

<div class="table-responsive">
  <table class="table table-striped align-middle">
    <thead>
      <tr>
        <th>ID</th>
        <th>Nombre</th>
        <th>Correo</th>
        <th>PIN</th>
        <th>Registro</th>
        <th>Acciones</th>
      </tr>
    </thead>
    <tbody>
      <?php if (count($clients) === 0): ?>
        <tr><td colspan="6" class="text-center">No se encontraron clientes.</td></tr>
      <?php endif; ?>
      <?php foreach ($clients as $c): ?>
      <tr>
        <td><?= e($c['id']) ?></td>
        <td><?= e($c['name']) ?></td>
        <td><?= e($c['email']) ?></td>
        <td><?= (!empty($c['pin_hash'])) ? 'Sí' : '—' ?></td>
        <td><?= e($c['created_at']) ?></td>
        <td>
          <button class="btn btn-sm btn-outline-primary" data-bs-toggle="collapse" data-bs-target="#edit<?= e($c['id']) ?>">Editar</button>
          <form method="post" class="d-inline" onsubmit="return confirm('¿Eliminar cliente? Se borrarán sus cuentas asignadas.');">
            <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="id" value="<?= e($c['id']) ?>">
            <button class="btn btn-sm btn-outline-danger">Eliminar</button>
          </form>
        </td>
      </tr>
      <tr class="collapse" id="edit<?= e($c['id']) ?>">
        <td colspan="6">
          <div class="card card-body">
            <form method="post" class="row g-2">
              <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
              <input type="hidden" name="action" value="update">
              <input type="hidden" name="id" value="<?= e($c['id']) ?>">
              <div class="col-md-4">
                <label class="form-label">Nombre</label>
                <input class="form-control" name="name" value="<?= e($c['name']) ?>">
              </div>
              <div class="col-md-4">
                <label class="form-label">Correo</label>
                <input class="form-control" name="email" type="email" value="<?= e($c['email']) ?>">
              </div>
              <div class="col-md-2">
                <label class="form-label">Nueva contraseña</label>
                <input class="form-control" name="password" placeholder="Dejar en blanco para mantener">
              </div>
              <div class="col-md-2">
                <label class="form-label">PIN</label>
                <input class="form-control" name="pin" placeholder="Opcional: reemplaza">
              </div>
              <div class="col-12">
                <button class="btn btn-primary">Actualizar</button>
              </div>
            </form>
          </div>
        </td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

<nav aria-label="Paginación clientes">
  <ul class="pagination justify-content-center">
    <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
      <a class="page-link" href="?search=<?= urlencode($search) ?>&page=<?= $page - 1 ?>" tabindex="-1">Anterior</a>
    </li>
    <?php for ($i=1; $i <= $totalPages; $i++): ?>
    <li class="page-item <?= $page === $i ? 'active' : '' ?>">
      <a class="page-link" href="?search=<?= urlencode($search) ?>&page=<?= $i ?>"><?= $i ?></a>
    </li>
    <?php endfor; ?>
    <li class="page-item <?= $page >= $totalPages ? 'disabled' : '' ?>">
      <a class="page-link" href="?search=<?= urlencode($search) ?>&page=<?= $page + 1 ?>">Siguiente</a>
    </li>
  </ul>
</nav>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<?php require_once __DIR__ . '/../templates/footer.php'; ?>
