<?php
declare(strict_types=1);

/**
 * /blocks/create_post.php
 * Універсальний блок створення поста.
 *
 * Відповідає за:
 * - одну HTML-форму для головної, профілю і групи
 * - конфігурований action
 * - автоматичну заміну legacy action на новий core endpoint
 * - hidden group_id тільки для груп
 * - emoji picker
 * - poll UI
 * - базовий link preview
 * - file input
 * - вбудовані стилі компонента, щоб форма однаково виглядала всюди
 *
 * Як використовувати:
 *   $postAction   = '/functional/post/create.php';      // optional
 *   $postGroupId  = 0;                                  // optional
 *   $postBack     = $_SERVER['REQUEST_URI'] ?? '/';     // optional
 *   $postFormId   = 'createPostMain';                   // optional
 *   $postTextareaName = 'body';                         // optional
 *   $postSubmitLabel  = 'Опублікувати';                 // optional
 *   $postPlaceholder  = 'Що у вас нового?';            // optional
 */

if (!function_exists('h')) {
    function h(?string $s): string
    {
        return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('vm_cp_lang')) {
    function vm_cp_lang(): string
    {
        $lang = function_exists('lang') ? (string)lang() : (string)($_SESSION['lang'] ?? 'uk');
        return in_array($lang, ['uk', 'ru', 'en'], true) ? $lang : 'uk';
    }
}

if (!function_exists('vm_cp_t')) {
    function vm_cp_t(string $uk, string $ru, string $en): string
    {
        return match (vm_cp_lang()) {
            'ru' => $ru,
            'en' => $en,
            default => $uk,
        };
    }
}

if (!function_exists('vm_cp_normalize_action')) {
    function vm_cp_normalize_action(?string $action): string
    {
        $fallback = '/functional/post/create.php';
        $action = trim((string)$action);
        if ($action === '') return $fallback;

        if (preg_match('~^https?://~i', $action)) {
            $parts = parse_url($action);
            $path = (string)($parts['path'] ?? '');
            $query = isset($parts['query']) && $parts['query'] !== '' ? ('?' . $parts['query']) : '';
            $action = $path . $query;
        }

        if ($action === '' || $action[0] !== '/') {
            return $fallback;
        }

        if (str_starts_with($action, '//')) {
            return $fallback;
        }

        $pathOnly = (string)parse_url($action, PHP_URL_PATH);
        if ($pathOnly === '') {
            return $fallback;
        }

        $legacy = [
            '/post_create.php',
            '/profile/post_create.php',
        ];

        if (in_array($pathOnly, $legacy, true)) {
            return $fallback;
        }

        return $action;
    }
}

$postActionRaw       = isset($postAction) && is_string($postAction) ? $postAction : '';
$postAction          = vm_cp_normalize_action($postActionRaw);
$postGroupId         = isset($postGroupId) ? (int)$postGroupId : 0;
$postBack            = isset($postBack) && is_string($postBack) && $postBack !== '' ? $postBack : (string)($_SERVER['REQUEST_URI'] ?? '/');
$postFormId          = isset($postFormId) && is_string($postFormId) && $postFormId !== '' ? $postFormId : 'vmCreatePostForm';
$postTextareaName    = isset($postTextareaName) && is_string($postTextareaName) && $postTextareaName !== '' ? $postTextareaName : 'body';
$postSubmitLabel     = isset($postSubmitLabel) && is_string($postSubmitLabel) && $postSubmitLabel !== '' ? $postSubmitLabel : vm_cp_t('Опублікувати', 'Опубликовать', 'Publish');
$postPlaceholder     = isset($postPlaceholder) && is_string($postPlaceholder) && $postPlaceholder !== '' ? $postPlaceholder : vm_cp_t('Що у вас нового?', 'Что у вас нового?', "What's new?");
$postPollEnabled     = isset($postPollEnabled) ? (bool)$postPollEnabled : true;
$postAllowFiles      = isset($postAllowFiles) ? (bool)$postAllowFiles : true;
$postMaxFilesLabel   = isset($postMaxFilesLabel) && is_string($postMaxFilesLabel) && $postMaxFilesLabel !== '' ? $postMaxFilesLabel : vm_cp_t('Можна вибрати кілька файлів', 'Можно выбрать несколько файлов', 'You can select multiple files');
$postAccept          = isset($postAccept) && is_string($postAccept) && $postAccept !== '' ? $postAccept : 'image/*,audio/*,video/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.zip,.rar,.7z,.webp';

$postEmojiLabel      = isset($postEmojiLabel) && is_string($postEmojiLabel) && $postEmojiLabel !== '' ? $postEmojiLabel : 'Emoji';
$postPollLabel       = isset($postPollLabel) && is_string($postPollLabel) && $postPollLabel !== '' ? $postPollLabel : vm_cp_t('Опитування', 'Опрос', 'Poll');
$postFilesLabel      = isset($postFilesLabel) && is_string($postFilesLabel) && $postFilesLabel !== '' ? $postFilesLabel : vm_cp_t('Файли', 'Файлы', 'Files');
$postNoFileLabel     = isset($postNoFileLabel) && is_string($postNoFileLabel) && $postNoFileLabel !== '' ? $postNoFileLabel : vm_cp_t('Файл не вибрано', 'Файл не выбран', 'No file selected');
$postManyFilesTpl    = isset($postManyFilesTpl) && is_string($postManyFilesTpl) && $postManyFilesTpl !== '' ? $postManyFilesTpl : vm_cp_t('Обрано файлів: %d', 'Выбрано файлов: %d', 'Selected files: %d');

$postPollQuestionPlaceholder = isset($postPollQuestionPlaceholder) && is_string($postPollQuestionPlaceholder) && $postPollQuestionPlaceholder !== ''
    ? $postPollQuestionPlaceholder
    : vm_cp_t('Питання опитування', 'Вопрос опроса', 'Poll question');

$postPollOption1Placeholder = isset($postPollOption1Placeholder) && is_string($postPollOption1Placeholder) && $postPollOption1Placeholder !== ''
    ? $postPollOption1Placeholder
    : vm_cp_t('Варіант 1', 'Вариант 1', 'Option 1');

$postPollOption2Placeholder = isset($postPollOption2Placeholder) && is_string($postPollOption2Placeholder) && $postPollOption2Placeholder !== ''
    ? $postPollOption2Placeholder
    : vm_cp_t('Варіант 2', 'Вариант 2', 'Option 2');

$postPollOption3Placeholder = isset($postPollOption3Placeholder) && is_string($postPollOption3Placeholder) && $postPollOption3Placeholder !== ''
    ? $postPollOption3Placeholder
    : vm_cp_t('Варіант 3', 'Вариант 3', 'Option 3');

$postPollOption4Placeholder = isset($postPollOption4Placeholder) && is_string($postPollOption4Placeholder) && $postPollOption4Placeholder !== ''
    ? $postPollOption4Placeholder
    : vm_cp_t('Варіант 4', 'Вариант 4', 'Option 4');

$csrf = function_exists('csrf_token') ? (string)csrf_token() : (string)($_SESSION['csrf_token'] ?? '');
$previewId = $postFormId . '_preview';
$emojiBoxId = $postFormId . '_emoji';
$pollBoxId = $postFormId . '_poll';
$fileInputId = $postFormId . '_files';
$fileNameId = $postFormId . '_file_name';

$emojis = ['😀','😁','😂','🤣','😊','😍','😘','😎','🤔','😢','😭','😡','👍','👎','👏','🔥','❤️','💙','💛','💚','🎉','✅'];

$vmCpMe = isset($me) && is_array($me) ? $me : (function_exists('current_user') ? current_user() : null);
$vmCpRestrState = (is_array($vmCpMe) && !empty($vmCpMe['id']) && isset($pdo) && $pdo instanceof PDO && function_exists('ar_get_state'))
    ? ar_get_state($pdo, (int)$vmCpMe['id'])
    : [];
$vmCpPostBlocked = is_array($vmCpRestrState) && function_exists('ar_is_action_blocked')
    ? ar_is_action_blocked($vmCpRestrState, 'posts')
    : false;
$vmCpPostBlockedText = $vmCpPostBlocked && function_exists('ar_action_error')
    ? ar_action_error($vmCpRestrState, 'posts')
    : '';

if (!defined('VM_POST_CREATE_ASSETS_PRINTED')) {
    define('VM_POST_CREATE_ASSETS_PRINTED', true);
    ?>
    <style>
      .vm-post-create-card{
        background:#fff;
        border:1px solid #d8dee6;
        border-radius:18px;
        padding:16px;
        box-shadow:0 2px 10px rgba(15,23,42,.04);
        margin-bottom:16px;
      }
      .vm-post-create-form{
        display:flex;
        flex-direction:column;
        gap:12px;
      }
      .vm-post-create-top{
        position:relative;
      }
      .vm-post-create-textarea{
        width:100%;
        min-height:126px;
        resize:vertical;
        border:1px solid #cfd7e3;
        border-radius:14px;
        padding:16px 18px;
        font-size:18px;
        line-height:1.45;
        color:#1f2937;
        background:#fff;
        outline:none;
        transition:border-color .15s ease, box-shadow .15s ease, background-color .15s ease;
      }
      .vm-post-create-textarea::placeholder{
        color:#6b7280;
      }
      .vm-post-create-textarea:focus{
        border-color:#6aa9ff;
        box-shadow:0 0 0 3px rgba(59,130,246,.14);
      }

      .vm-post-create-toolbar{
        display:flex;
        gap:10px;
        align-items:center;
        justify-content:space-between;
        flex-wrap:wrap;
      }
      .vm-post-create-tools{
        display:flex;
        gap:10px;
        align-items:center;
        flex-wrap:wrap;
        min-width:0;
      }
      .vm-post-tool-btn,
      .vm-post-file-btn{
        display:inline-flex;
        align-items:center;
        justify-content:center;
        gap:8px;
        height:42px;
        padding:0 14px;
        border:1px solid #d2d9e4;
        border-radius:12px;
        background:#fff;
        color:#1f2937;
        font-size:16px;
        font-weight:600;
        text-decoration:none;
        cursor:pointer;
        transition:background-color .15s ease, border-color .15s ease, box-shadow .15s ease, transform .15s ease;
        user-select:none;
      }
      .vm-post-tool-btn:hover,
      .vm-post-file-btn:hover{
        background:#f8fafc;
        border-color:#b8c5d6;
      }
      .vm-post-tool-btn:focus,
      .vm-post-file-btn:focus{
        outline:none;
        box-shadow:0 0 0 3px rgba(59,130,246,.14);
      }
      .vm-post-tool-btn.is-open{
        background:#eef4ff;
        border-color:#8db6ff;
        color:#1d4ed8;
      }

      .vm-post-file-wrap{
        display:inline-flex;
        align-items:center;
        gap:10px;
        flex-wrap:wrap;
      }
      .vm-post-file-input{
        position:absolute !important;
        width:1px !important;
        height:1px !important;
        padding:0 !important;
        margin:-1px !important;
        overflow:hidden !important;
        clip:rect(0,0,0,0) !important;
        white-space:nowrap !important;
        border:0 !important;
      }
      .vm-post-file-name{
        color:#4b5563;
        font-size:15px;
        max-width:320px;
        overflow:hidden;
        text-overflow:ellipsis;
        white-space:nowrap;
      }

      .vm-post-create-actions{
        display:flex;
        align-items:center;
        gap:12px;
        margin-left:auto;
      }
      .vm-post-submit-btn{
        display:inline-flex;
        align-items:center;
        justify-content:center;
        min-width:156px;
        height:46px;
        border:0;
        border-radius:12px;
        background:#1f6feb;
        color:#fff;
        font-size:16px;
        font-weight:700;
        padding:0 18px;
        cursor:pointer;
        transition:background-color .15s ease, transform .15s ease, box-shadow .15s ease;
        box-shadow:0 6px 16px rgba(31,111,235,.18);
      }
      .vm-post-submit-btn:hover{
        background:#1859bd;
      }
      .vm-post-submit-btn:active{
        transform:translateY(1px);
      }

      .vm-post-files-hint{
        margin-top:-4px;
        color:#6b7280;
        font-size:14px;
      }

      .vm-post-emoji-box,
      .vm-post-poll-box,
      .vm-post-link-preview{
        border:1px solid #d8dee6;
        border-radius:14px;
        background:#f8fafc;
      }

      .vm-post-emoji-box{
        display:flex;
        flex-wrap:wrap;
        gap:8px;
        padding:12px;
      }
      .vm-post-emoji-btn{
        width:40px;
        height:40px;
        border:1px solid #d7dce5;
        border-radius:10px;
        background:#fff;
        font-size:22px;
        line-height:1;
        cursor:pointer;
        transition:transform .12s ease, background-color .12s ease, border-color .12s ease;
      }
      .vm-post-emoji-btn:hover{
        transform:translateY(-1px);
        background:#f3f7ff;
        border-color:#9bbcf9;
      }

      .vm-post-poll-box{
        padding:12px;
      }
      .vm-post-poll-row + .vm-post-poll-row{
        margin-top:10px;
      }
      .vm-post-poll-input{
        width:100%;
        height:44px;
        border:1px solid #cfd7e3;
        border-radius:12px;
        background:#fff;
        padding:0 14px;
        font-size:15px;
        color:#1f2937;
        outline:none;
      }
      .vm-post-poll-input:focus{
        border-color:#6aa9ff;
        box-shadow:0 0 0 3px rgba(59,130,246,.14);
      }

      .vm-post-link-preview{
        padding:12px;
        overflow:hidden;
      }

      @media (max-width: 767.98px){
        .vm-post-create-card{
          padding:12px;
          border-radius:16px;
        }
        .vm-post-create-textarea{
          min-height:110px;
          font-size:17px;
          padding:14px 15px;
        }
        .vm-post-create-toolbar{
          flex-direction:column;
          align-items:stretch;
        }
        .vm-post-create-tools{
          width:100%;
        }
        .vm-post-file-wrap{
          width:100%;
          align-items:flex-start;
        }
        .vm-post-file-name{
          max-width:100%;
          white-space:normal;
          word-break:break-word;
        }
        .vm-post-create-actions{
          width:100%;
          margin-left:0;
        }
        .vm-post-submit-btn{
          width:100%;
          min-width:0;
        }
      }
    </style>
    <?php
}
?>

<?php if ($vmCpPostBlocked): ?>
  <div class="alert alert-warning mb-3"><?= h($vmCpPostBlockedText) ?></div>
  <?php return; ?>
<?php endif; ?>

<div class="vm-post-create-card" data-post-create>
  <form
      id="<?= h($postFormId) ?>"
      class="vm-post-create-form"
      method="post"
      action="<?= h($postAction) ?>"
      enctype="multipart/form-data"
      accept-charset="UTF-8"
  >
    <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
    <input type="hidden" name="back" value="<?= h($postBack) ?>">

    <?php if ($postGroupId > 0): ?>
      <input type="hidden" name="group_id" value="<?= (int)$postGroupId ?>">
    <?php endif; ?>

    <div class="vm-post-create-top">
      <textarea
          name="<?= h($postTextareaName) ?>"
          class="vm-post-create-textarea"
          rows="5"
          placeholder="<?= h($postPlaceholder) ?>"
          data-role="post-body"
          data-preview-id="<?= h($previewId) ?>"
      ></textarea>
    </div>

    <div class="vm-post-create-toolbar">
      <div class="vm-post-create-tools">
        <button type="button" class="vm-post-tool-btn" data-toggle-target="<?= h($emojiBoxId) ?>">😊 <?= h($postEmojiLabel) ?></button>

        <?php if ($postPollEnabled): ?>
          <button type="button" class="vm-post-tool-btn" data-toggle-target="<?= h($pollBoxId) ?>">📊 <?= h($postPollLabel) ?></button>
        <?php endif; ?>

        <?php if ($postAllowFiles): ?>
          <div class="vm-post-file-wrap">
            <label class="vm-post-file-trigger" for="<?= h($fileInputId) ?>">
              <input
                  id="<?= h($fileInputId) ?>"
                  type="file"
                  name="attachments[]"
                  multiple
                  accept="<?= h($postAccept) ?>"
                  class="vm-post-file-input"
              >
              <span class="vm-post-file-btn">📎 <?= h($postFilesLabel) ?></span>
            </label>
            <div
              id="<?= h($fileNameId) ?>"
              class="vm-post-file-name"
              data-file-name
              data-empty-label="<?= h($postNoFileLabel) ?>"
              data-many-template="<?= h($postManyFilesTpl) ?>"
            ><?= h($postNoFileLabel) ?></div>
          </div>
        <?php endif; ?>
      </div>

      <div class="vm-post-create-actions">
        <button type="submit" class="vm-post-submit-btn"><?= h($postSubmitLabel) ?></button>
      </div>
    </div>

    <?php if ($postAllowFiles): ?>
      <div class="vm-post-files-hint"><?= h($postMaxFilesLabel) ?></div>
    <?php endif; ?>

    <div id="<?= h($emojiBoxId) ?>" class="vm-post-emoji-box" hidden>
      <?php foreach ($emojis as $emoji): ?>
        <button type="button" class="vm-post-emoji-btn" data-emoji="<?= h($emoji) ?>"><?= h($emoji) ?></button>
      <?php endforeach; ?>
    </div>

    <?php if ($postPollEnabled): ?>
      <div id="<?= h($pollBoxId) ?>" class="vm-post-poll-box" hidden>
        <div class="vm-post-poll-row">
          <input type="text" name="poll_question" class="vm-post-poll-input" placeholder="<?= h($postPollQuestionPlaceholder) ?>" disabled>
        </div>

        <div class="vm-post-poll-row">
          <input type="text" name="poll_options[]" class="vm-post-poll-input" placeholder="<?= h($postPollOption1Placeholder) ?>" disabled>
        </div>
        <div class="vm-post-poll-row">
          <input type="text" name="poll_options[]" class="vm-post-poll-input" placeholder="<?= h($postPollOption2Placeholder) ?>" disabled>
        </div>
        <div class="vm-post-poll-row">
          <input type="text" name="poll_options[]" class="vm-post-poll-input" placeholder="<?= h($postPollOption3Placeholder) ?>" disabled>
        </div>
        <div class="vm-post-poll-row">
          <input type="text" name="poll_options[]" class="vm-post-poll-input" placeholder="<?= h($postPollOption4Placeholder) ?>" disabled>
        </div>
      </div>
    <?php endif; ?>

    <div id="<?= h($previewId) ?>" class="vm-post-link-preview" hidden></div>
  </form>
</div>

<script>
(function () {
  const form = document.getElementById(<?= json_encode($postFormId) ?>);
  if (!form) return;

  const body = form.querySelector('[data-role="post-body"]');
  const emojiBox = document.getElementById(<?= json_encode($emojiBoxId) ?>);
  const pollBox = document.getElementById(<?= json_encode($pollBoxId) ?>);
  const preview = document.getElementById(<?= json_encode($previewId) ?>);
  const fileInput = document.getElementById(<?= json_encode($fileInputId) ?>);
  const fileName  = document.getElementById(<?= json_encode($fileNameId) ?>);

  function syncToggleButtonState(btn, box) {
    if (!btn || !box) return;
    btn.classList.toggle('is-open', !box.hidden);
  }

  function syncPollDisabledState() {
    if (!pollBox) return;
    pollBox.querySelectorAll('input, textarea, select').forEach(function (el) {
      el.disabled = pollBox.hidden;
    });
  }

  form.querySelectorAll('[data-toggle-target]').forEach(function (btn) {
    btn.addEventListener('click', function () {
      const id = btn.getAttribute('data-toggle-target');
      const box = document.getElementById(id);
      if (!box) return;

      box.hidden = !box.hidden;
      syncToggleButtonState(btn, box);

      if (pollBox && box === pollBox) {
        syncPollDisabledState();
      }
    });

    const id = btn.getAttribute('data-toggle-target');
    const box = document.getElementById(id);
    if (box) {
      syncToggleButtonState(btn, box);
    }
  });

  syncPollDisabledState();

  if (fileInput && fileName) {
    const emptyLabel = fileName.getAttribute('data-empty-label') || '';
    const manyTpl = fileName.getAttribute('data-many-template') || '%d';

    fileInput.addEventListener('change', function () {
      const files = fileInput.files;
      if (!files || files.length === 0) {
        fileName.textContent = emptyLabel;
        return;
      }

      if (files.length === 1) {
        fileName.textContent = files[0].name || emptyLabel;
        return;
      }

      fileName.textContent = manyTpl.replace('%d', String(files.length));
    });
  }

  if (emojiBox && body) {
    emojiBox.querySelectorAll('[data-emoji]').forEach(function (btn) {
      btn.addEventListener('click', function () {
        const emoji = btn.getAttribute('data-emoji') || '';
        const start = body.selectionStart || 0;
        const end   = body.selectionEnd || 0;
        const value = body.value || '';

        body.value = value.slice(0, start) + emoji + value.slice(end);
        body.focus();

        const pos = start + emoji.length;
        body.setSelectionRange(pos, pos);
        body.dispatchEvent(new Event('input', { bubbles: true }));
      });
    });
  }

  let previewTimer = null;
  let previewController = null;

  function firstUrl(text) {
    const m = String(text || '').match(/https?:\/\/[^\s<>"']+/i);
    return m ? m[0] : '';
  }

  async function loadPreview(url) {
    if (!preview) return;

    if (previewController) previewController.abort();
    previewController = new AbortController();

    try {
      const res = await fetch('/link_preview.php?url=' + encodeURIComponent(url), {
        credentials: 'same-origin',
        signal: previewController.signal
      });

      if (!res.ok) throw new Error('preview');

      const html = await res.text();
      if (!html.trim()) {
        preview.hidden = true;
        preview.innerHTML = '';
        return;
      }

      preview.innerHTML = html;
      preview.hidden = false;
    } catch (e) {
      preview.hidden = true;
      preview.innerHTML = '';
    }
  }

  if (body && preview) {
    body.addEventListener('input', function () {
      clearTimeout(previewTimer);
      previewTimer = setTimeout(function () {
        const url = firstUrl(body.value);

        if (!url) {
          preview.hidden = true;
          preview.innerHTML = '';
          return;
        }

        loadPreview(url);
      }, 500);
    });
  }
})();
</script>