from pathlib import Path


path = Path(r"a:\risk_server\project\safety_gear\receipt_batch_print.php")
lines = path.read_text(encoding="utf-8").splitlines()


def replace_range(src, start, end, block):
    return src[: start - 1] + block + src[end:]


lines = replace_range(
    lines,
    7,
    12,
    [
        "const RECEIPT_COMPANY_NAME = '(주)현대기전';",
        "const RECEIPT_SITE_NAME = '옥계면 한라시멘트';",
        "const RECEIPT_PLEDGE_TEXT = '지급받은 보호구를 작업 중 항상 착용하겠으며, 미착용으로 인한 불이익은 본인에게 있음을 확인합니다.';",
        "const RECEIPT_PLEDGE_TEXT_RU = 'Ya podtverzhdayu, chto poluchil(a) dannye sredstva individualnoy zashchity, obyazuyus postoyanno ispolzovat ikh vo vremya raboty i ponimayu, chto otvetstvennost za posledstviya neispolzovaniya vozlagaetsya na menya.';",
        "const RECEIPT_PLEDGE_TEXT_UZ = 'Men korsatilgan shaxsiy himoya vositalarini olganimni tasdiqlayman, ish vaqtida ularni doimo taqib yurishga majbur ekanligimni va taqmaslik oqibatlari uchun javobgarlik ozimda bolishini tushunaman.';",
        "const RECEIPT_PLEDGE_TEXT_KY = 'Men korsetulgon zheke korgonuu karazhattaryn alganymdy yrastaym, ish uchurunda alardy dayyma tagynuuga mildettuu ekenimdi jana tagynbagandyk uchun joopkerchilik ozumdo bolorun tushunom.';",
    ],
)

lines = replace_range(
    lines,
    127,
    139,
    [
        "function receipt_locale_note(string $locale): string",
        "{",
        "    if ($locale === 'ru') {",
        "        return '러시아어 병기 출력입니다. 자필서명은 근로자가 직접 하고, 안전관리자가 원본 대조 후 확인 처리해 주세요.';",
        "    }",
        "    if ($locale === 'uz') {",
        "        return '우즈베크어 병기 출력입니다. 자필서명은 근로자가 직접 하고, 안전관리자가 원본 대조 후 확인 처리해 주세요.';",
        "    }",
        "    if ($locale === 'ky') {",
        "        return '키르기스어 병기 출력입니다. 자필서명은 근로자가 직접 하고, 안전관리자가 원본 대조 후 확인 처리해 주세요.';",
        "    }",
        "    return '';",
        "}",
    ],
)

lines = replace_range(
    lines,
    260,
    293,
    [
        "function receipt_gear_translation_map(string $locale): array",
        "{",
        "    $maps = [",
        "        'ru' => [",
        "            sg_normalize_text('안전모') => 'Zashchitnaya kaska',",
        "            sg_normalize_text('안전화') => 'Zashchitnaya obuv',",
        "            sg_normalize_text('안전대') => 'Strakhovochnaya privyaz',",
        "            sg_normalize_text('안전조끼') => 'Signalny zhilet',",
        "            sg_normalize_text('신호수조끼') => 'Zhilet signalshchika',",
        "            sg_normalize_text('경광봉') => 'Signalnyy zhezl',",
        "            sg_normalize_text('방진마스크') => 'Protivopylevaya maska',",
        "        ],",
        "        'uz' => [",
        "            sg_normalize_text('안전모') => 'Himoya kaskasi',",
        "            sg_normalize_text('안전화') => 'Himoya oyoq kiyimi',",
        "            sg_normalize_text('안전대') => 'Himoya belbogi',",
        "            sg_normalize_text('안전조끼') => 'Signal jileti',",
        "            sg_normalize_text('신호수조끼') => 'Signalchi jileti',",
        "            sg_normalize_text('경광봉') => 'Signal tayoqchasi',",
        "            sg_normalize_text('방진마스크') => 'Changdan himoya niqobi',",
        "        ],",
        "        'ky' => [",
        "            sg_normalize_text('안전모') => 'Korgonuu kaskasy',",
        "            sg_normalize_text('안전화') => 'Korgonuu but kiyimi',",
        "            sg_normalize_text('안전대') => 'Korgonuu belboosu',",
        "            sg_normalize_text('안전조끼') => 'Signal zhileti',",
        "            sg_normalize_text('신호수조끼') => 'Signalchy zhileti',",
        "            sg_normalize_text('경광봉') => 'Signal tayakchasy',",
        "            sg_normalize_text('방진마스크') => 'Changdan korgonuu maskasy',",
        "        ],",
        "    ];",
        "",
        "    return $maps[$locale] ?? [];",
        "}",
    ],
)

lines = replace_range(
    lines,
    311,
    314,
    [
        "function receipt_status_label(string $status): string",
        "{",
        "    return $status === 'confirmed' ? '확인 완료' : '발급 완료';",
        "}",
    ],
)

tail = [
    "$user = auth_current_user();",
    "if (!is_array($user)) {",
    "    header('Location: /risk_assessment/task_select.php');",
    "    exit;",
    "}",
    "",
    "if (!auth_can_manage($user)) {",
    "    http_response_code(403);",
    "    echo '안전관리자만 이 페이지에 접근할 수 있습니다.';",
    "    exit;",
    "}",
    "",
    "$pdo = sg_get_pdo();",
    "$allGroups = sg_fetch_assigned_items_grouped_by_employee($pdo);",
    "",
    "if ($_SERVER['REQUEST_METHOD'] === 'POST') {",
    "    $postState = receipt_build_state($pdo, $_POST);",
    "    $action = sg_normalize_text($_POST['action'] ?? '');",
    "",
    "    try {",
    "        if ($action === 'save_batch') {",
    "            if (empty($postState['print_groups'])) {",
    "                throw new RuntimeException('저장할 확인서가 없습니다.');",
    "            }",
    "",
    "            $savedCount = 0;",
    "            foreach ($postState['print_groups'] as $index => $group) {",
    "                $assignedItems = (array)($group['assigned_items'] ?? []);",
    "                $documentDate = $postState['mode'] === 'daily'",
    "                    ? ($postState['manual_date'] !== '' ? $postState['manual_date'] : date('Y-m-d'))",
    "                    : receipt_signature_date($assignedItems);",
    "                $rows = $postState['mode'] === 'daily'",
    "                    ? (array)($group['manual_rows'] ?? [])",
    "                    : receipt_aggregate_items($assignedItems);",
    "",
    "                sg_create_receipt(",
    "                    $pdo,",
    "                    [",
    "                        'document_no' => receipt_document_no($group, $index + 1, $postState['mode'] === 'daily' ? 'DGR' : 'SGR'),",
    "                        'worker_type' => $postState['mode'] === 'daily' ? 'daily' : 'employee',",
    "                        'employee_id' => $group['employee_id'] ?? '',",
    "                        'worker_name' => $group['employee_name'] ?? '',",
    "                        'worker_team' => $group['employee_team'] ?? '',",
    "                        'worker_position' => $group['employee_position'] ?? '',",
    "                        'company_name' => RECEIPT_COMPANY_NAME,",
    "                        'site_name' => RECEIPT_SITE_NAME,",
    "                        'issue_date' => $documentDate,",
    "                        'pledge_text' => receipt_pledge_text_by_locale($postState['mode'] === 'daily' ? $postState['manual_locale'] : 'ko'),",
    "                    ],",
    "                    $rows,",
    "                    $user",
    "                );",
    "                $savedCount++;",
    "            }",
    "",
    "            receipt_redirect(receipt_query_from_state($postState, ['notice' => $savedCount . '건의 확인서를 DB에 저장했습니다.']));",
    "        }",
    "",
    "        if ($action === 'save_manual_preset') {",
    "            if ($postState['mode'] !== 'daily') {",
    "                throw new RuntimeException('일용근로자 직접입력 모드에서만 preset을 저장할 수 있습니다.');",
    "            }",
    "            sg_save_receipt_preset(",
    "                $pdo,",
    "                (string)($_POST['manual_preset_name'] ?? ''),",
    "                (string)($postState['manual_items_raw'] ?? ''),",
    "                (string)($postState['manual_locale'] ?? 'ko'),",
    "                $user",
    "            );",
    "            receipt_redirect(receipt_query_from_state($postState, ['notice' => '공통 지급 보호구 preset을 저장했습니다.']));",
    "        }",
    "",
    "        if ($action === 'attach_receipt' || $action === 'confirm_receipt') {",
    "            $receiptId = max(0, (int)($_POST['receipt_id'] ?? 0));",
    "            if ($receiptId <= 0) {",
    "                throw new RuntimeException('확인서 ID가 올바르지 않습니다.');",
    "            }",
    "            $hasUpload = isset($_FILES['attachment']) && (int)($_FILES['attachment']['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_OK;",
    "            if ($action === 'attach_receipt' && !$hasUpload) {",
    "                throw new RuntimeException('업로드할 서명지 파일을 선택해 주세요.');",
    "            }",
    "            if ($hasUpload) {",
    "                sg_attach_receipt_file($pdo, $receiptId, $_FILES['attachment']);",
    "            }",
    "            if ($action === 'confirm_receipt') {",
    "                $currentAttachment = $hasUpload ? 'uploaded' : receipt_fetch_attachment_path($pdo, $receiptId);",
    "                if ($currentAttachment === '') {",
    "                    throw new RuntimeException('확인 완료 처리 전 서명지 파일을 먼저 업로드해 주세요.');",
    "                }",
    "                sg_confirm_receipt($pdo, $receiptId, $user, (string)($_POST['confirm_note'] ?? ''));",
    "                receipt_redirect(['notice' => '확인서 확인 완료 처리가 끝났습니다.']);",
    "            }",
    "            receipt_redirect(['notice' => '서명지 파일을 저장했습니다.']);",
    "        }",
    "",
    "        if ($action === 'delete_receipt') {",
    "            $receiptId = max(0, (int)($_POST['receipt_id'] ?? 0));",
    "            if ($receiptId <= 0) {",
    "                throw new RuntimeException('삭제할 확인서 ID가 올바르지 않습니다.');",
    "            }",
    "            sg_delete_receipt($pdo, $receiptId);",
    "            receipt_redirect(['notice' => '확인서를 삭제했습니다.']);",
    "        }",
    "    } catch (Throwable $e) {",
    "        receipt_redirect(receipt_query_from_state($postState, ['error' => $e->getMessage()]));",
    "    }",
    "}",
    "",
    "$state = receipt_build_state($pdo, $_GET);",
    "$mode = $state['mode'];",
    "$printMode = $state['print_mode'];",
    "$selectedIds = $state['selected_ids'];",
    "$manualTeam = $state['manual_team'];",
    "$manualPosition = $state['manual_position'];",
    "$manualDate = $state['manual_date'];",
    "$manualLocale = $state['manual_locale'];",
    "$manualPresetId = $state['manual_preset_id'];",
    "$manualPresetName = $state['manual_preset_name'];",
    "$manualNamesRaw = $state['manual_names_raw'];",
    "$manualItemsRaw = $state['manual_items_raw'];",
    "$printGroups = $state['print_groups'];",
    "$savedReceipts = sg_fetch_receipts($pdo, 80);",
    "$receiptPresets = sg_fetch_receipt_presets($pdo);",
    "$noticeMessage = sg_normalize_text($_GET['notice'] ?? '');",
    "$errorMessage = sg_normalize_text($_GET['error'] ?? '');",
    "?>",
    "<!DOCTYPE html>",
    "<html lang=\"ko\">",
    "<head>",
    "    <meta charset=\"UTF-8\">",
    "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">",
    "    <title>보호구 지급확인서 출력</title>",
    "    <style>",
    "        :root { --bg:#edf4f8; --panel:#fff; --line:#d7e0ea; --text:#132238; --muted:#64748b; --accent:#0f766e; --accent-soft:#ccfbf1; --danger:#b91c1c; --danger-soft:#fee2e2; }",
    "        * { box-sizing:border-box; }",
    "        body { margin:0; font-family:\"Malgun Gothic\", sans-serif; color:var(--text); background:radial-gradient(circle at top right, rgba(20,184,166,.12), transparent 22%), linear-gradient(180deg,#f8fbfd 0%, var(--bg) 100%); }",
    "        .page { width:min(1280px, calc(100vw - 24px)); margin:18px auto 28px; display:grid; gap:18px; }",
    "        .panel, .sheet { background:var(--panel); border:1px solid var(--line); border-radius:20px; box-shadow:0 12px 28px rgba(15,23,42,.08); padding:18px; }",
    "        .sheet { width:210mm; min-height:297mm; margin:0 auto; padding:12mm 14mm 12mm; border-radius:0; }",
    "        .sheet + .sheet { margin-top:16px; }",
    "        h1,h2,h3 { margin:0; }",
    "        .lead { margin:8px 0 0; color:var(--muted); line-height:1.6; font-size:14px; }",
    "        .flash { margin-top:14px; padding:12px 14px; border-radius:14px; font-size:14px; line-height:1.6; }",
    "        .flash.notice { background:var(--accent-soft); color:#134e4a; }",
    "        .flash.error { background:var(--danger-soft); color:var(--danger); }",
    "        .actions, .employee-grid, .mode-row, .inline-actions { display:flex; gap:10px; flex-wrap:wrap; align-items:center; }",
    "        .actions, .mode-row { margin-top:16px; }",
    "        .button, button { display:inline-flex; align-items:center; justify-content:center; padding:10px 14px; border-radius:12px; border:0; cursor:pointer; background:var(--accent); color:#fff; text-decoration:none; font:inherit; }",
    "        .button.secondary, button.secondary { background:#e2e8f0; color:#0f172a; }",
    "        .employee-grid { margin-top:16px; }",
    "        .employee-option { width:calc(33.333% - 7px); min-width:260px; border:1px solid var(--line); border-radius:16px; padding:12px 14px; background:#f8fafc; }",
    "        .employee-option label { display:flex; gap:10px; align-items:flex-start; cursor:pointer; }",
    "        .employee-name { font-weight:700; }",
    "        .employee-meta { color:var(--muted); font-size:12px; line-height:1.6; }",
    "        .form-grid { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:12px; margin-top:16px; }",
    "        .field { display:grid; gap:6px; }",
    "        .field label { font-size:12px; font-weight:700; color:var(--muted); }",
    "        .field input, .field textarea, .field select { width:100%; border:1px solid var(--line); border-radius:12px; padding:10px 12px; font:inherit; background:#fff; }",
    "        .field textarea { min-height:140px; resize:vertical; }",
    "        .field.span-4 { grid-column:1 / -1; }",
    "        .hint { color:var(--muted); font-size:12px; line-height:1.7; }",
    "        .locale-note { margin-top:10px; padding:10px 12px; border-radius:12px; background:#f8fafc; color:#334155; font-size:13px; line-height:1.7; }",
    "        .doc-head { display:flex; justify-content:space-between; gap:16px; align-items:flex-start; }",
    "        .doc-title { text-align:center; margin:14px 0 18px; font-size:28px; font-weight:800; letter-spacing:.03em; }",
    "        .doc-subtitle { text-align:center; margin:-8px 0 14px; color:#475569; font-size:15px; font-weight:700; }",
    "        .doc-meta { font-size:13px; line-height:1.8; }",
    "        .ko-small { font-size:.78em; color:#475569; font-weight:600; }",
    "        .ru-main { font-size:1em; color:#111827; }",
    "        .block-gap { margin-bottom:8px; }",
    "        table { width:100%; border-collapse:collapse; margin-top:12px; }",
    "        th, td { border:1px solid #222; padding:8px 10px; font-size:13px; line-height:1.5; text-align:left; vertical-align:top; }",
    "        th { background:#f8fafc; width:120px; }",
    "        .section-title { margin-top:14px; font-size:16px; font-weight:700; }",
    "        .pledge-box { margin-top:8px; border:1px solid #222; padding:10px 12px; line-height:1.65; font-size:13px; white-space:pre-line; }",
    "        .sign-area { margin-top:14px; display:grid; grid-template-columns:1fr 1fr; gap:12px; }",
    "        .sign-box { border:1px solid #222; min-height:102px; padding:10px; }",
    "        .sign-box h3 { font-size:14px; margin-bottom:10px; }",
    "        .sign-line { margin-top:24px; text-align:right; font-size:13px; }",
    "        .note { margin-top:10px; color:#475569; font-size:11px; line-height:1.55; }",
    "        .empty { padding:24px 18px; border:1px dashed var(--line); border-radius:16px; color:var(--muted); text-align:center; line-height:1.8; margin-top:14px; }",
    "        .receipt-list { display:grid; gap:14px; margin-top:16px; }",
    "        .receipt-card { border:1px solid var(--line); border-radius:18px; padding:16px; background:#f8fbfd; }",
    "        .receipt-top { display:flex; justify-content:space-between; gap:16px; align-items:flex-start; flex-wrap:wrap; }",
    "        .receipt-title { font-size:16px; font-weight:800; }",
    "        .receipt-meta { color:var(--muted); font-size:13px; line-height:1.7; }",
    "        .badge { display:inline-flex; align-items:center; padding:6px 10px; border-radius:999px; font-size:12px; font-weight:700; }",
    "        .badge.issued { background:#e0f2fe; color:#0c4a6e; }",
    "        .badge.confirmed { background:#dcfce7; color:#166534; }",
    "        .receipt-grid { display:grid; grid-template-columns:1.15fr .85fr; gap:14px; margin-top:14px; }",
    "        .sub-panel { border:1px solid var(--line); border-radius:14px; padding:14px; background:#fff; }",
    "        .mini-table { width:100%; margin-top:10px; }",
    "        .mini-table th, .mini-table td { font-size:12px; padding:7px 8px; }",
    "        .attachment-link { display:inline-flex; align-items:center; gap:6px; margin-top:8px; color:var(--accent); text-decoration:none; font-weight:700; }",
    "        .attachment-link:hover { text-decoration:underline; }",
    "        @media (max-width:980px) { .form-grid, .receipt-grid, .sign-area { grid-template-columns:1fr; } }",
    "        @media print { body { background:#fff; } .no-print { display:none !important; } .page { width:auto; margin:0; } .sheet { width:auto; min-height:auto; margin:0; box-shadow:none; border:0; page-break-after:always; } .sheet:last-child { page-break-after:auto; } }",
    "    </style>",
    "</head>",
    "<body>",
    "    <div class=\"page\">",
    "        <section class=\"panel no-print\">",
    "            <h1>보호구 지급확인서 출력</h1>",
    "            <p class=\"lead\">직원별 또는 일용근로자 직접입력 방식으로 확인서를 만들고, 출력 후 DB 저장, 서명지 첨부, 안전관리자 확인 완료 처리까지 진행할 수 있습니다.</p>",
    "            <?php if ($noticeMessage !== ''): ?><div class=\"flash notice\"><?= h($noticeMessage) ?></div><?php endif; ?>",
    "            <?php if ($errorMessage !== ''): ?><div class=\"flash error\"><?= h($errorMessage) ?></div><?php endif; ?>",
    "            <form method=\"get\" id=\"daily-builder-form\">",
    "                <div class=\"actions\">",
    "                    <a class=\"button secondary\" href=\"/safety_gear/index.php\">보호구 관리로 돌아가기</a>",
    "                    <a class=\"button secondary\" href=\"/risk_assessment/work_list.php\">작업목록으로 이동</a>",
    "                    <button type=\"submit\" class=\"button\">확인서 생성</button>",
    "                    <?php if ($printMode && !empty($printGroups)): ?><button type=\"button\" class=\"button secondary\" onclick=\"window.print()\">인쇄하기</button><?php endif; ?>",
    "                </div>",
    "                <div class=\"mode-row\">",
    "                    <label><input type=\"radio\" name=\"mode\" value=\"employee\"<?= $mode !== 'daily' ? ' checked' : '' ?>> 직원 선택 출력</label>",
    "                    <label><input type=\"radio\" name=\"mode\" value=\"daily\"<?= $mode === 'daily' ? ' checked' : '' ?>> 일용근로자 직접입력 출력</label>",
    "                </div>",
    "            </form>",
    "        </section>",
    "    </div>",
    "</body>",
    "</html>",
]

lines = prefix + tail
path.write_text(\"\\n\".join(lines) + \"\\n\", encoding=\"utf-8\")
