<?php
$isEdit = isset($task);
$pageTitle = $isEdit ? t('edit') . ': ' . Helper::e($task['title']) : t('new_task');
$currentStatusId = Helper::post('status_id', $task['status_id'] ?? ($parentId ? null : ($statuses[0]['id'] ?? null)));
if (Helper::get('status_id')) $currentStatusId = Helper::get('status_id');
$currentLabels = $taskLabels ?? Helper::post('labels', []);
?>

<div class="page-header">
    <div class="page-header-left">
        <a href="<?= $isEdit ? '/task/' . $task['id'] : '/project/' . $project['id'] ?>" class="btn btn-ghost btn-sm">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
            <?= t('back') ?>
        </a>
        <h1 class="page-title"><?= $pageTitle ?></h1>
    </div>
</div>

<?php if (!empty($errors)): ?>
<div class="alert alert-error">
    <?php foreach ($errors as $e): ?><div><?= Helper::e($e) ?></div><?php endforeach; ?>
</div>
<?php endif; ?>

<div class="task-form-layout">
    <form method="POST" enctype="multipart/form-data"
          action="<?= $isEdit ? '/task/' . $task['id'] . '/edit' : '/task/create/' . $project['id'] ?>">
        <?= Helper::csrf() ?>
        <?php if ($isEdit): ?>
        <input type="hidden" name="action" value="update">
        <?php endif; ?>
        <!-- Main fields -->
        <div class="card">
            <div class="card-body">
                <div class="form-group">
                    <label class="form-label" for="title"><?= t('task_title') ?> *</label>
                    <input type="text" id="title" name="title" class="form-input form-input-lg" required autofocus
                           value="<?= Helper::e($isEdit ? $task['title'] : Helper::post('title')) ?>">
                </div>
                <div class="form-group">
                    <label class="form-label">
                        <?= t('task_desc') ?>
                        <?php if (in_array('description', $requiredFields)): ?><span class="required-star">*</span><?php endif; ?>
                    </label>
                    <div id="desc-editor" class="rich-editor-wrap" style="min-height:120px"></div>
                    <input type="hidden" name="description" id="desc-hidden">
                </div>
            </div>
        </div>

        <!-- Sidebar fields -->
        <div class="task-form-sidebar">
            <div class="card">
                <div class="card-body">
                    <div class="form-group">
                        <label class="form-label"><?= t('task_status') ?></label>
                        <select name="status_id" class="form-select">
                            <?php foreach ($statuses as $s): ?>
                            <option value="<?= $s['id'] ?>" <?= $currentStatusId == $s['id'] ? 'selected' : '' ?>
                                    style="--dot-color:<?= $s['color'] ?>">
                                <?= Helper::e($s['name']) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="form-label"><?= t('priority') ?></label>
                        <select name="priority" class="form-select">
                            <?php foreach (['low','medium','high','urgent'] as $p): ?>
                            <option value="<?= $p ?>" <?= ($isEdit ? $task['priority'] : Helper::post('priority','medium')) === $p ? 'selected' : '' ?>>
                                <?= t('priority_' . $p) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <?php
$_assignedUserIds     = array_map('intval', $assignedUserIds     ?? []);
$_assignedExternalIds = array_map('intval', $assignedExternalIds ?? []);
$_allProjectExts      = $projectExternals ?? [];
$_projExtWithEmail    = array_values(array_filter($_allProjectExts, fn($p) => !empty($p['email'])));
$_projDummies         = array_values(array_filter($_allProjectExts, fn($p) => empty($p['email'])));
?>
                    <div class="form-group">
                        <label class="form-label"><?= t('assigned_to') ?></label>
                        <!-- Project members as checkboxes -->
                        <?php if (!empty($members)): ?>
                        <div class="assignee-member-list">
                            <?php foreach ($members as $m): ?>
                            <label class="assignee-member-check">
                                <input type="checkbox" name="assignee_user_ids[]" value="<?= (int)$m['user_id'] ?>"
                                       <?= in_array((int)$m['user_id'], $_assignedUserIds) ? 'checked' : '' ?>>
                                <?= Helper::avatar(['username' => $m['username'], 'avatar' => $m['avatar'] ?? null, 'id' => $m['user_id']], 22) ?>
                                <span><?= Helper::e($m['username']) ?></span>
                            </label>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                        <!-- Project externals with email (portal access) -->
                        <?php if (!empty($_projExtWithEmail)): ?>
                        <div class="assignee-member-list" style="margin-top:6px;padding-top:6px;border-top:1px solid var(--border)">
                            <div class="ext-section-label"><?= t('external_participants') ?> (<?= t('ext_portal_link') ?>)</div>
                            <?php foreach ($_projExtWithEmail as $pe): ?>
                            <label class="assignee-member-check">
                                <input type="checkbox" name="assignee_external_ids[]" value="<?= (int)$pe['id'] ?>"
                                       <?= in_array((int)$pe['id'], $_assignedExternalIds) ? 'checked' : '' ?>>
                                <span class="avatar-initials avatar-ext" style="width:22px;height:22px;font-size:9px"><?= Helper::e(mb_strtoupper(mb_substr($pe['name'],0,1))) ?></span>
                                <span><?= Helper::e($pe['name']) ?></span>
                                <span class="badge-ext" style="font-size:10px"><?= Helper::e($pe['email']) ?></span>
                            </label>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                        <!-- Dummy names: project-level placeholders (checkboxes) + ad-hoc (free text) -->
                        <div class="ext-assignee-section" style="margin-top:8px;padding-top:8px;border-top:1px solid var(--border)">
                            <div class="ext-section-label"><?= t('dummy_assignees') ?></div>
                            <?php if (!empty($_projDummies)): ?>
                            <div class="assignee-member-list" style="margin-bottom:6px">
                                <?php foreach ($_projDummies as $pd): ?>
                                <label class="assignee-member-check">
                                    <input type="checkbox" name="assignee_external_ids[]" value="<?= (int)$pd['id'] ?>"
                                           <?= in_array((int)$pd['id'], $_assignedExternalIds) ? 'checked' : '' ?>>
                                    <span class="avatar-initials avatar-ext" style="width:22px;height:22px;font-size:9px"><?= Helper::e(mb_strtoupper(mb_substr($pd['name'],0,1))) ?></span>
                                    <span><?= Helper::e($pd['name']) ?></span>
                                </label>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>
                            <div id="extAssigneeList">
                                <?php foreach ($assignedExternals ?? [] as $ext): ?>
                                <div class="ext-assignee-tag">
                                    <input type="hidden" name="assignee_external_names[]" value="<?= Helper::e($ext) ?>">
                                    <span class="avatar-initials avatar-ext" style="width:20px;height:20px;font-size:8px"><?= Helper::e(mb_strtoupper(mb_substr($ext,0,1))) ?></span>
                                    <span><?= Helper::e($ext) ?></span>
                                    <button type="button" data-remove-parent class="ext-tag-remove" title="<?= t('remove') ?>">×</button>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <div class="ext-add-row">
                                <input type="text" id="extNameInput" class="form-input form-input-sm"
                                       placeholder="<?= t('external_name_placeholder') ?>"
                                       data-keydown="extAssigneeKeydown">
                                <button type="button" class="btn btn-ghost btn-sm" data-click="addExtAssignee">+ <?= t('add') ?></button>
                            </div>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">
                                <?= t('start_date') ?>
                                <?php if (in_array('start_date', $requiredFields)): ?><span class="required-star">*</span><?php endif; ?>
                            </label>
                            <input type="date" name="start_date" class="form-input"
                                   value="<?= Helper::e($isEdit ? $task['start_date'] : Helper::post('start_date')) ?>"
                                   <?= in_array('start_date', $requiredFields) ? 'required' : '' ?>>
                        </div>
                        <div class="form-group">
                            <label class="form-label">
                                <?= t('due_date') ?>
                                <?php if (in_array('due_date', $requiredFields)): ?><span class="required-star">*</span><?php endif; ?>
                            </label>
                            <input type="date" name="due_date" class="form-input"
                                   value="<?= Helper::e($isEdit ? $task['due_date'] : Helper::post('due_date')) ?>"
                                   <?= in_array('due_date', $requiredFields) ? 'required' : '' ?>>
                        </div>
                    </div>

                    <?php if (!empty($labels)): ?>
                    <div class="form-group">
                        <label class="form-label"><?= t('labels') ?></label>
                        <div class="label-checkboxes">
                            <?php foreach ($labels as $label): ?>
                            <label class="label-check">
                                <input type="checkbox" name="labels[]" value="<?= $label['id'] ?>"
                                       <?= in_array($label['id'], $currentLabels) ? 'checked' : '' ?>>
                                <span class="label-badge-check" style="background:<?= Helper::e($label['color']) ?>20;color:<?= Helper::e($label['color']) ?>;border:1px solid <?= Helper::e($label['color']) ?>40">
                                    <?= Helper::e($label['name']) ?>
                                </span>
                            </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>

                    <?php if (!empty($allProjectTasks)): ?>
                    <?php
                    $selPredIds  = array_map('intval', $predecessorIds ?? []);
                    $selSuccIds  = array_map('intval', $successorIds  ?? []);
                    $selSize     = min(count($allProjectTasks) + 1, 6);
                    ?>
                    <div class="form-group">
                        <label class="form-label"><?= t('predecessors') ?></label>
                        <select name="predecessors[]" id="formPredSelect"
                                class="form-select dep-select" multiple size="<?= $selSize ?>">
                            <option value="0" class="dep-none-opt"
                                    <?= empty($selPredIds) ? 'selected' : '' ?>>
                                — <?= t('no_predecessors') ?> —
                            </option>
                            <?php foreach ($allProjectTasks as $pt): ?>
                            <option value="<?= $pt['id'] ?>"
                                    <?= in_array((int)$pt['id'], $selPredIds) ? 'selected' : '' ?>>
                                <?= Helper::e($pt['title']) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label"><?= t('successors') ?></label>
                        <select name="successors[]" id="formSuccSelect"
                                class="form-select dep-select" multiple size="<?= $selSize ?>">
                            <option value="0" class="dep-none-opt"
                                    <?= empty($selSuccIds) ? 'selected' : '' ?>>
                                — <?= t('no_successors') ?> —
                            </option>
                            <?php foreach ($allProjectTasks as $pt): ?>
                            <option value="<?= $pt['id'] ?>"
                                    <?= in_array((int)$pt['id'], $selSuccIds) ? 'selected' : '' ?>>
                                <?= Helper::e($pt['title']) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <small class="form-hint"><?= t('predecessors_hint') ?></small>
                    </div>
                    <?php endif; ?>

                    <div class="form-group">
                        <label class="form-label"><?= t('upload_file') ?></label>
                        <input type="file" name="attachment" class="form-file">
                    </div>
                </div>
            </div>
        </div>

        <div class="form-actions" style="margin-top:16px">
            <?php if ($isEdit): ?>
            <button type="submit" class="btn btn-primary"><?= t('save') ?></button>
            <a href="/task/<?= $task['id'] ?>" class="btn btn-ghost"><?= t('cancel') ?></a>
            <button type="button" class="btn btn-danger" style="margin-left:auto"
                    data-click="confirmDeleteTask"
                    data-confirm-msg="<?= Helper::e(t('confirm_delete')) ?>">
                <?= t('delete') ?>
            </button>
            <?php else: ?>
            <button type="submit" class="btn btn-primary"><?= t('create') ?></button>
            <a href="/project/<?= $project['id'] ?>" class="btn btn-ghost"><?= t('cancel') ?></a>
            <?php endif; ?>
        </div>
    </form>
</div>

<?php if ($isEdit): ?>
<form id="deleteTaskForm" method="POST" action="/task/<?= $task['id'] ?>/edit">
    <?= Helper::csrf() ?>
    <input type="hidden" name="action" value="delete">
</form>
<?php endif; ?>

<script nonce="<?= csp_nonce() ?>">
function extAssigneeKeydown(el, e) {
    if (e.key === 'Enter') { e.preventDefault(); addExtAssignee(); }
}
function confirmDeleteTask(btn) {
    if (confirm(btn.dataset.confirmMsg)) {
        document.getElementById('deleteTaskForm').submit();
    }
}
function addExtAssignee() {
    var input = document.getElementById('extNameInput');
    var name  = input.value.trim();
    if (!name) return;
    var list = document.getElementById('extAssigneeList');
    var div  = document.createElement('div');
    div.className = 'ext-assignee-tag';
    var safeVal = name.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    var initial = name.charAt(0).toUpperCase();
    div.innerHTML =
        '<input type="hidden" name="assignee_external_names[]" value="' + safeVal + '">' +
        '<span class="avatar-initials avatar-ext" style="width:20px;height:20px;font-size:8px">' + initial + '</span>' +
        '<span>' + safeVal + '</span>' +
        '<button type="button" data-remove-parent class="ext-tag-remove" title="Entfernen">×</button>';
    list.appendChild(div);
    input.value = '';
    input.focus();
}
</script>
<script nonce="<?= csp_nonce() ?>">
(function () {
    function initDepSelect(id) {
        const sel = document.getElementById(id);
        if (!sel) return;
        sel.addEventListener('mousedown', (e) => {
            if (!(e.target instanceof HTMLOptionElement)) return;
            const isNone = e.target.value === '0';
            setTimeout(() => {
                if (isNone) {
                    [...sel.options].forEach(o => { if (o.value !== '0') o.selected = false; });
                } else {
                    const noneOpt = [...sel.options].find(o => o.value === '0');
                    if (noneOpt) noneOpt.selected = false;
                }
            }, 0);
        });
    }
    initDepSelect('formPredSelect');
    initDepSelect('formSuccSelect');
})();
</script>
<script nonce="<?= csp_nonce() ?>" src="/assets/js/richeditor.js"></script>
<style>
.re-toolbar{display:flex;align-items:center;gap:2px;padding:4px 6px;background:var(--bg-base);border:1px solid var(--border-color);border-bottom:none;border-radius:var(--border-radius-sm) var(--border-radius-sm) 0 0;flex-wrap:wrap}
.re-btn{background:none;border:1px solid transparent;border-radius:3px;cursor:pointer;padding:3px 6px;font-size:.8rem;color:var(--text-primary);line-height:1;display:inline-flex;align-items:center;justify-content:center}
.re-btn:hover{background:var(--bg-hover);border-color:var(--border-color)}
.re-sep{width:1px;height:16px;background:var(--border-color);margin:0 3px}
.re-editor{border:1px solid var(--border-color);border-radius:0 0 var(--border-radius-sm) var(--border-radius-sm);padding:8px 10px;font-size:.9rem;outline:none;overflow-y:auto;line-height:1.5;color:var(--text-primary);background:var(--bg-card)}
.re-editor:empty::before{content:attr(data-placeholder);color:var(--text-muted);pointer-events:none}
.re-editor:focus{border-color:var(--primary)}
.re-editor table{border-collapse:collapse;width:100%;margin:8px 0}
.re-editor td,.re-editor th{border:1px solid var(--border-color);padding:6px 10px;min-width:60px}
.re-editor img{max-width:100%;height:auto;border-radius:4px;margin:4px 0}
.re-editor p{margin:.4em 0}
</style>
<script nonce="<?= csp_nonce() ?>">
window.addEventListener('DOMContentLoaded', () => {
    const initialDesc = <?= json_encode($isEdit ? ($task['description'] ?? '') : Helper::post('description')) ?>;
    initRichEditor('desc-editor', 'desc-hidden', {
        initialContent: initialDesc,
        minHeight: 120
    });
});
</script>
