<?php
declare(strict_types=1);

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

require_permission($conn, 'employees');

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

$positionId = filter_input(INPUT_POST, 'position_id', FILTER_VALIDATE_INT);
$positionName = trim((string) ($_POST['position_name'] ?? ''));
$roleKey = strtolower(trim((string) ($_POST['role_key'] ?? '')));
$branchScope = (string) ($_POST['branch_scope'] ?? 'assigned');
$permissions = array_values(array_intersect((array) ($_POST['permissions'] ?? array()), array_keys(auth_permission_labels())));
$isActive = isset($_POST['is_active']) ? 1 : 0;
$editQuery = array('show_form' => 1);
if ($positionId) {
    $editQuery['position_id'] = $positionId;
}
$editPath = '../pages/positions.php?' . http_build_query($editQuery);

if ($positionName === '') {
    redirect_with_flash($editPath, 'error', localized_flash_message('กรุณาระบุชื่อตำแหน่ง', 'Position name is required.'), $_POST);
}

if ($roleKey === '') {
    $roleKey = strtolower((string) preg_replace('/[^a-zA-Z0-9]+/', '_', $positionName));
}

$roleKey = trim((string) preg_replace('/[^a-z0-9_]+/', '_', $roleKey), '_');
if ($roleKey === '') {
    $roleKey = 'position_' . time();
}

if (!in_array($branchScope, array('all', 'assigned'), true)) {
    $branchScope = 'assigned';
}

$permissionsJson = json_encode($permissions, JSON_UNESCAPED_UNICODE);
$beforePosition = array();
$beforePermissions = array();
if ($positionId) {
    $positionSnapshotStmt = db_prepare($conn, "
        SELECT position_id, position_name, role_key, branch_scope, permissions, is_active
        FROM positions
        WHERE position_id = ?
        LIMIT 1
    ");
    $positionSnapshotStmt->bind_param('i', $positionId);
    $positionSnapshotStmt->execute();
    $positionSnapshot = $positionSnapshotStmt->get_result()->fetch_assoc();
    $positionSnapshotStmt->close();

    if (!$positionSnapshot) {
        redirect_with_flash('../pages/positions.php', 'error', localized_flash_message('ไม่พบตำแหน่ง', 'Position was not found.'));
    }

    $beforePermissions = json_decode((string) ($positionSnapshot['permissions'] ?? '[]'), true);
    $beforePermissions = is_array($beforePermissions) ? array_values(array_map('strval', $beforePermissions)) : array();
    $beforePosition = array(
        'position_name' => (string) ($positionSnapshot['position_name'] ?? ''),
        'role_key' => (string) ($positionSnapshot['role_key'] ?? ''),
        'branch_scope' => (string) ($positionSnapshot['branch_scope'] ?? ''),
        'is_active' => (int) ($positionSnapshot['is_active'] ?? 0),
    );
}

try {
    if ($positionId) {
        $stmt = db_prepare($conn, "
            UPDATE positions
            SET position_name = ?, role_key = ?, branch_scope = ?, permissions = ?, is_active = ?
            WHERE position_id = ?
        ");
        $stmt->bind_param('ssssii', $positionName, $roleKey, $branchScope, $permissionsJson, $isActive, $positionId);
        $stmt->execute();
        $stmt->close();

        $afterPosition = array(
            'position_name' => $positionName,
            'role_key' => $roleKey,
            'branch_scope' => $branchScope,
            'is_active' => $isActive,
        );
        $positionDiff = audit_diff_assoc($beforePosition, $afterPosition);
        $permissionDiff = audit_membership_diff($beforePermissions, $permissions);

        if (!empty($positionDiff['after']) || !empty($permissionDiff['added']) || !empty($permissionDiff['removed'])) {
            audit_log($conn, array(
                'module_key' => 'position',
                'action_key' => 'update',
                'entity_type' => 'position',
                'entity_id' => $positionId,
                'message' => localized_flash_message('อัปเดตตำแหน่งเรียบร้อยแล้ว', 'Position updated.'),
                'before' => $positionDiff['before'],
                'after' => $positionDiff['after'],
                'meta' => array(
                    'permissions_added' => $permissionDiff['added'],
                    'permissions_removed' => $permissionDiff['removed'],
                ),
            ));
        }

        redirect_with_flash('../pages/positions.php', 'success', localized_flash_message('อัปเดตตำแหน่งเรียบร้อยแล้ว', 'Position updated.'));
    }

    $stmt = db_prepare($conn, "
        INSERT INTO positions (position_name, role_key, branch_scope, permissions, is_active)
        VALUES (?, ?, ?, ?, ?)
    ");
    $stmt->bind_param('ssssi', $positionName, $roleKey, $branchScope, $permissionsJson, $isActive);
    $stmt->execute();
    $positionId = (int) $conn->insert_id;
    $stmt->close();

    audit_log($conn, array(
        'module_key' => 'position',
        'action_key' => 'create',
        'entity_type' => 'position',
        'entity_id' => $positionId,
        'message' => 'Position created.',
        'after' => array(
            'position_name' => $positionName,
            'role_key' => $roleKey,
            'branch_scope' => $branchScope,
            'is_active' => $isActive,
        ),
        'meta' => array(
            'permissions_added' => array_values($permissions),
            'permissions_removed' => array(),
        ),
    ));

    redirect_with_flash('../pages/positions.php', 'success', localized_flash_message('เพิ่มตำแหน่งเรียบร้อยแล้ว', 'Position added.'));
} catch (Throwable $exception) {
    redirect_with_flash($editPath, 'error', localized_flash_message('บันทึกตำแหน่งไม่สำเร็จ', 'Position was not saved.'), $_POST);
}
