using AR;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using UniMarc.Properties;

namespace UniMarc
{
    public partial class Main : Form
    {
        Helper_DB _DB = new Helper_DB();
        IP ip = new IP();
        public string DB_User_Data;
    

        public Main()
        {
            InitializeComponent();
            this.mdiTabControl.TabPages.Clear();
            this.mdiTabControl.DrawMode = TabDrawMode.OwnerDrawFixed;
            this.mdiTabControl.DrawItem += MdiTabControl_DrawItem;
            PUB.Init();
            this.btDevDb.Visible = System.Diagnostics.Debugger.IsAttached;
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.Size = new Size(1920, 1080);
                this.WindowState = FormWindowState.Normal;
            }
        }

        public string User_Name { get; internal set; }

        private void Main_Load(object sender, EventArgs e)
        {
            this.Visible = false;   // 메인폼을 먼저 숨김


            VersionText.Text = string.Format("UniMarc Ver.{0}", ip.VersionInfo());

            using (login login = new login())
            {
                if (DialogResult.OK == login.ShowDialog(this))
                {
                    this.Visible = true;
                }
                else
                {
                    this.Close();
                }
            }

            _DB.DBcon();
            string cmd = _DB.DB_Search("User_Data", "ID", User_Name);
            DB_User_Data = _DB.DB_Send_CMD_Search(cmd);
            try
            {
                string[] result = DB_User_Data.Split('|');

                if (result[3] == null) {
                    PUB.user.UserName = "";
                    PUB.user.CompanyName = string.Empty;
                }
                else
                {
                    PUB.user.CompanyName = result[4];
                    PUB.user.UserName = result[3];
                }

                cmd = _DB.DB_Select_Search("`idx`", "Comp", "comp_name", result[4]);
                PUB.user.CompanyIdx = _DB.DB_Send_CMD_Search(cmd).Replace("|", "");

                if (PUB.user.CompanyIdx != "1")
                {
                    납품관리ToolStripMenuItem.Visible = false;
                    회계ToolStripMenuItem.Visible = false;
                }
                if (result[5] != "관리자") { 마스터ToolStripMenuItem.Visible = false; }

                lbCompanyName.Text = PUB.user.CompanyName;
                botUserLabel.Text = PUB.user.UserName;


                

                this.Text = "[ '" + PUB.user.CompanyIdx + "' : " + result[4] + " - " + result[3] + "]";

                isAccess();
                SetBtnName();
            }
            catch (Exception ex) { UTIL.MsgE(ex.ToString()); }

            UpdaterCheck();

            this.Text += $" (Build {Application.ProductVersion})";
        }
        /// <summary>
        /// factory client update checkd
        /// </summary>
        static void UpdaterCheck()
        {
            var fi = new System.IO.FileInfo("_Factory_Client.exe");
            var fio = new System.IO.FileInfo("Factory_Client.exe");
            if (fi.Exists)
            {
                if (fio.Exists == false)
                {
                    fi.CopyTo(fio.FullName);
                    fio.LastWriteTime = fi.LastWriteTime;
                    fio.LastAccessTime = fi.LastAccessTime;
                }
                else
                {
                    //check size
                    if (fi.Length != fio.Length || fi.LastWriteTime != fio.LastWriteTime)
                    {
                        fi.CopyTo(fio.FullName, true);
                        fio.LastWriteTime = fi.LastWriteTime;
                        fio.LastAccessTime = fi.LastAccessTime;
                    }
                }
                Console.WriteLine("updater patch");
            }
        }

        #region 즐겨찾기 버튼 세팅
        public void SetBtnName()
        {
            string Area =
                "`ShortCut1`, `ShortCut2`, `ShortCut3`, `ShortCut4`, `ShortCut5`, " +
                "`ShortCut6`, `ShortCut7`, `ShortCut8`, `ShortCut9`, `ShortCut10`, " +
                "`ShortCut11`, `ShortCut12`";

            string cmd = string.Format("SELECT {0} FROM `User_ShortCut` WHERE `id` = \"{1}\"", Area, User_Name);
            string res = _DB.DB_Send_CMD_Search(cmd);
            string[] ary_res = res.Split('|');

            Button[] btn = {
                ShortCut1, ShortCut2, ShortCut3, ShortCut4, ShortCut5,
                ShortCut6, ShortCut7, ShortCut8, ShortCut9, ShortCut10,
                ShortCut11, ShortCut12
            };
            for (int a = 0; a < btn.Length; a++)
            {
                if (ary_res[a] == "")
                    ary_res[a] = string.Format("미지정{0}", a + 1);

                btn[a].Text = ary_res[a];
                btn[a].BackgroundImage = SetPicture(ary_res[a]);
                btn[a].BackgroundImageLayout = ImageLayout.Stretch;

                if (!ary_res[a].Contains("미지정"))
                    btn[a].Enabled = true;
            }
        }

        private Image SetPicture(string Text)
        {
            Image[] source_Home = {
                Resources._1_2_사용자관리, Resources._1_3_납품처관리, Resources._1_4_주문처관리, Resources._1_5_도서정보관리

            };

            Image[] source_Marc = {
                Resources._3_1_1_마크작성, Resources._3_1_2_마크목록, Resources._3_1_3_소장자료검색, Resources._3_1_4_마크정리, Resources._3_1_5_복본조사, Resources._3_1_5_복본조사, Resources._3_1_6_ISBN조회,
                Resources._3_2_1_목록, Resources._3_2_2_편목,
                Resources._3_2_1_반입, Resources._3_2_2_반출,
                Resources._3_3_1_전집관리, Resources._3_3_2_저자기호,
                Resources._3_4_1_DLS조회입력, Resources._3_4_2_DLS복본조사,
                Resources._3_5_1_마크통계
            };

            string[] Home = {
                "사용자 관리", "납품 / 거래처 관리", "주문처 관리", "도서정보 관리"
            };

            string[] Marc = {
                "마크 추가", "마크 목록", "소장자료검색", "마크 정리", "복본 조사","복본 조사(New)", "ISBN 조회",
                "DVD/CD/LP 목록", "DVD/CD/LP 편목",
                "반입", "반출",
                "전집관리", "저자기호",
                "DLS 조회 입력", "DLS 복본 조사",
                "마크통계"
            };

            int count = 0;
            foreach (string BoxText in Home)
            {
                if (Text == BoxText)
                    return source_Home[count];

                count++;
            }

            count = 0;
            foreach (string BoxText in Marc)
            {
                if (Text == BoxText)
                    return source_Marc[count];

                count++;
            }
            return Resources._0_Empty;
        }

        private void Btn_ShortCut_Click(object sender, EventArgs e)
        {
            #region 변수선언
            Button btn = sender as Button;
            string btnText = btn.Text;

            string[] Div = {
                "물품등록", "목록조회", "목록집계", "주문입력", "입고작업",
                "재고입력 및 조회", "반품처리" };
            ToolStripMenuItem[] DivT = {
                목록등록, 목록조회, 목록집계, 주문입력, 입고작업,
                재고입력및조회, 반품처리
            };

            string[] Acc = {
                "송금내역조회", "송금등록", "매입 집계", "매입 장부", "매출 입력",
                "매출 입금", "매출 조회", "매출 집계", "파트타임 관리" };
            ToolStripMenuItem[] AccT = {
                송금내역조회, 송금등록, 매입집계, 매입장부, 매출입력,
                매출입금, 매출조회, 매출집계, 파트타임관리
            };
            ToolStripMenuItem[] TempAcc = {
                송금내역조회, 송금등록, 매입, 매입, 매출,
                매출, 매출, 매출, 파트타임관리
            };

            string[] Marc = {
                "마크 추가", "마크 목록", "소장자료검색", "마크 정리", "ISBN 조회",
                "DVD/CD/LP 목록", "DVD/CD/LP 편목",
                "반입", "반출", "복본 조사", "복본 조사(New)","DLS 복본 조사", "마크 수집", "전집관리",
                "검수", "저자기호", "DLS 조회 입력", "서류작성",
                "마크통계", "장비관리" };
            ToolStripMenuItem[] MarcT = {
                마크작성, 마크목록, 소장자료검색, 마크정리, iSBN조회, 목록, 편목, 마크반입,
                마크반출, 복본조사1, 복본조사2,  dLS복본조사, 마크수집, 전집관리,
                검수, 저자기호, DLS조회, 서류작성,
                마크통계, 장비관리
            };
            ToolStripMenuItem[] TempMarc = {
                마크작업, 마크작업, 마크작업, 마크작업, 마크작업, dVDCDLPToolStripMenuItem, dVDCDLPToolStripMenuItem, 반입및반출,
                반입및반출, 마크작업, DLS, 부가기능, 부가기능,
                부가기능, 부가기능, DLS, 마크기타,
                마크기타, 마크기타
            };


            string[] Home = {
                "사용자 관리", "납품 / 거래처 관리", "주문처 관리", "도서정보 관리" };
            ToolStripMenuItem[] HomeT = {
                사용자관리, 납품거래처관리, 주문처관리, 도서정보관리
            };

            string[][] MenuTotal = { Div, Acc, Marc, Home };
            ToolStripMenuItem[][] MenuTotalT = { DivT, AccT, MarcT, HomeT };
            ToolStripMenuItem[][] MenuCheckT = { DivT, TempAcc, TempMarc, HomeT };

            int[] count = { -1, -1 };
            #endregion

            for (int a = 0; a < MenuTotal.Length; a++)
            {
                bool IsText = false;
                for (int b = 0; b < MenuTotal[a].Length; b++)
                {
                    if (MenuTotal[a][b].Trim().ToLower() == btnText.Trim().ToLower())
                    {
                        IsText = true;
                        count[1] = b;
                        break;
                    }
                }
                if (IsText)
                {
                    count[0] = a;
                    break;
                }
            }

            // 지정된게 없을경우 리턴
            foreach (int a in count)
                if (a == -1)
                    return;

            // 권한설정으로 인한 리턴
            if (!MenuCheckT[count[0]][count[1]].Enabled)
            {
                UTIL.MsgE("권한이 설정되지 않았습니다!");
                return;
            }

            // 실행.
            MenuTotalT[count[0]][count[1]].PerformClick();
        }
        #endregion

        #region 권한별 잠금
        public void isAccess()
        {
            string Area =
                 "`Div_ListInput`, `Div_ListLookup`, `Div_ListTotal`, `Div_OrderInput`, `Div_Inven`,"
               + "`Div_Stock`, `Div_Return`,"

               + "`Acc_SendMoneyList`, `Acc_SendMoneyInput`, `Acc_Buy`, `Acc_Sales`, `Acc_PartTime`,"

               + "`Marc_Setup`, `Marc_Work`, `Marc_Input`, `Marc_Option`, `Marc_DLS`,"
               + " `Marc_ETC`,"

               + "`Manage_User`, `Manage_Client`, `Manage_Purchase`, `Manage_Book`";

            string cmd = string.Format("SELECT {0} FROM `User_Access` WHERE `id` = \"{1}\"", Area, User_Name);
            string res = _DB.DB_Send_CMD_Search(cmd);
            string[] ary_res = res.Split('|');

            ToolStripMenuItem[] menus =
            {
                목록등록, 목록조회, 목록집계, 주문입력, 입고작업,
                재고입력및조회, 반품처리,

                송금내역조회, 송금등록, 매입, 매출, 파트타임관리,

                마크설정, 마크작업, 반입및반출, 부가기능, DLS, 마크기타,

                사용자관리, 납품거래처관리, 주문처관리, 도서정보관리
            };

            for (int a = 0; a < ary_res.Length; a++)
            {
                if (ary_res[a] == "0")
                    menus[a].Enabled = false;
                else if (ary_res[a] == "1")
                    menus[a].Enabled = true;
            }

            ToolStripMenuItem[] Div = {
                목록등록, 목록조회, 목록집계, 주문입력, 입고작업,
                재고입력및조회, 반품처리
            };
            IsMenuAccess(Div, 납품관리ToolStripMenuItem);

            ToolStripMenuItem[] Acc = {
                송금내역조회, 송금등록, 매입, 매출, 파트타임관리
            };
            IsMenuAccess(Acc, 회계ToolStripMenuItem);

            ToolStripMenuItem[] Marc = {
                마크설정, 마크작업, 반입및반출, 부가기능, DLS, 마크기타
            };
            IsMenuAccess(Marc, 마크ToolStripMenuItem);

            ToolStripMenuItem[] Manage = {
                사용자관리, 납품거래처관리, 주문처관리, 도서정보관리
            };
            IsMenuAccess(Manage, 홈ToolStripMenuItem);
        }

        private void IsMenuAccess(ToolStripMenuItem[] Menu, ToolStripMenuItem Target)
        {
            bool IsEnabled = true;
            for (int a = 0; a < Menu.Length; a++)
            {
                if (Menu[a].Enabled)
                    IsEnabled = false;

                if (!IsEnabled)
                    break;
            }

            if (IsEnabled)
                Target.Enabled = false;

        }
        #endregion

        #region 홈 탭
        // 홈 탭 클릭이벤트
        // Fields removed due to OpenFormInTab logic

        private void 사용자정보ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // User_Infor is special (TopMost), might need check. 
            // Using OpenFormInTab for now, but keeping original behavior if needed.
            // Original: User_Infor.TopMost = true; User_Infor.Show();
            OpenFormInTab(() =>
            {
                var f = new User_Infor(this);
                f.TopMost = true;
                return f;
            });
        }
        private void 사용자관리ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Home_User_manage(this));
        }
        private void 납품거래처관리ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Transaction_manage(this));
        }
        private void 주문처관리ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Order_manage(this));
        }

        private void 비밀번호변경ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new pw_change(this));
        }

        private void 도서정보관리ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Book_infor_manage());
        }

        private void 사용대장ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new ledger_of_use(this));
        }
        #endregion

        #region 납품관리 탭
        // 납품관리 탭 클릭 이벤트
        // Fields removed due to OpenFormInTab logic

        private void 물품등록ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Commodity_registration(this));
        }

        private void 목록등록편의ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new List_Lookup(this));
        }

        private void 목록집계ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new List_aggregation(this));
        }

        private void 주문입력ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Order_input(this));
        }
        private void 매입ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Purchase(this));
        }
        private void 재고입력및조회ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Input_Lookup_Stock(this));
        }
        private void 반품처리ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Bring_Back(this));
        }
        #endregion

        #region 회계 탭
        // 회계 탭 클릭 이벤트
        // Fields removed due to OpenFormInTab logic


        private void 파트타임관리ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Part_time(this));
        }
        private void 송금등록ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Acc_remit_Reg2 had commented out MdiParent setting in original code, 
            // but assuming it should be tabbed like others.
            OpenFormInTab(() => new Remit_reg2(this));
        }
        private void 송금내역조회ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Remit_reg(this));
        }

        private void 매입장부ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Purchase_Book(this));
        }

        private void 매입집계ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Purchase_Aggregation(this));
        }

        private void 매입미결제ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Purchase_not_pay(this));
        }

        private void 매출입력ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Sales_Input(this));
        }
        private void 매출입금toolStripMenuItem1_Click_1(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Sales_In_Pay(this));
        }
        private void 매출입금ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Sales_Deposit(this));
        }

        private void 매출장부ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Sales_Lookup(this));
        }

        private void 매출미수금ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Sales_Book(this));
        }

        private void 매출입금ToolStripMenuItem_Click(object sender, EventArgs e)        // 계산서 관리
        {
            OpenFormInTab(() => new Bill_manage(this));
        }
        #endregion

        #region 설정
        // Fields removed
        // Mac_shortcut, Mac_set_Macro, Mac_nonverbal, Job_Order removed

        private void 단축키설정ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Setup_Shortcut(this));
        }
        private void 매크로문구설정ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Set_Macro(this));
        }
        private void 불용어ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Nonverbal(this));
        }

        private void 작업지시서ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Job_Order(this));
        }
        #endregion

        #region 마크 작업
        // Fields removed
        // AddMarc, Mac_List, Marc_Plan, Mac_search_Infor, Mac_check_Copy, Mac_check_ISBN removed

        private void 마크작성ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab<AddMarc>(() => new AddMarc(this));

        }
        private void 마크목록ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab<Mac_List>(() => new Mac_List(this));
        }
        private void 소장자료검색ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Search_Infor(this));
        }
        private void 마크정리ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Marc_Plan(this));
        }
        private void 복본조사ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            // Check_copy seems to be a normal windowstate form, but we convert it to tab as per request.
            OpenFormInTab(() => new Check_copy(this));
        }

        private void iSBN조회ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() =>
            {
                var f = new Check_ISBN(this);
                f.tb_list_name.Enabled = true;
                return f;
            });
        }

        #endregion

        #region DVD / CD / LP
        // Fields removed
        // cl, cll removed

        private void 편목ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new CD_LP(this));
        }

        private void 목록_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new CD_LP_List(this));
        }
        #endregion

        #region 반입 및 반출
        // Fields removed
        // Mac_Input, Mac_Output removed

        private void 반입ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Mac_Input(this));
        }
        private void 반출ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Mac_Output(this));
        }

        #endregion

        #region 부가기능

        // Fields removed
        // Mac_Collect, Mac_all_Book_Manage, Mac_Chack_Up, Mac_symbol_Add removed

        private void 마크수집ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Collect_Mac(this));
        }
        private void 전집관리ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new All_Book_manage(this));
        }
        private void 검수ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Mac_Chack_Up(this));
        }
        private void 저자기호ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // This was previously directly created and shown without checking active instance in commented out code.
            // We will assume standard tab behavior is desired.
            OpenFormInTab(() => new Symbol_Add(this));
        }


        #endregion

        #region DLS

        // Fields removed
        // DLS_school_Lookup, Mac_dLS_Copy removed

        private void dLS조회ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new DLS_Lookup(this));
        }
        private void dLS복본조사ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new DLS_Copy(this));
        }
        #endregion

        #region 기타
        // Fields removed
        // Make_Document, Mac_Stat, Mac_equip_Manage removed

        private void 서류작성ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Make_Document(this));
        }
        private void 마크통계ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Mac_Stat(this));
        }
        private void 장비관리ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Equip_manage(this));
        }

        #endregion

        #region 작업일지 탭

        //  작업일지 탭 이벤트
        //  작업일지 탭 이벤트
        // Fields removed
        // work_Log removed

        private void 작업일지ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Work_Log(this));
        }
        #endregion

        #region 편의기능 탭
        //  편의기능 탭 이벤트
        // Fields removed
        // calendar, talk, quick_Menu, board, send_Notice, sale_Sale, sale_Settlement, sale_End, sale_Member_Manage removed

        private void 캘린더ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Calendar(this));
        }
        private void 채팅ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Talk(this));
        }
        private void 퀵메뉴ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Quick_menu(this));
        }
        private void 게시판ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Board(this));
        }
        private void 공지발송ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Send_Notice(this));
        }
        private void 판매ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Sale_Sale(this));
        }
        private void 정산ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Sale_Settlement(this));
        }
        private void 판매마감ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Sale_End(this));
        }
        private void 회원관리ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Sale_Member_Manage(this));
        }

        #endregion

        #region 마스터 탭
        //  마스터 탭 이벤트
        // Fields removed
        // master_user_Manage, master_notice_Send, master_sales_Details, master_user_Account_Inquiry, master_mac_setting, master_batch_Processing removed

        private void 신규사업자등록ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (From_User_manage_List tUser_mamge = new From_User_manage_List())
            {
                tUser_mamge.ShowDialog();
            }
        }



        private void 공지발송ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Notice_Send(this));
        }
        private void 매출내역ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Sales_Details(this));
        }
        private void 이용자거래처조회ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new User_account_inquiry(this));
        }
        private void 마크설정ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Mac_Setting(this));
        }
        private void 일괄처리관리ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Batch_processing(this));
        }

        private void 복본조사2_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() =>
            {
                var f = new Check_copyWD(this);
                f.WindowState = FormWindowState.Normal;
                return f;
            });
        }

        private void btDevDb_Click(object sender, EventArgs e)
        {
            var f = new fDevDB();
            f.Show();
        }

        #endregion

        private void AddTabForm(Form form)
        {
            form.TopLevel = false;
            form.FormBorderStyle = FormBorderStyle.None;
            form.Dock = DockStyle.Fill;

            TabPage tb = new TabPage();
            tb.Name = form.GetType().Name + "_" + form.GetHashCode(); // Unique name
            tb.Text = form.Text;
            tb.Tag = form; // Store form reference
            tb.Controls.Add(form);

            mdiTabControl.TabPages.Add(tb);
            mdiTabControl.SelectedTab = tb;

            form.Show();

            // Handle Close
            form.FormClosed += (s, e) =>
            {
                mdiTabControl.TabPages.Remove(tb);
                tb.Dispose();
            };

            // Sync Text changes if necessary
            form.TextChanged += (s, e) => { tb.Text = form.Text; };
        }

        private void MdiTabControl_DrawItem(object sender, DrawItemEventArgs e)
        {
            TabControl tc = sender as TabControl;
            TabPage page = tc.TabPages[e.Index];
            Rectangle bounds = e.Bounds;

            // Determine colors
            Color backColor = (e.State == DrawItemState.Selected) ? Color.Lime : SystemColors.Control;
            Color foreColor = (e.State == DrawItemState.Selected) ? Color.Black : Color.Black;

            // Fill background
            using (SolidBrush brush = new SolidBrush(backColor))
            {
                e.Graphics.FillRectangle(brush, bounds);
            }

            // Draw text
            TextRenderer.DrawText(e.Graphics, page.Text, page.Font, bounds, foreColor, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
        }

        public T OpenFormInTab<T>(Func<T> createForm, bool allowMultiple = false) where T : Form
        {
            // Check if form is already open in tabs
            if (!allowMultiple)
            {
                foreach (TabPage tb in mdiTabControl.TabPages)
                {
                    if (tb.Tag is T)
                    {
                        mdiTabControl.SelectedTab = tb;
                        ((Form)tb.Tag).Focus();
                        return (T)tb.Tag;
                    }
                }
            }

            // Not found, create and add
            T form = createForm();
            AddTabForm(form);
            return form;
        }

        private void menu_allclose_Click(object sender, EventArgs e)
        {
            // Create a copy of the list since closing forms modifies the collection
            var tabs = mdiTabControl.TabPages.Cast<TabPage>().ToList();

            foreach (TabPage tb in tabs)
            {
                if (tb.Tag is Form form)
                {
                    form.Close();
                }
            }
        }

        private void 신규마크작성NewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab<AddMarc2>(() => new AddMarc2(this));
        }

        private void 소장자료검색NewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFormInTab(() => new Search_Infor2(this));
        }
    }
}