-- =============================================================================
-- 업체(company) 이후 업무 메뉴용 테이블 일괄 생성
-- =============================================================================
-- 선행 조건: local_government, code_kind, code_detail, company
--   (및 회원/로그인 흐름이 있으면 login_tables.sql 로 member, member_log 등)
--
-- 이미 login_tables.sql 을 실행했다면 designated_shop 은 건너뜁니다(CREATE IF NOT EXISTS).
--
-- 실행 예:
--   mysql --default-character-set=utf8mb4 -h 127.0.0.1 -u USER -p DB_NAME < writable/database/after_company_feature_tables.sql
--
-- 원본 분할 스크립트(동일 정의): bag_price_tables.sql, packaging_unit_tables.sql,
-- sales_agency_tables.sql, manager_tables.sql, free_recipient_tables.sql,
-- order_tables.sql, sales_tables.sql, activity_log_tables.sql, bag_misc_flow_tables.sql,
-- login_tables.sql (designated_shop 부분만 아래에 포함)
-- =============================================================================

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ---------------------------------------------------------------------------
-- 지정판매소 (주문/판매 메뉴 FK) — login_tables.sql 과 동일
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `designated_shop` (
  `ds_idx`           INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '지정판매소 PK',
  `ds_lg_idx`        INT UNSIGNED NOT NULL COMMENT '소속 지자체 FK',
  `ds_mb_idx`        INT UNSIGNED NULL     DEFAULT NULL COMMENT '로그인 회원 FK(1:1)',
  `ds_shop_no`       VARCHAR(50)  NOT NULL DEFAULT '' COMMENT '판매소번호',
  `ds_name`          VARCHAR(100) NOT NULL DEFAULT '' COMMENT '상호명',
  `ds_biz_no`        VARCHAR(20)  NOT NULL DEFAULT '' COMMENT '사업자번호',
  `ds_rep_name`      VARCHAR(50)  NOT NULL DEFAULT '' COMMENT '대표자명',
  `ds_biz_type`      VARCHAR(100) NOT NULL DEFAULT '' COMMENT '업태',
  `ds_biz_kind`      VARCHAR(100) NOT NULL DEFAULT '' COMMENT '업종',
  `ds_va_number`     VARCHAR(50)  NOT NULL DEFAULT '' COMMENT '가상계좌(표시용 번호, 계좌번호와 동기화 가능)',
  `ds_va_bank`       VARCHAR(80)  NOT NULL DEFAULT '' COMMENT '가상계좌(은행)',
  `ds_va_account`    VARCHAR(50)  NOT NULL DEFAULT '' COMMENT '계좌번호',
  `ds_zip`           VARCHAR(10)  NOT NULL DEFAULT '' COMMENT '우편번호',
  `ds_addr`          VARCHAR(255) NOT NULL DEFAULT '' COMMENT '도로명주소',
  `ds_addr_jibun`    VARCHAR(255) NOT NULL DEFAULT '' COMMENT '지번주소',
  `ds_addr_detail`   VARCHAR(200) NOT NULL DEFAULT '' COMMENT '상세주소(동·호 등)',
  `ds_tel`           VARCHAR(20)  NOT NULL DEFAULT '' COMMENT '일반전화',
  `ds_rep_phone`     VARCHAR(20)  NOT NULL DEFAULT '' COMMENT '개인전화',
  `ds_email`         VARCHAR(100) NOT NULL DEFAULT '' COMMENT '이메일',
  `ds_gugun_code`    VARCHAR(20)  NOT NULL DEFAULT '' COMMENT '구코드',
  `ds_zone_code`     VARCHAR(80)  NOT NULL DEFAULT '' COMMENT '구역',
  `ds_branch_no`     VARCHAR(50)  NOT NULL DEFAULT '' COMMENT '종사업장번호',
  `ds_designated_at` DATE         NULL     DEFAULT NULL COMMENT '지정일자',
  `ds_state`         TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '1=정상, 2=폐업, 3=직권해지',
  `ds_state_changed_at` DATE      NULL     DEFAULT NULL COMMENT '변경일자',
  `ds_change_reason` VARCHAR(500) NOT NULL DEFAULT '' COMMENT '변경사유',
  `ds_regdate`       DATETIME     NOT NULL COMMENT '등록일시',
  PRIMARY KEY (`ds_idx`),
  KEY `idx_ds_lg_idx` (`ds_lg_idx`),
  KEY `idx_ds_mb_idx` (`ds_mb_idx`),
  UNIQUE KEY `uk_ds_shop_no` (`ds_shop_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='지정판매소';

-- ---------------------------------------------------------------------------
-- 판매 대행소 (sales_agency_tables.sql)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `sales_agency` (
  `sa_idx`       INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `sa_lg_idx`    INT UNSIGNED NOT NULL COMMENT '지자체 FK',
  `sa_kind`      VARCHAR(50)  NOT NULL DEFAULT '' COMMENT '대행소 구분',
  `sa_code`      VARCHAR(50)  NOT NULL DEFAULT '' COMMENT '대행소 코드',
  `sa_name`      VARCHAR(100) NOT NULL DEFAULT '' COMMENT '대행소 명',
  `sa_regdate`   DATETIME NOT NULL,
  PRIMARY KEY (`sa_idx`),
  UNIQUE KEY `uk_sa_lg_code` (`sa_lg_idx`, `sa_code`),
  KEY `idx_sa_lg_idx` (`sa_lg_idx`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='판매 대행소';

-- ---------------------------------------------------------------------------
-- 담당자 (manager_tables.sql)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `manager` (
  `mg_idx`           INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `mg_lg_idx`        INT UNSIGNED NOT NULL COMMENT '지자체 FK',
  `mg_name`          VARCHAR(50) NOT NULL DEFAULT '' COMMENT '담당자명',
  `mg_dept_code`     VARCHAR(20) NOT NULL DEFAULT '' COMMENT '소속 code_detail(S)',
  `mg_position_code` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '직위 code_detail(T)',
  `mg_tel`           VARCHAR(20) NOT NULL DEFAULT '' COMMENT '전화번호',
  `mg_phone`         VARCHAR(20) NOT NULL DEFAULT '' COMMENT '휴대전화',
  `mg_email`         VARCHAR(100) NOT NULL DEFAULT '' COMMENT '이메일',
  `mg_state`         TINYINT UNSIGNED NOT NULL DEFAULT 1,
  `mg_regdate`       DATETIME NOT NULL,
  PRIMARY KEY (`mg_idx`),
  KEY `idx_mg_lg_idx` (`mg_lg_idx`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='담당자';

-- ---------------------------------------------------------------------------
-- 무료용 대상자 (free_recipient_tables.sql)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `free_recipient` (
  `fr_idx`       INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `fr_lg_idx`    INT UNSIGNED NOT NULL COMMENT '지자체 FK',
  `fr_type_code` VARCHAR(20) NOT NULL COMMENT '무상지급구분 code_detail(H)',
  `fr_name`      VARCHAR(100) NOT NULL DEFAULT '' COMMENT '대상자/기관명',
  `fr_phone`     VARCHAR(20) NOT NULL DEFAULT '',
  `fr_addr`      VARCHAR(255) NOT NULL DEFAULT '',
  `fr_dong_code` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '동코드 code_detail(D)',
  `fr_note`      VARCHAR(255) NOT NULL DEFAULT '' COMMENT '비고',
  `fr_end_date`  DATE NULL DEFAULT NULL COMMENT '종료일자',
  `fr_state`     TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '1=정상, 0=삭제',
  `fr_regdate`   DATETIME NOT NULL,
  PRIMARY KEY (`fr_idx`),
  KEY `idx_fr_lg_idx` (`fr_lg_idx`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='무료용 대상자';

-- ---------------------------------------------------------------------------
-- 봉투 단가 (bag_price_tables.sql)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `bag_price` (
  `bp_idx`        INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `bp_lg_idx`     INT UNSIGNED NOT NULL COMMENT '지자체 FK',
  `bp_bag_code`   VARCHAR(50)  NOT NULL COMMENT '봉투코드(code_detail cd_code, ck=O)',
  `bp_bag_name`   VARCHAR(100) NOT NULL DEFAULT '' COMMENT '봉투명(등록시점 스냅샷)',
  `bp_order_price`  DECIMAL(12,2) NOT NULL DEFAULT 0 COMMENT '발주단가',
  `bp_wholesale`    DECIMAL(12,2) NOT NULL DEFAULT 0 COMMENT '도매가',
  `bp_consumer`     DECIMAL(12,2) NOT NULL DEFAULT 0 COMMENT '소비자가',
  `bp_start_date` DATE NOT NULL COMMENT '적용 시작일',
  `bp_end_date`   DATE NULL DEFAULT NULL COMMENT '적용 종료일(NULL=현재 적용중)',
  `bp_state`      TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '1=사용, 0=미사용',
  `bp_regdate`    DATETIME NOT NULL,
  `bp_moddate`    DATETIME NULL DEFAULT NULL,
  `bp_reg_mb_idx` INT UNSIGNED NULL COMMENT '등록자',
  PRIMARY KEY (`bp_idx`),
  KEY `idx_bp_lg_bag` (`bp_lg_idx`, `bp_bag_code`),
  KEY `idx_bp_dates` (`bp_start_date`, `bp_end_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='지자체별 봉투 단가';

CREATE TABLE IF NOT EXISTS `bag_price_history` (
  `bph_idx`          INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `bph_bp_idx`       INT UNSIGNED NOT NULL COMMENT 'bag_price FK',
  `bph_field`        VARCHAR(30) NOT NULL COMMENT '변경 필드명',
  `bph_old_value`    VARCHAR(100) NOT NULL DEFAULT '',
  `bph_new_value`    VARCHAR(100) NOT NULL DEFAULT '',
  `bph_changed_at`   DATETIME NOT NULL,
  `bph_changed_by`   INT UNSIGNED NULL COMMENT '변경자 mb_idx',
  PRIMARY KEY (`bph_idx`),
  KEY `idx_bph_bp_idx` (`bph_bp_idx`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='봉투 단가 변경 이력';

-- ---------------------------------------------------------------------------
-- 포장 단위 (packaging_unit_tables.sql)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `packaging_unit` (
  `pu_idx`        INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `pu_lg_idx`     INT UNSIGNED NOT NULL COMMENT '지자체 FK',
  `pu_bag_code`   VARCHAR(50) NOT NULL COMMENT '봉투코드(code_detail cd_code, ck=O)',
  `pu_bag_name`   VARCHAR(100) NOT NULL DEFAULT '' COMMENT '봉투명(스냅샷)',
  `pu_box_per_pack` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '박스당 팩 수',
  `pu_pack_per_sheet` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '팩당 낱장 수',
  `pu_total_per_box` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '1박스당 총 낱장 수',
  `pu_start_date` DATE NOT NULL,
  `pu_end_date`   DATE NULL DEFAULT NULL,
  `pu_state`      TINYINT UNSIGNED NOT NULL DEFAULT 1,
  `pu_regdate`    DATETIME NOT NULL,
  `pu_moddate`    DATETIME NULL DEFAULT NULL,
  `pu_reg_mb_idx` INT UNSIGNED NULL,
  PRIMARY KEY (`pu_idx`),
  KEY `idx_pu_lg_bag` (`pu_lg_idx`, `pu_bag_code`),
  KEY `idx_pu_dates` (`pu_start_date`, `pu_end_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='포장 단위';

CREATE TABLE IF NOT EXISTS `packaging_unit_history` (
  `puh_idx`        INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `puh_pu_idx`     INT UNSIGNED NOT NULL,
  `puh_field`      VARCHAR(30) NOT NULL,
  `puh_old_value`  VARCHAR(100) NOT NULL DEFAULT '',
  `puh_new_value`  VARCHAR(100) NOT NULL DEFAULT '',
  `puh_changed_at` DATETIME NOT NULL,
  `puh_changed_by` INT UNSIGNED NULL,
  PRIMARY KEY (`puh_idx`),
  KEY `idx_puh_pu_idx` (`puh_pu_idx`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='포장 단위 변경 이력';

-- ---------------------------------------------------------------------------
-- 발주 / 입고 / 재고 (order_tables.sql)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `bag_order` (
  `bo_idx`         INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `bo_uuid`        CHAR(36) NOT NULL COMMENT 'UUID v4',
  `bo_version`     INT UNSIGNED NOT NULL DEFAULT 1 COMMENT '발주 버전',
  `bo_lg_idx`      INT UNSIGNED NOT NULL COMMENT '지자체 FK',
  `bo_gugun_code`  VARCHAR(20) NOT NULL DEFAULT '' COMMENT '구/군 코드',
  `bo_dong_code`   VARCHAR(20) NOT NULL DEFAULT '' COMMENT '동 코드',
  `bo_company_idx` INT UNSIGNED NULL COMMENT '제작업체 FK (company)',
  `bo_agency_idx`  INT UNSIGNED NULL COMMENT '입고처(대행소) FK (sales_agency)',
  `bo_fee_rate`    DECIMAL(5,2) NOT NULL DEFAULT 0 COMMENT '수수료율(%)',
  `bo_order_date`  DATE NOT NULL COMMENT '발주일',
  `bo_bag_types`   TEXT NULL COMMENT '봉투 종류 목록(JSON)',
  `bo_unit_prices` TEXT NULL COMMENT '발주 단가 목록(JSON)',
  `bo_qty_boxes`   TEXT NULL COMMENT '발주 박스 수량 목록(JSON)',
  `bo_lot_no`      VARCHAR(50) NOT NULL DEFAULT '' COMMENT 'LOT 번호',
  `bo_hash`        VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'SHA-256 해시',
  `bo_status`      VARCHAR(10) NOT NULL DEFAULT 'normal' COMMENT 'normal/cancelled/deleted',
  `bo_orderer_idx` INT UNSIGNED NULL COMMENT '발주자 mb_idx',
  `bo_regdate`     DATETIME NOT NULL COMMENT '등록일시',
  `bo_moddate`     DATETIME NULL DEFAULT NULL COMMENT '수정일시',
  PRIMARY KEY (`bo_uuid`, `bo_version`),
  -- 코드/화면 로직은 bo_idx(숫자 PK)로 조회/취소/삭제하고 있어, bo_idx도 유니크로 유지한다.
  UNIQUE KEY `uk_bo_idx` (`bo_idx`),
  UNIQUE KEY `uk_bo_uuid_ver` (`bo_uuid`, `bo_version`),
  KEY `idx_bo_lg_idx` (`bo_lg_idx`),
  KEY `idx_bo_status` (`bo_status`),
  KEY `idx_bo_order_date` (`bo_order_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='발주';

CREATE TABLE IF NOT EXISTS `bag_order_item` (
  `boi_idx`        INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `boi_bo_idx`     INT UNSIGNED NOT NULL COMMENT 'bag_order FK',
  `boi_bag_code`   VARCHAR(50) NOT NULL COMMENT '봉투코드(code_detail O)',
  `boi_bag_name`   VARCHAR(100) NOT NULL DEFAULT '',
  `boi_unit_price` DECIMAL(12,2) NOT NULL DEFAULT 0 COMMENT '발주 단가',
  `boi_qty_box`    INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '발주 박스 수',
  `boi_qty_sheet`  INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '낱장 환산 수량',
  `boi_amount`     DECIMAL(14,2) NOT NULL DEFAULT 0 COMMENT '금액(단가*낱장수)',
  PRIMARY KEY (`boi_idx`),
  KEY `idx_boi_bo_idx` (`boi_bo_idx`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='발주 상세';

CREATE TABLE IF NOT EXISTS `bag_receiving` (
  `br_idx`         INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `br_bo_idx`      INT UNSIGNED NOT NULL COMMENT 'bag_order FK',
  `br_lg_idx`      INT UNSIGNED NOT NULL,
  `br_bag_code`    VARCHAR(50) NOT NULL,
  `br_bag_name`    VARCHAR(100) NOT NULL DEFAULT '',
  `br_qty_box`     INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '입고 박스 수',
  `br_qty_sheet`   INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '입고 낱장 수',
  `br_receive_date` DATE NOT NULL,
  `br_receiver_idx` INT UNSIGNED NULL COMMENT '인수자 mb_idx',
  `br_sender_name` VARCHAR(50) NOT NULL DEFAULT '' COMMENT '인계자명',
  `br_type`        VARCHAR(20) NOT NULL DEFAULT 'scanner' COMMENT 'scanner/batch',
  `br_regdate`     DATETIME NOT NULL,
  PRIMARY KEY (`br_idx`),
  KEY `idx_br_bo_idx` (`br_bo_idx`),
  KEY `idx_br_lg_idx` (`br_lg_idx`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='발주 입고';

CREATE TABLE IF NOT EXISTS `bag_inventory` (
  `bi_idx`       INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `bi_lg_idx`    INT UNSIGNED NOT NULL,
  `bi_bag_code`  VARCHAR(50) NOT NULL,
  `bi_bag_name`  VARCHAR(100) NOT NULL DEFAULT '',
  `bi_qty`       INT NOT NULL DEFAULT 0 COMMENT '현재 재고(낱장)',
  `bi_updated_at` DATETIME NOT NULL,
  PRIMARY KEY (`bi_idx`),
  UNIQUE KEY `uk_bi_lg_bag` (`bi_lg_idx`, `bi_bag_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='봉투 재고';

-- ---------------------------------------------------------------------------
-- 주문 / 판매 / 불출 (sales_tables.sql)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `shop_order` (
  `so_idx`         INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `so_lg_idx`      INT UNSIGNED NOT NULL,
  `so_ds_idx`      INT UNSIGNED NULL COMMENT '지정판매소 FK',
  `so_ds_name`     VARCHAR(100) NOT NULL DEFAULT '' COMMENT '판매소명(스냅샷)',
  `so_order_date`  DATE NOT NULL COMMENT '접수일',
  `so_delivery_date` DATE NULL COMMENT '배달일',
  `so_payment_type` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '이체/가상계좌',
  `so_channel`     VARCHAR(20) NOT NULL DEFAULT 'phone' COMMENT '접수채널 phone/web/app/counter',
  `so_paid`        TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '입금여부 1=예',
  `so_received`    TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '수령여부 1=예',
  `so_total_qty`   INT UNSIGNED NOT NULL DEFAULT 0,
  `so_total_amount` DECIMAL(14,2) NOT NULL DEFAULT 0,
  `so_status`      VARCHAR(10) NOT NULL DEFAULT 'normal' COMMENT 'normal/cancelled',
  `so_orderer_idx` INT UNSIGNED NULL,
  `so_regdate`     DATETIME NOT NULL,
  PRIMARY KEY (`so_idx`),
  KEY `idx_so_lg_idx` (`so_lg_idx`),
  KEY `idx_so_ds_idx` (`so_ds_idx`),
  KEY `idx_so_lg_order_channel` (`so_lg_idx`, `so_order_date`, `so_channel`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='주문 접수';

CREATE TABLE IF NOT EXISTS `shop_order_item` (
  `soi_idx`        INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `soi_so_idx`     INT UNSIGNED NOT NULL,
  `soi_bag_code`   VARCHAR(50) NOT NULL,
  `soi_bag_name`   VARCHAR(100) NOT NULL DEFAULT '',
  `soi_unit_price` DECIMAL(12,2) NOT NULL DEFAULT 0,
  `soi_qty`        INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '접수량(낱장)',
  `soi_amount`     DECIMAL(14,2) NOT NULL DEFAULT 0,
  `soi_box_count`  INT UNSIGNED NOT NULL DEFAULT 0,
  `soi_pack_count` INT UNSIGNED NOT NULL DEFAULT 0,
  `soi_sheet_count` INT UNSIGNED NOT NULL DEFAULT 0,
  PRIMARY KEY (`soi_idx`),
  KEY `idx_soi_so_idx` (`soi_so_idx`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='주문 상세';

CREATE TABLE IF NOT EXISTS `bag_sale` (
  `bs_idx`        INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `bs_lg_idx`     INT UNSIGNED NOT NULL,
  `bs_so_idx`     INT UNSIGNED NULL COMMENT '주문 FK (NULL=직접판매)',
  `bs_ds_idx`     INT UNSIGNED NULL COMMENT '지정판매소 FK',
  `bs_ds_name`    VARCHAR(100) NOT NULL DEFAULT '',
  `bs_sale_date`  DATE NOT NULL,
  `bs_bag_code`   VARCHAR(50) NOT NULL,
  `bs_bag_name`   VARCHAR(100) NOT NULL DEFAULT '',
  `bs_qty`        INT NOT NULL DEFAULT 0 COMMENT '판매수량(낱장, 음수=반품)',
  `bs_unit_price` DECIMAL(12,2) NOT NULL DEFAULT 0,
  `bs_amount`     DECIMAL(14,2) NOT NULL DEFAULT 0,
  `bs_type`       VARCHAR(20) NOT NULL DEFAULT 'sale' COMMENT 'sale/return/cancel',
  `bs_regdate`    DATETIME NOT NULL,
  PRIMARY KEY (`bs_idx`),
  KEY `idx_bs_lg_idx` (`bs_lg_idx`),
  KEY `idx_bs_ds_idx` (`bs_ds_idx`),
  KEY `idx_bs_sale_date` (`bs_sale_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='판매/반품';

CREATE TABLE IF NOT EXISTS `bag_issue` (
  `bi2_idx`        INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `bi2_lg_idx`     INT UNSIGNED NOT NULL,
  `bi2_year`       YEAR NOT NULL,
  `bi2_quarter`    TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '분기(1~4)',
  `bi2_issue_type` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '무료용/공공용',
  `bi2_issue_date` DATE NOT NULL,
  `bi2_dest_type`  VARCHAR(20) NOT NULL DEFAULT '' COMMENT '불출처 구분(동사무소 등)',
  `bi2_dest_name`  VARCHAR(100) NOT NULL DEFAULT '' COMMENT '불출처명',
  `bi2_bag_code`   VARCHAR(50) NOT NULL,
  `bi2_bag_name`   VARCHAR(100) NOT NULL DEFAULT '',
  `bi2_qty`        INT NOT NULL DEFAULT 0 COMMENT '불출수량(낱장, 음수=취소)',
  `bi2_status`     VARCHAR(10) NOT NULL DEFAULT 'normal' COMMENT 'normal/cancelled',
  `bi2_regdate`    DATETIME NOT NULL,
  PRIMARY KEY (`bi2_idx`),
  KEY `idx_bi2_lg_idx` (`bi2_lg_idx`),
  KEY `idx_bi2_date` (`bi2_issue_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='무료용 불출';

CREATE TABLE IF NOT EXISTS `bag_issue_item_code` (
  `bic_idx`        BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `bic_lg_idx`     INT UNSIGNED NOT NULL,
  `bic_bi2_idx`    INT UNSIGNED NOT NULL COMMENT 'bag_issue.bi2_idx',
  `bic_bag_code`   VARCHAR(50) NOT NULL DEFAULT '' COMMENT '봉투 종류 코드',
  `bic_issue_code` VARCHAR(80) NOT NULL DEFAULT '' COMMENT '불출 품목 코드',
  `bic_qty`        INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '원수량(낱장)',
  `bic_cancel_qty` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '취소수량(낱장)',
  `bic_state`      VARCHAR(10) NOT NULL DEFAULT 'normal' COMMENT 'normal/cancelled',
  `bic_regdate`    DATETIME NOT NULL,
  PRIMARY KEY (`bic_idx`),
  KEY `idx_bic_lg_idx` (`bic_lg_idx`),
  KEY `idx_bic_bi2_idx` (`bic_bi2_idx`),
  KEY `idx_bic_issue_code` (`bic_issue_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='무료용 불출 품목코드 상세';

-- ---------------------------------------------------------------------------
-- 감사 로그 (activity_log_tables.sql) — audit_helper.php
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `activity_log` (
  `al_idx` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `al_mb_idx` INT UNSIGNED DEFAULT NULL COMMENT '회원 PK',
  `al_action` VARCHAR(20) NOT NULL COMMENT 'create/update/delete',
  `al_table` VARCHAR(100) NOT NULL COMMENT '대상 테이블명',
  `al_record_id` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '대상 레코드 PK',
  `al_data_before` JSON DEFAULT NULL COMMENT '변경 전 데이터',
  `al_data_after` JSON DEFAULT NULL COMMENT '변경 후 데이터',
  `al_ip` VARCHAR(45) NOT NULL DEFAULT '' COMMENT 'IP 주소',
  `al_regdate` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '기록일시',
  PRIMARY KEY (`al_idx`),
  KEY `idx_al_table_record` (`al_table`, `al_record_id`),
  KEY `idx_al_mb` (`al_mb_idx`),
  KEY `idx_al_regdate` (`al_regdate`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='CRUD 활동 로그';

-- 블록체인 원장 (폐쇄형 SQL Ledger)
CREATE TABLE IF NOT EXISTS `blockchain_ledger` (
  `bl_idx`            BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '블록 인덱스(Height)',
  `bl_created_at`     DATETIME NOT NULL COMMENT '블록 생성 시각',
  `bl_tx_type`        VARCHAR(30) NOT NULL DEFAULT '' COMMENT '트랜잭션 타입(ORDER_CREATE/ORDER_UPDATE/...)',
  `bl_entity_uuid`    CHAR(36) NULL COMMENT '업무 엔티티 UUID',
  `bl_entity_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT '엔티티 버전',
  `bl_payload`        JSON NOT NULL COMMENT '블록 payload(JSON)',
  `bl_previous_hash`  CHAR(64) NOT NULL DEFAULT '' COMMENT '이전 블록 해시',
  `bl_hash`           CHAR(64) NOT NULL DEFAULT '' COMMENT '현재 블록 해시',
  `bl_nonce`          INT NOT NULL DEFAULT 0 COMMENT '논스(폐쇄형 체인에서 기본 0)',
  `bl_actor_idx`      INT UNSIGNED NULL COMMENT '수행자 mb_idx',
  `bl_lg_idx`         INT UNSIGNED NULL COMMENT '지자체 lg_idx',
  PRIMARY KEY (`bl_idx`),
  KEY `idx_bl_entity_uuid` (`bl_entity_uuid`),
  KEY `idx_bl_tx_type` (`bl_tx_type`),
  KEY `idx_bl_lg_idx` (`bl_lg_idx`),
  UNIQUE KEY `uk_bl_hash` (`bl_hash`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='블록체인 원장';

-- ---------------------------------------------------------------------------
-- 기타 입출고 리포트 (bag_misc_flow_tables.sql)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `bag_misc_flow` (
  `bmf_idx` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `bmf_lg_idx` INT UNSIGNED NOT NULL COMMENT '지자체 PK',
  `bmf_type` ENUM('in','out') NOT NULL COMMENT '입고/출고',
  `bmf_bag_code` VARCHAR(50) NOT NULL COMMENT '봉투 코드',
  `bmf_bag_name` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '봉투명',
  `bmf_qty` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '수량',
  `bmf_date` DATE NOT NULL COMMENT '입출고 일자',
  `bmf_reason` VARCHAR(200) NOT NULL DEFAULT '' COMMENT '사유',
  `bmf_regdate` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '등록일',
  PRIMARY KEY (`bmf_idx`),
  KEY `idx_bmf_lg_date` (`bmf_lg_idx`, `bmf_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='기타 입출고';

SET FOREIGN_KEY_CHECKS = 1;
