<?php
declare(strict_types=1);

/**
 * /functional/group/leave.php
 * Вихід з групи (видаляє membership), owner не може вийти.
 *
 * Оновлено:
 * - SEO: noindex + no-store
 * - можна відкривати ?id= або ?g=slug
 * - тільки POST + CSRF (захист від CSRF/GET-виходу)
 * - перевірка наявності group_members
 */

require_once __DIR__ . '/../../includes/start.php';
require_once __DIR__ . '/_lib.php';

/* SEO: endpoint не індексуємо */
if (!headers_sent()) {
    header('X-Robots-Tag: noindex, nofollow, noarchive, nosnippet', true);
    header('Cache-Control: no-store, max-age=0', true);
}

if (function_exists('require_login')) {
    require_login();
} else {
    $me0 = g_me();
    if (!$me0) { header('Location: /login.php'); exit; }
}

$pdo = g_db();
$me  = g_me();

if (!$me || (int)($me['id'] ?? 0) <= 0) {
    header('Location: /login.php');
    exit;
}

/* group resolve: by id or slug */
$id   = (int)($_GET['id'] ?? 0);
$slug = trim((string)($_GET['g'] ?? ''));

$g = null;
if ($id > 0) {
    $g = g_group_get($pdo, $id);
} elseif ($slug !== '') {
    $g = g_group_get_by_slug($pdo, $slug);
}

if (!$g) { http_response_code(404); echo "Group not found"; exit; }

/* group_members table must exist */
if (!g_table_exists($pdo, 'group_members')) {
    http_response_code(500);
    echo "DB schema missing: group_members. Run migration.";
    exit;
}

/* owner can't leave */
if ((int)($g['owner_user_id'] ?? 0) === (int)$me['id']) {
    $url = g_group_url($g);
    $sep = (strpos($url, '?') !== false) ? '&' : '?';
    header('Location: ' . $url . $sep . 'm=owner_cant_leave');
    exit;
}

/* only POST + CSRF */
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    $url = g_group_url($g);
    $sep = (strpos($url, '?') !== false) ? '&' : '?';
    header('Location: ' . $url . $sep . 'm=leave_post');
    exit;
}

if (!g_csrf_check((string)($_POST['csrf'] ?? ''))) {
    $url = g_group_url($g);
    $sep = (strpos($url, '?') !== false) ? '&' : '?';
    header('Location: ' . $url . $sep . 'm=csrf');
    exit;
}

/* delete membership */
try {
    $st = $pdo->prepare("DELETE FROM group_members WHERE group_id=? AND user_id=?");
    $st->execute([(int)$g['id'], (int)$me['id']]);
} catch (Throwable $e) {
    error_log('[group leave] ' . $e->getMessage());
    $url = g_group_url($g);
    $sep = (strpos($url, '?') !== false) ? '&' : '?';
    header('Location: ' . $url . $sep . 'm=leave_error');
    exit;
}

header('Location: ' . g_group_url($g));
exit;