<?php
// src/controllers/InviteController.php
class InviteController {
  public static function index($db) {
    $uid = $_SESSION['user']['id'];
    
    // Invites del usuario + contador
    $stmt = $db->prepare("SELECT invites_left FROM users WHERE id = ?");
    $stmt->execute([$uid]);
    $me = $stmt->fetch();
    $left = $me ? (int)$me['invites_left'] : 0;

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate']) && $left > 0) {
      validate_csrf();
      
      // Generar nuevo código
      $code = 'INV-' . strtoupper(bin2hex(random_bytes(4)));
      $db->prepare("INSERT INTO invites (id, code, issued_by, created_at) VALUES (UUID(), ?, ?, NOW())")->execute([$code, $uid]);
      $db->prepare("UPDATE users SET invites_left = invites_left - 1 WHERE id = ?")->execute([$uid]);
      
      flash('success', 'Código generado: ' . $code);
      redirect('invites');
    }

    // Listado de mis invites
    $list = $db->prepare("SELECT code, used_by, used_at, created_at FROM invites WHERE issued_by = ? ORDER BY created_at DESC");
    $list->execute([$uid]);
    $invites = $list->fetchAll();

    view('invites/index', ['invites'=>$invites, 'left'=>$left]);
  }
}