<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/layout.php';
require_once __DIR__ . '/../includes/employee_management.php';

require_permission($conn, 'employees');

$positionEditId = filter_input(INPUT_GET, 'position_id', FILTER_VALIDATE_INT);
$oldInput = pull_old_input();
$showPositionFormFlag = filter_input(INPUT_GET, 'show_form', FILTER_VALIDATE_INT);

$editingPosition = null;
if ($positionEditId) {
    $stmt = db_prepare($conn, "
        SELECT position_id, position_name, role_key, branch_scope, permissions, is_active
        FROM positions
        WHERE position_id = ?
        LIMIT 1
    ");
    $stmt->bind_param('i', $positionEditId);
    $stmt->execute();
    $editingPosition = $stmt->get_result()->fetch_assoc();
    $stmt->close();
}

$positions = array();
$positionsResult = $conn->query("
    SELECT
        p.position_id,
        p.position_name,
        p.role_key,
        p.branch_scope,
        p.permissions,
        p.is_active,
        COUNT(e.employee_id) AS employee_count
    FROM positions p
    LEFT JOIN employees e ON e.position_id = p.position_id
    GROUP BY
        p.position_id,
        p.position_name,
        p.role_key,
        p.branch_scope,
        p.permissions,
        p.is_active
    ORDER BY p.is_active DESC, p.position_name ASC
");

if ($positionsResult instanceof mysqli_result) {
    while ($row = $positionsResult->fetch_assoc()) {
        $positions[] = $row;
    }
}

$permissionLabels = auth_permission_labels();
$permissionGroupLabel = static function (string $permissionKey): string {
    return employee_permission_group_label($permissionKey);
};
$activeMatrixPositions = array_values(array_filter($positions, static function (array $position): bool {
    return (int) ($position['is_active'] ?? 0) === 1;
}));
$positionPermissionMap = array();
foreach ($positions as $positionRow) {
    $decodedPermissions = json_decode((string) ($positionRow['permissions'] ?? '[]'), true);
    $positionPermissionMap[(int) ($positionRow['position_id'] ?? 0)] = is_array($decodedPermissions)
        ? array_values(array_unique(array_map('strval', $decodedPermissions)))
        : array();
}
$multiRolePermissionGroups = array();
foreach ($permissionLabels as $permissionKey => $permissionLabel) {
    $groupLabel = $permissionGroupLabel((string) $permissionKey);
    if (!isset($multiRolePermissionGroups[$groupLabel])) {
        $multiRolePermissionGroups[$groupLabel] = array();
    }

    $multiRolePermissionGroups[$groupLabel][] = array(
        'key' => (string) $permissionKey,
        'label' => (string) $permissionLabel,
    );
}
$positionName = old_value($oldInput, 'position_name', (string) ($editingPosition['position_name'] ?? ''));
$roleKey = old_value($oldInput, 'role_key', (string) ($editingPosition['role_key'] ?? ''));
$positionScope = old_value($oldInput, 'branch_scope', old_value($oldInput, 'position_branch_scope', (string) ($editingPosition['branch_scope'] ?? 'assigned')));
$positionActive = old_value($oldInput, 'is_active', old_value($oldInput, 'position_is_active', (string) ($editingPosition['is_active'] ?? '1'))) !== '0';
$selectedPermissions = old_array($oldInput, 'permissions');
if (empty($selectedPermissions) && $editingPosition) {
    $decodedPermissions = json_decode((string) ($editingPosition['permissions'] ?? '[]'), true);
    $selectedPermissions = is_array($decodedPermissions) ? $decodedPermissions : array();
}
$showPositionForm = $editingPosition !== null || !empty($oldInput) || (int) $showPositionFormFlag === 1;
$pageTitle = ui_text('ตำแหน่งงาน', 'Positions');
$pageDescription = ui_text(
    'จัดการตำแหน่งงาน สิทธิ์การใช้งาน และขอบเขตสาขาเริ่มต้น แยกจากบัญชีพนักงาน',
    'Manage job positions, function permissions and default branch scope separately from employee accounts.'
);
$manageSystemLabel = ui_text('จัดการระบบ', 'Manage System');
$manageEmployeesLabel = ui_text('จัดการพนักงาน', 'Manage employees');
$positionToolsLabel = ui_text('เครื่องมือตำแหน่ง', 'Position tools');
$positionToolsHelperLabel = ui_text('เปิดฟอร์มตำแหน่งเมื่อคุณต้องการเพิ่มหรือแก้ไขบทบาทเท่านั้น', 'Open the position form only when you want to add or edit a role.');
$hideFormLabel = ui_text('ซ่อนฟอร์ม', 'Hide form');
$addPositionLabel = ui_text('เพิ่มตำแหน่ง', 'Add position');
$formToggleLabel = $showPositionForm ? $hideFormLabel : $addPositionLabel;
$editPositionLabel = ui_text('แก้ไขตำแหน่ง', 'Edit position');
$formTitle = $editingPosition ? $editPositionLabel : $addPositionLabel;
$positionFormHelperLabel = ui_text('สิทธิ์ในส่วนนี้จะกำหนดว่าฟังก์ชันใดบ้างที่มองเห็นและเข้าใช้งานได้', 'Permissions here control which functions appear and can be opened.');
$newPositionLabel = ui_text('เพิ่มตำแหน่งใหม่', 'New position');
$positionNameLabel = ui_text('ชื่อตำแหน่ง', 'Position name');
$roleKeyLabel = ui_text('คีย์ตำแหน่ง', 'Role key');
$defaultBranchScopeLabel = ui_text('ขอบเขตสาขาเริ่มต้น', 'Default branch scope');
$functionPermissionsLabel = ui_text('สิทธิ์การใช้งาน', 'Function permissions');
$activePositionLabel = ui_text('ตำแหน่งงานที่เปิดใช้งาน', 'Active position');
$savePositionLabel = $editingPosition ? ui_text('บันทึกตำแหน่ง', 'Save position') : $addPositionLabel;
$setPermissionsForMultipleRolesLabel = ui_text('กำหนดสิทธิ์หลายตำแหน่งพร้อมกัน', 'Set Permissions for Multiple Roles');
$multiRoleHelperLabel = ui_text('แสดงหรือซ่อนคอลัมน์ของตำแหน่งที่ใช้งานอยู่ แล้วอัปเดตสิทธิ์หลายตำแหน่งพร้อมกันในการบันทึกครั้งเดียว', 'Show or hide active role columns, then update permissions across multiple positions in one save.');
$selectAllLabel = ui_text('เลือกทั้งหมด', 'Select All');
$positionFallbackLabel = ui_text('ตำแหน่ง', 'Position');
$permissionMatrixLabel = ui_text('ตารางสิทธิ์', 'Permission matrix');
$activeRolesLabel = ui_text('ตำแหน่งที่เปิดใช้งาน', 'active role(s)');
$permissionsCountLabel = ui_text('สิทธิ์', 'permission(s)');
$groupLabel = ui_text('กลุ่ม', 'Group');
$permissionLabel = ui_text('สิทธิ์', 'Permission');
$saveMultiRolePermissionsLabel = ui_text('บันทึกสิทธิ์หลายตำแหน่ง', 'Save multi-role permissions');
$positionsTitleLabel = ui_text('ตำแหน่งงาน', 'Positions');
$positionRecordsLabel = ui_text('รายการตำแหน่ง', 'position record(s)');
$scopeLabel = ui_text('ขอบเขต', 'Scope');
$employeesLabel = ui_text('พนักงาน', 'Employees');
$statusLabel = ui_text('สถานะ', 'Status');
$actionLabel = ui_text('การทำรายการ', 'Action');
$editLabel = ui_text('แก้ไข', 'Edit');

render_page_start($pageTitle, 'positions', array('translation_buffer' => false));
?>

<section class="page-hero">
    <div>
        <h1><?= e($pageTitle) ?></h1>
        <p><?= e($pageDescription) ?></p>
    </div>
    <div class="hero-actions">
        <a class="button button-secondary" href="manage_system.php"><?= e($manageSystemLabel) ?></a>
        <a class="button button-secondary" href="employees.php"><?= e($manageEmployeesLabel) ?></a>
    </div>
</section>

<?= render_employee_management_tabs('positions') ?>

<section class="form-card">
    <div class="section-head">
        <div>
            <h2 class="section-title"><?= e($positionToolsLabel) ?></h2>
            <p class="helper"><?= e($positionToolsHelperLabel) ?></p>
        </div>
        <button
            class="button button-accent"
            type="button"
            data-edit-toggle
            aria-expanded="<?= $showPositionForm ? 'true' : 'false' ?>"
            aria-controls="position-form-panel"
            data-closed-label="<?= e($addPositionLabel) ?>"
            data-open-label="<?= e($hideFormLabel) ?>"
        ><?= e($formToggleLabel) ?></button>
    </div>
</section>

<div class="grid">
    <section class="form-card" id="position-form-panel" <?= $showPositionForm ? '' : 'hidden' ?>>
        <div class="section-head">
            <div>
                <h2 class="section-title"><?= e($formTitle) ?></h2>
                <p class="helper"><?= e($positionFormHelperLabel) ?></p>
            </div>
            <?php if ($editingPosition): ?>
                <a class="button button-ghost" href="positions.php?show_form=1"><?= e($newPositionLabel) ?></a>
            <?php endif; ?>
        </div>

        <form method="POST" action="../process/save_position.php">
            <?php if ($editingPosition): ?>
                <input type="hidden" name="position_id" value="<?= (int) $editingPosition['position_id'] ?>">
            <?php endif; ?>

            <div class="form-grid">
                <div class="field">
                    <label for="position_name"><?= e($positionNameLabel) ?></label>
                    <input id="position_name" name="position_name" type="text" value="<?= e($positionName) ?>" required>
                </div>

                <div class="field">
                    <label for="role_key"><?= e($roleKeyLabel) ?></label>
                    <input id="role_key" name="role_key" type="text" value="<?= e($roleKey) ?>" placeholder="manager">
                </div>

                <div class="field">
                    <label for="position_branch_scope"><?= e($defaultBranchScopeLabel) ?></label>
                    <select id="position_branch_scope" name="branch_scope">
                        <?php foreach (employee_branch_scope_options() as $scopeValue => $scopeOptionLabel): ?>
                            <option value="<?= e($scopeValue) ?>" <?= $positionScope === $scopeValue ? 'selected' : '' ?>><?= e($scopeOptionLabel) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="field">
                <label><?= e($functionPermissionsLabel) ?></label>
                <div class="checkbox-grid">
                    <?php foreach ($permissionLabels as $permissionKey => $permissionLabel): ?>
                        <label class="service-option compact-option">
                            <input type="checkbox" name="permissions[]" value="<?= e($permissionKey) ?>" <?= in_array($permissionKey, $selectedPermissions, true) ? 'checked' : '' ?>>
                            <span><?= e(translate_text($permissionLabel)) ?></span>
                        </label>
                    <?php endforeach; ?>
                </div>
            </div>

            <label class="service-option compact-option">
                <input type="checkbox" name="is_active" value="1" <?= $positionActive ? 'checked' : '' ?>>
                <span><?= e($activePositionLabel) ?></span>
            </label>

            <button class="button button-accent" type="submit"><?= e($savePositionLabel) ?></button>
        </form>
    </section>
</div>

<?php if (!empty($activeMatrixPositions)): ?>
    <form method="POST" action="../process/save_multi_role_permissions.php" data-multi-role-permissions>
        <section class="card multi-role-filter-panel" style="margin-top: 18px;">
            <div class="section-head">
                <div>
                    <h2 class="section-title"><?= e($setPermissionsForMultipleRolesLabel) ?></h2>
                    <p class="helper"><?= e($multiRoleHelperLabel) ?></p>
                </div>
            </div>

            <label class="service-option compact-option multi-role-select-all">
                <input type="checkbox" checked data-multi-role-toggle-all>
                <span><?= e($selectAllLabel) ?></span>
            </label>

            <div class="multi-role-role-toggles">
                <?php foreach ($activeMatrixPositions as $matrixPosition): ?>
                    <?php $matrixPositionId = (int) ($matrixPosition['position_id'] ?? 0); ?>
                    <label class="service-option compact-option multi-role-toggle">
                        <input type="checkbox" checked data-multi-role-toggle data-column-id="<?= $matrixPositionId ?>">
                        <span><?= e((string) ($matrixPosition['position_name'] ?? $positionFallbackLabel)) ?></span>
                    </label>
                <?php endforeach; ?>
            </div>
        </section>

        <section class="table-card multi-role-table-card" style="margin-top: 18px;">
            <div class="section-head" style="padding: 18px 18px 0;">
                <div>
                    <h2 class="section-title"><?= e($permissionMatrixLabel) ?></h2>
                    <p class="helper"><?= count($activeMatrixPositions) ?> <?= e($activeRolesLabel) ?> / <?= count($permissionLabels) ?> <?= e($permissionsCountLabel) ?></p>
                </div>
            </div>

            <?php foreach ($activeMatrixPositions as $matrixPosition): ?>
                <input type="hidden" name="position_ids[]" value="<?= (int) ($matrixPosition['position_id'] ?? 0) ?>">
            <?php endforeach; ?>

            <table class="multi-role-permission-table" style="min-width: 980px;">
                <thead>
                <tr>
                    <th><?= e($groupLabel) ?></th>
                    <th><?= e($permissionLabel) ?></th>
                    <?php foreach ($activeMatrixPositions as $matrixPosition): ?>
                        <?php $matrixPositionId = (int) ($matrixPosition['position_id'] ?? 0); ?>
                        <th class="multi-role-role-head" data-multi-role-column-head="<?= $matrixPositionId ?>">
                            <?= e((string) ($matrixPosition['position_name'] ?? $positionFallbackLabel)) ?>
                        </th>
                    <?php endforeach; ?>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($multiRolePermissionGroups as $groupLabel => $permissionRows): ?>
                    <?php $groupRowCount = count($permissionRows); ?>
                    <?php foreach ($permissionRows as $rowIndex => $permissionRow): ?>
                        <?php $permissionKey = (string) ($permissionRow['key'] ?? ''); ?>
                        <tr>
                            <?php if ($rowIndex === 0): ?>
                                <td rowspan="<?= $groupRowCount ?>" class="multi-role-group-cell">
                                    <strong><?= e($groupLabel) ?></strong>
                                </td>
                            <?php endif; ?>
                            <td class="multi-role-permission-cell"><?= e(translate_text((string) ($permissionRow['label'] ?? $permissionKey))) ?></td>
                            <?php foreach ($activeMatrixPositions as $matrixPosition): ?>
                                <?php
                                $matrixPositionId = (int) ($matrixPosition['position_id'] ?? 0);
                                $matrixPermissions = $positionPermissionMap[$matrixPositionId] ?? array();
                                ?>
                                <td class="multi-role-checkbox-cell" data-multi-role-column="<?= $matrixPositionId ?>">
                                    <input
                                        type="checkbox"
                                        name="multi_permissions[<?= $matrixPositionId ?>][]"
                                        value="<?= e($permissionKey) ?>"
                                        <?= in_array($permissionKey, $matrixPermissions, true) ? 'checked' : '' ?>
                                    >
                                </td>
                            <?php endforeach; ?>
                        </tr>
                    <?php endforeach; ?>
                <?php endforeach; ?>
                </tbody>
            </table>

            <div class="actions" style="padding: 18px;">
                <button class="button button-accent" type="submit"><?= e($saveMultiRolePermissionsLabel) ?></button>
            </div>
        </section>
    </form>
<?php endif; ?>

<section class="table-card" style="margin-top: 18px;">
    <div class="section-head" style="padding: 18px 18px 0;">
        <div>
            <h2 class="section-title"><?= e($positionsTitleLabel) ?></h2>
            <p class="helper"><?= count($positions) ?> <?= e($positionRecordsLabel) ?></p>
        </div>
    </div>

    <table style="min-width: 680px;">
        <thead>
        <tr>
            <th><?= e($positionNameLabel) ?></th>
            <th><?= e($scopeLabel) ?></th>
            <th><?= e($employeesLabel) ?></th>
            <th><?= e($statusLabel) ?></th>
            <th><?= e($actionLabel) ?></th>
        </tr>
        </thead>
        <tbody>
        <?php foreach ($positions as $position): ?>
            <tr>
                <td>
                    <div class="stack">
                        <strong><?= e((string) $position['position_name']) ?></strong>
                        <span class="muted"><?= e((string) $position['role_key']) ?></span>
                    </div>
                </td>
                <td><?= e(employee_branch_scope_label((string) $position['branch_scope'])) ?></td>
                <td><?= (int) ($position['employee_count'] ?? 0) ?></td>
                <td><span class="<?= (int) $position['is_active'] === 1 ? 'badge badge-paid' : 'badge badge-unpaid' ?>"><?= e(employee_status_label((int) $position['is_active'] === 1)) ?></span></td>
                <td><a class="button button-secondary" href="positions.php?position_id=<?= (int) $position['position_id'] ?>"><?= e($editLabel) ?></a></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</section>

<?php render_page_end(); ?>
