<?php
namespace Thirty\controllers; class InvitesController{ private static function random_code($len=10){ $c='ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; $o=''; for($i=0;$i<$len;$i++) $o.=$c[random_int(0,strlen($c)-1)]; return $o; } public static function index(){ require_auth(); global $DB; $uid=user()['id']; $codes=$DB->prepare('SELECT id,code,status,uses,max_uses,expires_at,created_at FROM invites WHERE creator_user_id=? ORDER BY created_at DESC'); $codes->execute([$uid]); $rows=$codes->fetchAll(); $rem=$DB->prepare('SELECT remaining_invites FROM users WHERE id=?'); $rem->execute([$uid]); $remaining=(int)$rem->fetchColumn(); view('invites/index',['codes'=>$rows,'remaining'=>$remaining]); } public static function create(){ require_auth(); verify_csrf(); global $DB; $uid=user()['id']; $rem=$DB->prepare('SELECT remaining_invites FROM users WHERE id=?'); $rem->execute([$uid]); $remaining=(int)$rem->fetchColumn(); if($remaining<=0){ set_flash('No te quedan invitaciones.'); redirect(base_url('/invites')); } $code=self::random_code(10); $DB->beginTransaction(); try{ $DB->prepare('UPDATE users SET remaining_invites=remaining_invites-1 WHERE id=?')->execute([$uid]); $DB->prepare('INSERT INTO invites (code,creator_user_id,max_uses) VALUES (?,?,1)')->execute([$code,$uid]); $DB->commit(); set_flash('Invitación creada: '.$code);} catch(\Throwable $e){ $DB->rollBack(); set_flash('No se pudo crear la invitación.'); } redirect(base_url('/invites')); } public static function revoke(){ require_auth(); verify_csrf(); global $DB; $uid=user()['id']; $iid=(int)($_POST['invite_id']??0); $upd=$DB->prepare('UPDATE invites SET status="revoked" WHERE id=? AND creator_user_id=? AND uses=0 AND status="active"'); $upd->execute([$iid,$uid]); if($upd->rowCount()>0){ $DB->prepare('UPDATE users SET remaining_invites=remaining_invites+1 WHERE id=?')->execute([$uid]); set_flash('Invitación revocada.'); } else { set_flash('No se puede revocar (quizá ya usada).'); } redirect(base_url('/invites')); }}
