<?php

declare(strict_types=1);

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\ActivityLogModel;
use Config\Roles;

/**
 * 사용자 작업(감사) 로그 조회 — 생성/수정/삭제 이력.
 * 관리자 전용(adminAuth). 슈퍼/본부는 전체, 지자체관리자는 소속 지자체 사용자만.
 */
class ActivityLog extends BaseController
{
    private ActivityLogModel $logModel;

    /** 테이블명 → 한글 라벨 */
    private const TABLE_LABELS = [
        'member'                   => '회원',
        'member_approval_request'  => '회원 승인요청',
        'company'                  => '업체',
        'designated_shop'          => '지정판매소',
        'sales_agency'             => '판매 대행소',
        'free_recipient'           => '무료 수령처',
        'manager'                  => '담당자',
        'local_government'         => '지자체',
        'code_kind'                => '기본코드 종류',
        'code_detail'              => '기본코드',
        'packaging_unit'           => '포장 단위',
        'packaging_unit_history'   => '포장 단위 이력',
        'bag_price'                => '단가',
        'bag_price_history'        => '단가 이력',
        'bag_order'                => '발주',
        'bag_order_item'           => '발주 품목',
        'bag_receiving'            => '입고',
        'bag_inventory'            => '재고',
        'bag_sale'                 => '판매',
        'bag_issue'                => '무료용 불출',
        'bag_issue_item_code'      => '불출 품목코드',
        'shop_order'               => '전화 주문',
        'shop_order_item'          => '전화 주문 품목',
        'menu'                     => '메뉴',
        'menu_type'                => '메뉴 유형',
        'feedback'                 => '사용자 의견',
        'feedback_file'            => '의견 첨부',
        'blockchain_ledger'        => '원장',
        'export'                   => '엑셀 다운로드',
        'print'                    => '인쇄',
    ];

    /** action → 한글 라벨 */
    private const ACTION_LABELS = [
        'create' => '등록',
        'update' => '수정',
        'delete' => '삭제',
        'export' => '엑셀 다운로드',
        'print'  => '인쇄',
    ];

    /** 컬럼 → 한글 라벨 (없으면 접미사 추정 → 원문) */
    private const FIELD_LABELS = [
        'mb_id' => '아이디', 'mb_name' => '이름', 'mb_level' => '권한등급', 'mb_group' => '그룹',
        'cp_type' => '구분', 'cp_biz_no' => '사업자번호', 'cp_rep_name' => '대표자',
        'ds_shop_no' => '지정번호', 'ds_rep_name' => '대표자', 'ds_biz_no' => '사업자번호',
        'ck_code' => '코드', 'cd_code' => '코드', 'cd_value' => '값', 'cd_sort' => '정렬순서',
        'sa_kind' => '종류', 'lg_sido' => '시도', 'lg_gugun' => '구·군',
        'mm_link' => '메뉴 링크', 'mm_is_view' => '노출여부', 'mm_level' => '노출등급',
        'bs_bag_name' => '품목', 'bs_qty' => '수량', 'bs_amount' => '금액', 'bs_sale_date' => '판매일',
        'bo_status' => '상태', 'bi2_status' => '상태',
    ];

    /** 로그인 시 갱신되는 회원 필드(이것만 바뀌면 '로그인'으로 표시) */
    private const LOGIN_FIELDS = ['mb_session_token', 'mb_latestdate', 'mb_login_fail_count', 'mb_locked_until'];

    public function __construct()
    {
        $this->logModel = model(ActivityLogModel::class);
    }

    /** 컬럼명 → 한글 라벨 (정확 매칭 → 접미사 추정 → 원문) */
    private function fieldLabel(string $col): string
    {
        if (isset(self::FIELD_LABELS[$col])) {
            return self::FIELD_LABELS[$col];
        }
        $suffix = [
            '_name' => '이름', '_tel' => '전화번호', '_phone' => '전화번호', '_addr' => '주소',
            '_email' => '이메일', '_state' => '상태', '_regdate' => '등록일', '_date' => '일자',
            '_qty' => '수량', '_amount' => '금액', '_price' => '단가', '_code' => '코드',
        ];
        foreach ($suffix as $sfx => $lbl) {
            if (str_ends_with($col, $sfx)) {
                return $lbl;
            }
        }

        return $col;
    }

    /** 레코드 표시 이름 추출 (이름 계열 필드 우선) */
    private function recordName(array $data): string
    {
        foreach (['mb_name', 'cp_name', 'ds_name', 'lg_name', 'ck_name', 'cd_name', 'sa_name', 'fr_name', 'mn_name', 'mm_name'] as $k) {
            if (! empty($data[$k])) {
                return (string) $data[$k];
            }
        }
        foreach ($data as $k => $v) {
            if (str_ends_with((string) $k, '_name') && (string) $v !== '') {
                return (string) $v;
            }
        }

        return '';
    }

    private function fmtVal(mixed $v): string
    {
        if (is_array($v)) {
            $v = json_encode($v, JSON_UNESCAPED_UNICODE);
        }
        $s = (string) ($v ?? '');
        if ($s === '') {
            return '(없음)';
        }

        return mb_strlen($s) > 10 ? mb_substr($s, 0, 10) . '…' : $s;
    }

    /** 로그 1행에 사람이 읽기 쉬운 요약(summaryText)·변경목록(changeList)·로그인여부(isLogin)를 붙인다 */
    private function attachSummary(object $row): void
    {
        $table  = (string) ($row->al_table ?? '');
        $action = (string) ($row->al_action ?? '');
        $before = $row->al_data_before ? (json_decode((string) $row->al_data_before, true) ?: []) : [];
        $after  = $row->al_data_after ? (json_decode((string) $row->al_data_after, true) ?: []) : [];
        $tlabel = self::TABLE_LABELS[$table] ?? $table;

        $changes = [];
        $isLogin = false;
        if ($action === 'update') {
            foreach ($after as $k => $v) {
                $bv = $before[$k] ?? null;
                if (! array_key_exists($k, $before) || (string) $bv !== (string) $v) {
                    $changes[$k] = [$bv, $v];
                }
            }
            if ($table === 'member' && $changes !== [] && array_diff(array_keys($changes), self::LOGIN_FIELDS) === []) {
                $isLogin = true;
            }
        }

        $name = $this->recordName($action === 'delete' ? $before : $after);
        if ($name === '') {
            $name = $this->recordName($before);
        }
        $namePart = $name !== '' ? " '" . $name . "'" : ((int) ($row->al_record_id ?? 0) ? ' #' . (int) $row->al_record_id : '');

        if ($isLogin) {
            $text = '로그인';
        } elseif ($action === 'export') {
            $text = '엑셀 다운로드 — ' . (string) ($after['파일'] ?? '');
        } elseif ($action === 'print') {
            $text = '인쇄 — ' . (string) ($after['화면'] ?? $after['경로'] ?? '');
        } elseif ($action === 'create') {
            $text = $tlabel . $namePart . ' 등록';
        } elseif ($action === 'delete') {
            $text = $tlabel . $namePart . ' 삭제';
        } else {
            $text = $tlabel . $namePart . ' 수정';
        }

        $skip = array_merge(self::LOGIN_FIELDS, ['mb_passwd', 'mb_totp_secret', 'mb_session_token']);
        $changeList = [];
        foreach ($changes as $k => $pair) {
            if (in_array($k, $skip, true)) {
                continue;
            }
            $changeList[] = [
                'label' => $this->fieldLabel($k),
                'from'  => $this->fmtVal($pair[0]),
                'to'    => $this->fmtVal($pair[1]),
            ];
        }

        $row->summaryText = $text;
        $row->isLogin     = $isLogin;
        $row->changeList  = $changeList;
    }

    public function index(): string
    {
        helper('admin');

        $start  = (string) ($this->request->getGet('start') ?? '');
        $end    = (string) ($this->request->getGet('end') ?? '');
        $action = (string) ($this->request->getGet('action') ?? '');
        $table  = (string) ($this->request->getGet('table') ?? '');
        $user   = trim((string) ($this->request->getGet('user') ?? ''));

        $builder = $this->logModel
            ->select('activity_log.*, member.mb_id, member.mb_name, member.mb_lg_idx')
            ->join('member', 'member.mb_idx = activity_log.al_mb_idx', 'left');

        // 테넌트 분리: 슈퍼/본부는 전체, 그 외 관리자는 소속 지자체 사용자만
        $level = (int) session()->get('mb_level');
        if (! Roles::isSuperAdminEquivalent($level)) {
            $lgIdx = admin_effective_lg_idx();
            $builder->where('member.mb_lg_idx', $lgIdx);
        }

        if ($start !== '') {
            $builder->where('activity_log.al_regdate >=', $start . ' 00:00:00');
        }
        if ($end !== '') {
            $builder->where('activity_log.al_regdate <=', $end . ' 23:59:59');
        }
        if (isset(self::ACTION_LABELS[$action])) {
            $builder->where('activity_log.al_action', $action);
        }
        if ($table !== '' && isset(self::TABLE_LABELS[$table])) {
            $builder->where('activity_log.al_table', $table);
        }
        if ($user !== '') {
            $builder->groupStart()
                ->like('member.mb_id', $user)
                ->orLike('member.mb_name', $user)
                ->groupEnd();
        }

        $list  = $builder->orderBy('activity_log.al_idx', 'DESC')->paginate(20);
        $pager = $this->logModel->pager;

        foreach ($list as $row) {
            $this->attachSummary($row);
        }

        return view('admin/layout', [
            'title'   => '활동 로그',
            'content' => view('admin/access/activity_log', [
                'list'        => $list,
                'pager'       => $pager,
                'start'       => $start,
                'end'         => $end,
                'action'      => $action,
                'table'       => $table,
                'user'        => $user,
                'tableLabels' => self::TABLE_LABELS,
                'actionLabels' => self::ACTION_LABELS,
            ]),
        ]);
    }

    public function show(int $id): string
    {
        helper('admin');
        $row = $this->logModel
            ->select('activity_log.*, member.mb_id, member.mb_name, member.mb_lg_idx')
            ->join('member', 'member.mb_idx = activity_log.al_mb_idx', 'left')
            ->where('activity_log.al_idx', $id)
            ->first();

        if ($row === null) {
            return view('admin/layout', [
                'title'   => '활동 로그',
                'content' => '<div class="p-6 text-gray-500">로그를 찾을 수 없습니다.</div>',
            ]);
        }

        // 테넌트 분리 검증
        $level = (int) session()->get('mb_level');
        if (! Roles::isSuperAdminEquivalent($level)) {
            $lgIdx = admin_effective_lg_idx();
            if ((int) ($row->mb_lg_idx ?? 0) !== (int) $lgIdx) {
                return view('admin/layout', [
                    'title'   => '활동 로그',
                    'content' => '<div class="p-6 text-gray-500">접근 권한이 없습니다.</div>',
                ]);
            }
        }

        $before = $row->al_data_before ? (json_decode((string) $row->al_data_before, true) ?: []) : [];
        $after  = $row->al_data_after ? (json_decode((string) $row->al_data_after, true) ?: []) : [];

        return view('admin/layout', [
            'title'   => '활동 로그 상세',
            'content' => view('admin/access/activity_log_detail', [
                'row'         => $row,
                'before'      => $before,
                'after'       => $after,
                'tableLabels' => self::TABLE_LABELS,
                'actionLabels' => self::ACTION_LABELS,
            ]),
        ]);
    }
}
