<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/bootstrap.php';

require_permission($conn, 'employees');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect('../pages/positions.php');
}

$positionIds = array_values(array_unique(array_filter(array_map('intval', (array) ($_POST['position_ids'] ?? array())))));
$permissionLabels = auth_permission_labels();
$allowedPermissionKeys = array_keys($permissionLabels);
$submittedPermissions = (array) ($_POST['multi_permissions'] ?? array());

if (empty($positionIds)) {
    redirect_with_flash('../pages/positions.php', 'error', localized_flash_message('ยังไม่ได้เลือกตำแหน่งสำหรับอัปเดตสิทธิ์หลายบทบาท', 'No position was selected for multi role permission update.'));
}

$positionIdSql = implode(',', array_map('intval', $positionIds));
$positions = array();
$positionSnapshots = array();
$positionResult = $conn->query("
    SELECT position_id, position_name, permissions
    FROM positions
    WHERE position_id IN ({$positionIdSql})
");

if ($positionResult instanceof mysqli_result) {
    while ($row = $positionResult->fetch_assoc()) {
        $positions[] = (int) ($row['position_id'] ?? 0);
        $positionSnapshots[(int) ($row['position_id'] ?? 0)] = array(
            'position_name' => (string) ($row['position_name'] ?? ''),
            'permissions' => is_array(json_decode((string) ($row['permissions'] ?? '[]'), true))
                ? array_values(array_map('strval', json_decode((string) ($row['permissions'] ?? '[]'), true)))
                : array(),
        );
    }
}

if (count($positions) !== count($positionIds)) {
    redirect_with_flash('../pages/positions.php', 'error', localized_flash_message('มีตำแหน่งที่เลือกอย่างน้อย 1 รายการไม่พร้อมใช้งานแล้ว', 'One or more selected positions are no longer available.'));
}

$conn->begin_transaction();

try {
    $updateStmt = db_prepare($conn, "
        UPDATE positions
        SET permissions = ?
        WHERE position_id = ?
    ");

    foreach ($positionIds as $positionId) {
        $permissions = array_values(array_intersect(
            array_map('strval', (array) ($submittedPermissions[$positionId] ?? array())),
            $allowedPermissionKeys
        ));
        $permissions = array_values(array_unique($permissions));
        $permissionsJson = json_encode($permissions, JSON_UNESCAPED_UNICODE);

        $updateStmt->bind_param('si', $permissionsJson, $positionId);
        $updateStmt->execute();

        $beforePermissions = $positionSnapshots[$positionId]['permissions'] ?? array();
        $permissionDiff = audit_membership_diff($beforePermissions, $permissions);
        if (!empty($permissionDiff['added']) || !empty($permissionDiff['removed'])) {
            audit_log($conn, array(
                'module_key' => 'permission',
                'action_key' => 'update',
                'entity_type' => 'position_permissions',
                'entity_id' => $positionId,
                'message' => 'Position permissions updated from multi-role screen.',
                'meta' => array(
                    'position_name' => (string) ($positionSnapshots[$positionId]['position_name'] ?? ''),
                    'permissions_added' => $permissionDiff['added'],
                    'permissions_removed' => $permissionDiff['removed'],
                ),
            ));
        }
    }

    $updateStmt->close();
    $conn->commit();

    redirect_with_flash('../pages/positions.php', 'success', localized_flash_message('อัปเดตสิทธิ์หลายบทบาทเรียบร้อยแล้ว', 'Multi role permissions updated.'));
} catch (Throwable $exception) {
    $conn->rollback();
    redirect_with_flash('../pages/positions.php', 'error', localized_flash_message('บันทึกสิทธิ์หลายบทบาทไม่สำเร็จ', 'Multi role permissions were not saved.'));
}
