<?php
session_start();
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/helpers.php';

// --- Variables de sesión y parámetros iniciales ---
$user_role = $_SESSION['user_role'] ?? '';
$user_id = $_SESSION['uid'] ?? 0;

$client_id = (int)($_GET['client_id'] ?? 0);
$page = max(1, (int)($_GET['page'] ?? 1));
$platform_id = isset($_GET['platform_id']) && $_GET['platform_id'] !== '' ? (int)$_GET['platform_id'] : null;
$search_email = trim($_GET['search_email'] ?? '');

// --- Validar cliente ---
if (!$client_id) {
    echo json_encode(['error' => 'Cliente no seleccionado.', 'html' => '']);
    exit;
}

if ($user_role !== 'superadmin') {
    $checkStmt = pdo()->prepare("SELECT COUNT(*) FROM users WHERE id = ? AND admin_id = ?");
    $checkStmt->execute([$client_id, $user_id]);
    if ($checkStmt->fetchColumn() == 0) {
        echo json_encode(['error' => 'Acceso denegado a este cliente.', 'html' => '']);
        exit;
    }
}

// --- Manejo de acciones POST: update y delete ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $action = $_POST['action'] ?? '';

    if ($action === 'update') {
        $id = (int)($_POST['id'] ?? 0);
        $email = $_POST['email'] ?? '';
        $expiration_date = $_POST['expiration_date'] ?? null;
        $price = isset($_POST['price']) ? floatval($_POST['price']) : null;

        $expiration_date = $expiration_date === '' ? null : $expiration_date;

        if ($id > 0 && filter_var($email, FILTER_VALIDATE_EMAIL)) {

            // Validar permiso para actualizar
            if ($user_role !== 'superadmin') {
                $validStmt = pdo()->prepare("SELECT COUNT(*) FROM assigned_accounts WHERE id = ? AND client_id = ? AND user_id = ?");
                $validStmt->execute([$id, $client_id, $user_id]);
            } else {
                $validStmt = pdo()->prepare("SELECT COUNT(*) FROM assigned_accounts WHERE id = ? AND client_id = ?");
                $validStmt->execute([$id, $client_id]);
            }
            if ($validStmt->fetchColumn() == 0) {
                echo json_encode(['success' => false, 'error' => 'No permitido actualizar esta asignación.']);
                exit;
            }

            // Ejecutar actualización
            $updateSql = "UPDATE assigned_accounts SET email = ?, expiration_date = ?, price = ? WHERE id = ? AND client_id = ?";
            $stmt = pdo()->prepare($updateSql);
            $success = $stmt->execute([$email, $expiration_date, $price, $id, $client_id]);

            echo json_encode(['success' => $success]);
            exit;
        }

        echo json_encode(['success' => false, 'error' => 'Datos inválidos o correo no válido.']);
        exit;
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);

        if ($id > 0) {
            // Validar permiso para eliminar
            if ($user_role !== 'superadmin') {
                $validStmt = pdo()->prepare("SELECT COUNT(*) FROM assigned_accounts WHERE id = ? AND client_id = ? AND user_id = ?");
                $validStmt->execute([$id, $client_id, $user_id]);
            } else {
                $validStmt = pdo()->prepare("SELECT COUNT(*) FROM assigned_accounts WHERE id = ? AND client_id = ?");
                $validStmt->execute([$id, $client_id]);
            }
            if ($validStmt->fetchColumn() == 0) {
                echo json_encode(['success' => false, 'error' => 'No permitido eliminar esta asignación.']);
                exit;
            }

            // Ejecutar eliminación
            $deleteSql = "DELETE FROM assigned_accounts WHERE id = ? AND client_id = ?";
            $stmt = pdo()->prepare($deleteSql);
            $success = $stmt->execute([$id, $client_id]);

            echo json_encode(['success' => $success]);
            exit;
        }

        echo json_encode(['success' => false, 'error' => 'ID inválido.']);
        exit;
    }

    // Acción no reconocida
    echo json_encode(['success' => false, 'error' => 'Acción no reconocida.']);
    exit;
}

// --- Consulta para paginación y filtros ---
$itemsPerPage = 10;
$offset = ($page - 1) * $itemsPerPage;

$params = [$client_id];
$whereSql = "WHERE a.client_id = ?";

if ($user_role !== 'superadmin') {
    $whereSql .= " AND a.user_id = ?";
    $params[] = $user_id;
}

if ($platform_id !== null) {
    $whereSql .= " AND a.platform_id = ?";
    $params[] = $platform_id;
}

if ($search_email !== '') {
    $whereSql .= " AND a.email LIKE ?";
    $params[] = "%{$search_email}%";
}

// Contar total ítems
$countSql = "SELECT COUNT(*) FROM assigned_accounts a $whereSql";
$countStmt = pdo()->prepare($countSql);
$countStmt->execute($params);
$totalItems = (int)$countStmt->fetchColumn();
$totalPages = max(1, ceil($totalItems / $itemsPerPage));

// Consulta paginada con unión
$sql = "SELECT a.id, p.name AS platform_name, a.email, a.expiration_date, a.price
        FROM assigned_accounts a
        INNER JOIN platforms p ON a.platform_id = p.id
        $whereSql
        ORDER BY a.id DESC
        LIMIT $itemsPerPage OFFSET $offset";

$stmt = pdo()->prepare($sql);
$stmt->execute($params);
$results = $stmt->fetchAll();

// --- Generar HTML ---
ob_start();
?>

<table class="table table-striped table-hover">
  <thead>
    <tr>
      <th>ID</th>
      <th>Plataforma</th>
      <th>Correo</th>
      <th>Caducidad</th>
      <th>Días restantes</th>
      <th>Precio</th>
      <th>Acciones</th>
    </tr>
  </thead>
  <tbody>
    <?php if (!$results): ?>
      <tr><td colspan="7" class="text-center">No hay cuentas asignadas.</td></tr>
    <?php else: ?>
      <?php foreach ($results as $row):
          $claseFila = '';
          $dias = '';
          if ($row['expiration_date']) {
              $diff = (strtotime($row['expiration_date']) - strtotime(date('Y-m-d'))) / 86400;
              if ($diff < 0) {
                  $dias = 'Expirada';
                  $claseFila = 'table-danger';
              } else if ($diff == 0) {
                  $dias = 'Vence hoy';
                  $claseFila = 'table-warning';
              } else if ($diff == 1) {
                  $dias = 'Vence mañana';
                  $claseFila = 'table-warning';
              } else {
                  $dias = (int)$diff . ' días';
              }
          } else {
              $dias = 'N/A';
          }
      ?>
      <tr data-id="<?= e($row['id']) ?>" class="<?= $claseFila ?>">
        <td><?= e($row['id']) ?></td>
        <td><?= e($row['platform_name']) ?></td>
        <td class="email-cell"><?= e($row['email']) ?></td>
        <td class="expiration-cell"><?= $row['expiration_date'] ? date('d/m/Y', strtotime($row['expiration_date'])) : 'N/A' ?></td>
        <td><?= $dias ?></td>
        <td class="price-cell"><?= number_format($row['price'], 2) ?></td>
        <td>
          <button type="button" class="btn btn-sm btn-outline-primary btn-edit">Editar</button>
          <button type="button" class="btn btn-sm btn-outline-danger btn-delete">Eliminar</button>
        </td>
      </tr>
      <?php endforeach; ?>
    <?php endif; ?>
  </tbody>
</table>

<?php if ($totalPages > 1): ?>
<nav aria-label="Paginación">
  <ul class="pagination">
    <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
      <a href="#" class="page-link" data-page="<?= $page - 1 ?>">Anterior</a>
    </li>
    <?php for ($i = 1; $i <= $totalPages; $i++): ?>
      <li class="page-item <?= ($i === $page) ? 'active' : '' ?>">
        <a href="#" class="page-link" data-page="<?= $i ?>"><?= $i ?></a>
      </li>
    <?php endfor; ?>
    <li class="page-item <?= ($page >= $totalPages) ? 'disabled' : '' ?>">
      <a href="#" class="page-link" data-page="<?= $page + 1 ?>">Siguiente</a>
    </li>
  </ul>
</nav>
<?php endif; ?>

<?php
$html = ob_get_clean();
echo json_encode(['html' => $html]);
?>
