<?php
declare(strict_types=1);

/**
 * /functional/group/post_create.php
 * Створення поста В ГРУПІ через спільне ядро /functional/post/_lib.php
 */

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

require_login();

if (!headers_sent()) {
    header('X-Robots-Tag: noindex, nofollow, noarchive, nosnippet', true);
    header('Cache-Control: no-store, max-age=0', true);
}

if (!isset($pdo) || !($pdo instanceof PDO)) $pdo = db();
if (!isset($me) || !is_array($me)) $me = current_user();

if (!function_exists('gp_group_url')) {
    function gp_group_url(array $g): string
    {
        if (function_exists('g_group_url')) {
            return (string)g_group_url($g);
        }

        $slug = trim((string)($g['slug'] ?? ''));
        if ($slug !== '') {
            return '/functional/group/view.php?g=' . rawurlencode($slug);
        }

        return '/functional/group/view.php?id=' . (int)($g['id'] ?? 0);
    }
}

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

$csrfOk = false;
if (function_exists('csrf_check') && function_exists('post_str')) {
    $csrfOk = (bool)csrf_check(post_str('csrf'));
} else {
    $csrfOk = function_exists('g_csrf_check')
        ? (bool)g_csrf_check((string)($_POST['csrf'] ?? ''))
        : false;
}

if (!$csrfOk) {
    flash_set('err', function_exists('t') ? t('bad_csrf') : 'Bad CSRF token.');
    redirect('/functional/group/index.php');
}

$groupId = (int)($_POST['group_id'] ?? 0);
if ($groupId <= 0) {
    flash_set('err', 'Error: group_id required.');
    redirect('/functional/group/index.php');
}

if (!g_table_exists($pdo, 'groups')) {
    flash_set('err', 'Error: groups table missing.');
    redirect('/functional/group/index.php');
}
if (!g_table_exists($pdo, 'posts')) {
    flash_set('err', 'Error: posts table missing.');
    redirect('/functional/group/index.php');
}
if (!g_column_exists($pdo, 'posts', 'group_id')) {
    flash_set('err', 'Error: posts.group_id missing. Run migration for groups posts.');
    redirect('/functional/group/index.php');
}

$st = $pdo->prepare("SELECT * FROM `groups` WHERE id=? LIMIT 1");
$st->execute([$groupId]);
$group = $st->fetch(PDO::FETCH_ASSOC) ?: null;

if (!$group) {
    flash_set('err', 'Error: Group not found.');
    redirect('/functional/group/index.php');
}

$groupUrl = gp_group_url($group);

$backRaw = function_exists('post_str')
    ? (string)post_str('back', '')
    : (string)($_POST['back'] ?? '');

$back = vm_post_safe_back($backRaw, $groupUrl);
if ($back === '' || $back === '/') {
    $back = $groupUrl;
}

$vmGroupPostRestrictionState = function_exists('ar_get_state') ? ar_get_state($pdo, (int)($me['id'] ?? 0)) : [];
if (is_array($vmGroupPostRestrictionState) && function_exists('ar_is_action_blocked') && ar_is_action_blocked($vmGroupPostRestrictionState, 'posts')) {
    flash_set('err', function_exists('ar_action_error')
        ? ar_action_error($vmGroupPostRestrictionState, 'posts')
        : vm_post_t('Вам заборонено публікувати пости.', 'Вам запрещено публиковать посты.', 'You are not allowed to create posts.'));
    redirect($back);
}

$isAdmin = ((string)($me['role'] ?? '') === 'admin');
$isOwner = ((int)($group['owner_user_id'] ?? 0) === (int)($me['id'] ?? 0));
$isMember = false;

if (!$isAdmin && !$isOwner) {
    if (!g_table_exists($pdo, 'group_members')) {
        flash_set('err', 'Error: group_members missing.');
        redirect($groupUrl);
    }

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

    if ($gmHasStatus) {
        $st = $pdo->prepare("
            SELECT 1
            FROM group_members
            WHERE group_id=? AND user_id=? AND status='active'
            LIMIT 1
        ");
        $st->execute([(int)$group['id'], (int)$me['id']]);
    } else {
        $st = $pdo->prepare("
            SELECT 1
            FROM group_members
            WHERE group_id=? AND user_id=?
            LIMIT 1
        ");
        $st->execute([(int)$group['id'], (int)$me['id']]);
    }

    $isMember = (bool)$st->fetchColumn();
}

if (!$isAdmin && !$isOwner && !$isMember) {
    flash_set('err', 'Error: No permission to post in this group.');
    redirect($groupUrl);
}

$body = function_exists('post_str')
    ? (string)post_str('body', '')
    : (string)($_POST['body'] ?? '');

$pollQuestion = function_exists('post_str')
    ? (string)post_str('poll_question', '')
    : (string)($_POST['poll_question'] ?? '');

$pollOptions = $_POST['poll_options'] ?? [];
if (!is_array($pollOptions)) $pollOptions = [];

$postFiles = [];
foreach (['attachments', 'files', 'post_files'] as $field) {
    if (isset($_FILES[$field])) {
        $postFiles = $_FILES[$field];
        break;
    }
}

$projectRoot = realpath(dirname(__DIR__, 2)) ?: dirname(__DIR__, 2);

$res = vm_post_create_core([
    'pdo'           => $pdo,
    'me'            => $me,
    'project_root'  => $projectRoot,
    'body'          => $body,
    'group_id'      => (int)$group['id'],
    'files'         => $postFiles,
    'poll_question' => $pollQuestion,
    'poll_options'  => $pollOptions,
]);

if (!$res['ok']) {
    $msg = trim((string)($res['error'] ?? ''));
    if ($msg === '') {
        $msg = vm_post_t(
            'Не вдалося створити пост.',
            'Не удалось создать пост.',
            'Failed to create post.'
        );
    }

    flash_set('err', $msg);
    redirect($back);
}

$uploadError = trim((string)($res['upload_error'] ?? ''));
if ($uploadError !== '') {
    flash_set('err', $uploadError);
}

flash_set('ok', (function_exists('t') ? t('publish') : 'Published') . ' OK');
redirect($back);
