<?php
$title = 'Resumen de Cuentas';
require_once __DIR__ . '/../templates/header.php';
require_role('client');
csrf_check();

$u = current_user();
$pin_ok = $_SESSION['pin_ok'] ?? false;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['pin'])) {
  $pin = trim($_POST['pin'] ?? '');
  if ($u['pin_hash'] && password_verify($pin, $u['pin_hash'])) {
    $_SESSION['pin_ok'] = true;
    $pin_ok = true;
  } else {
    $error = 'PIN incorrecto';
  }
}

// Obtener plataformas para filtro
$platformsStmt = pdo()->query('SELECT id, name FROM platforms ORDER BY name');
$platforms = $platformsStmt->fetchAll();
$platformFilter = $_GET['platform'] ?? null;

// Nueva casilla para activar filtro de estado
$estadoFilter = $_GET['estado'] ?? 'todas'; // Puede ser 'todas', 'activas', 'vencidas'

if ($pin_ok) {
  $query = '
    SELECT a.*, p.name as platform
    FROM assigned_accounts a
    JOIN platforms p ON p.id = a.platform_id
    WHERE a.client_id = ?
  ';
  $params = [$u['id']];
  if ($platformFilter && $platformFilter !== 'all') {
    $query .= ' AND p.id = ?';
    $params[] = $platformFilter;
  }
  $query .= ' ORDER BY a.platform_id, a.email';

  $stmt = pdo()->prepare($query);
  $stmt->execute($params);
  $rows = $stmt->fetchAll();

  // Procesar fechas y estados
  foreach ($rows as &$row) {
    if (!empty($row['expiration_date'])) {
      $fechaExp = new DateTime($row['expiration_date']);
      $hoy = new DateTime();
      $diasRestantes = $hoy->diff($fechaExp)->format('%r%a');
      $row['dias_restantes'] = ((int)$diasRestantes < 0) ? 0 : (int)$diasRestantes;
      $row['expirada'] = ((int)$diasRestantes < 0); // Verdadero si la fecha ya pasó
    } else {
      $row['dias_restantes'] = null;
      $row['expirada'] = false;
    }
  }
  unset($row);

  // Aplicar filtro de estado desde la casilla
  if ($estadoFilter === 'activas') {
    $rows = array_filter($rows, function($r) { return !$r['expirada']; });
  } elseif ($estadoFilter === 'vencidas') {
    $rows = array_filter($rows, function($r) { return $r['expirada']; });
  }
}
?>

<?php if (!$pin_ok): ?>
  <div class="card card-body mb-3">
    <h3>Resumen de cuentas asignadas</h3>
    <p>Para ver tus cuentas asignadas, ingresa tu <strong>PIN</strong>.</p>
    <form method="post" class="row g-2">
      <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
      <div class="col-md-3">
        <input class="form-control" name="pin" placeholder="PIN" type="password" required>
      </div>
      <div class="col-md-2">
        <button class="btn btn-primary">Validar</button>
      </div>
    </form>
    <?php if (!empty($error)): ?><div class="alert alert-danger mt-2"><?= e($error) ?></div><?php endif; ?>
  </div>
<?php else: ?>
  <div class="alert alert-success">PIN validado. <a href="?reset_pin=1" class="ms-2">Cerrar</a></div>
  <?php if (!empty($_GET['reset_pin'])) { $_SESSION['pin_ok'] = false; header('Location: assigned_summary.php'); exit; } ?>

  <!-- Filtro de plataforma y estado -->
  <form method="get" class="mb-3 d-flex align-items-center">
    <label for="platform" class="me-2 mb-0">Filtrar por plataforma:</label>
    <select name="platform" id="platform" onchange="this.form.submit()" class="form-select w-auto d-inline-block me-3">
      <option value="all" <?= ($platformFilter === null || $platformFilter === 'all') ? 'selected' : '' ?>>Todas</option>
      <?php foreach ($platforms as $p): ?>
        <option value="<?= e($p['id']) ?>" <?= ($platformFilter == $p['id']) ? 'selected' : '' ?>>
          <?= e($p['name']) ?>
        </option>
      <?php endforeach; ?>
    </select>
    <label for="estado" class="me-2 mb-0">Estado:</label>
    <select name="estado" id="estado" onchange="this.form.submit()" class="form-select w-auto d-inline-block">
      <option value="todas" <?= ($estadoFilter == 'todas' ? 'selected' : '') ?>>Todas</option>
      <option value="activas" <?= ($estadoFilter == 'activas' ? 'selected' : '') ?>>Activas</option>
      <option value="vencidas" <?= ($estadoFilter == 'vencidas' ? 'selected' : '') ?>>Vencidas</option>
    </select>
  </form>

  <div class="table-responsive">
    <table class="table table-striped align-middle">
      <thead>
        <tr>
          <th>Plataforma</th>
          <th>Correo</th>
          <th>Fecha de Terminación</th>
          <th>Días Restantes</th>
          <th>Estado</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rows as $r): ?>
          <?php
            if ($r['expirada']) {
              $estado = 'Vencida';
              $clase = 'table-danger';
            } else {
              if ($r['dias_restantes'] === 0) {
                $estado = 'Vence hoy';
                $clase = 'table-warning';
              } elseif ($r['dias_restantes'] === 1) {
                $estado = 'Vence mañana';
                $clase = 'table-warning';
              } else {
                $estado = 'Activa';
                $clase = '';
              }
            }
          ?>
          <tr class="<?= $clase ?>">
            <td><?= e($r['platform']) ?></td>
            <td><?= e($r['email']) ?></td>
            <td><?= e($r['expiration_date'] ?: 'N/A') ?></td>
            <td><?= $r['dias_restantes'] !== null ? $r['dias_restantes'] : 'N/A' ?></td>
            <td><?= $estado ?></td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
<?php endif; ?>

<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'; ?>
