<?php
declare(strict_types=1);

/**
 * /functional/group/invite_action.php
 * Прийняття / відхилення запрошення в групу.
 *
 * ВАЖЛИВО:
 * - обробляє ТІЛЬКИ pending invite
 * - pending request користувач сам прийняти не може
 */

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);
}

/* login */
if (function_exists('require_login')) {
    require_login();
}

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

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

$meId = (int)($me['id'] ?? 0);

if (!function_exists('is_post')) {
    function is_post(): bool {
        return (string)($_SERVER['REQUEST_METHOD'] ?? '') === 'POST';
    }
}

if (!is_post()) {
    http_response_code(405);
    echo 'Method Not Allowed';
    exit;
}

$action = trim((string)($_POST['action'] ?? ''));
$groupId = (int)($_POST['group_id'] ?? 0);
$csrf = (string)($_POST['csrf'] ?? '');
$backRaw = trim((string)($_POST['back'] ?? ''));

if (!in_array($action, ['accept', 'reject'], true) || $groupId <= 0) {
    http_response_code(400);
    echo 'Bad Request';
    exit;
}

if (!g_csrf_check($csrf)) {
    if (function_exists('flash_set')) {
        flash_set('err', g_t('Помилка безпеки (CSRF).', 'Ошибка безопасности (CSRF).', 'Security error (CSRF).'));
    }
    redirect('/group.php');
}

if (!g_table_exists($pdo, 'groups') || !g_table_exists($pdo, 'group_members')) {
    if (function_exists('flash_set')) {
        flash_set('err', g_t('Модуль груп недоступний.', 'Модуль групп недоступен.', 'Groups module is unavailable.'));
    }
    redirect('/group.php');
}

/* safe back */
if ($backRaw !== '') {
    if (function_exists('safe_local_path')) {
        $back = safe_local_path($backRaw, '');
    } else {
        $back = (preg_match('~^/~', $backRaw) && !str_starts_with($backRaw, '//')) ? $backRaw : '';
    }
} else {
    $back = '';
}

/* group fetch */
$g = g_group_get($pdo, $groupId);
if (!$g) {
    if (function_exists('flash_set')) {
        flash_set('err', g_t('Групу не знайдено.', 'Группа не найдена.', 'Group not found.'));
    }
    redirect('/group.php');
}

$groupUrl = g_group_url($g);
if ($back === '') $back = $groupUrl;

$gmHasStatus      = g_column_exists($pdo, 'group_members', 'status');
$gmHasPendingKind = g_column_exists($pdo, 'group_members', 'pending_kind');

/* membership fetch: only invite */
try {
    if ($gmHasStatus) {
        $sql = "
            SELECT *
            FROM group_members
            WHERE group_id = ?
              AND user_id = ?
              AND status = 'pending'
        ";

        $args = [$groupId, $meId];

        if ($gmHasPendingKind) {
            $sql .= " AND (pending_kind = 'invite' OR pending_kind IS NULL OR pending_kind = '')";
        }

        $sql .= " LIMIT 1";

        $st = $pdo->prepare($sql);
        $st->execute($args);
    } else {
        $st = $pdo->prepare("
            SELECT *
            FROM group_members
            WHERE group_id = ?
              AND user_id = ?
            LIMIT 1
        ");
        $st->execute([$groupId, $meId]);
    }

    $membership = $st->fetch(PDO::FETCH_ASSOC) ?: null;
} catch (Throwable $e) {
    $membership = null;
}

if (!$membership) {
    if (function_exists('flash_set')) {
        flash_set('err', g_t(
            'Активного запрошення не знайдено.',
            'Активное приглашение не найдено.',
            'Active invite not found.'
        ));
    }
    redirect($back);
}

/* notifications helper */
$markInviteRead = static function(PDO $pdo, int $userId, int $groupId): void {
    try {
        if (!g_table_exists($pdo, 'notifications')) return;

        $hasReadAt = g_column_exists($pdo, 'notifications', 'read_at');
        $sql = "UPDATE notifications SET is_read=1";
        if ($hasReadAt) $sql .= ", read_at=NOW()";
        $sql .= " WHERE user_id=? AND type='group_invite' AND group_id=? AND is_read=0";

        $st = $pdo->prepare($sql);
        $st->execute([$userId, $groupId]);
    } catch (Throwable $e) {
        error_log('[group invite_action notify] ' . $e->getMessage());
    }
};

try {
    if ($action === 'accept') {
        if ($gmHasStatus) {
            $sql = "
                UPDATE group_members
                SET status='active'
            ";
            if ($gmHasPendingKind) {
                $sql .= ", pending_kind=NULL";
            }
            $sql .= "
                WHERE group_id=? AND user_id=? AND status='pending'
            ";
            if ($gmHasPendingKind) {
                $sql .= " AND (pending_kind='invite' OR pending_kind IS NULL OR pending_kind='')";
            }
            $sql .= " LIMIT 1";

            $st = $pdo->prepare($sql);
            $st->execute([$groupId, $meId]);
        }

        $markInviteRead($pdo, $meId, $groupId);

        if (function_exists('flash_set')) {
            flash_set('ok', g_t(
                'Ви приєдналися до групи ✅',
                'Вы присоединились к группе ✅',
                'You joined the group ✅'
            ));
        }

        redirect($groupUrl);
    }

    if ($action === 'reject') {
        if ($gmHasStatus) {
            $sql = "
                DELETE FROM group_members
                WHERE group_id=? AND user_id=? AND status='pending'
            ";
            if ($gmHasPendingKind) {
                $sql .= " AND (pending_kind='invite' OR pending_kind IS NULL OR pending_kind='')";
            }
            $sql .= " LIMIT 1";

            $st = $pdo->prepare($sql);
            $st->execute([$groupId, $meId]);
        } else {
            $st = $pdo->prepare("
                DELETE FROM group_members
                WHERE group_id=? AND user_id=?
                LIMIT 1
            ");
            $st->execute([$groupId, $meId]);
        }

        $markInviteRead($pdo, $meId, $groupId);

        if (function_exists('flash_set')) {
            flash_set('ok', g_t(
                'Запрошення відхилено.',
                'Приглашение отклонено.',
                'Invite declined.'
            ));
        }

        redirect('/group.php');
    }

    redirect($back);

} catch (Throwable $e) {
    error_log('[group invite_action] ' . $e->getMessage());

    if (function_exists('flash_set')) {
        flash_set('err', g_t(
            'Помилка сервера.',
            'Ошибка сервера.',
            'Server error.'
        ));
    }

    redirect($back);
}