using System;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;
using FCOMMON;

namespace Project.Web
{
    public partial class MachineBridge
    {
        #region Common API

        /// <summary>
        /// 네비게이션 메뉴 조회
        /// </summary>
        public string GetNavigationMenu()
        {
            try
            {
                var menuItems = new[]
                {
                    new { key = "dashboard", title = "대시보드", url = "/DashBoard/index.html", icon = "M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2H5a2 2 0 00-2-2z M8 5a2 2 0 012-2h4a2 2 0 012 2v2H8V5z", isVisible = true, sortOrder = 1 },
                    new { key = "common", title = "공용코드", url = "/Common.html", icon = "M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z", isVisible = true, sortOrder = 2 },
                    new { key = "jobreport", title = "업무일지", url = "/Jobreport/index.html", icon = "M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2", isVisible = true, sortOrder = 3 },
                    new { key = "kuntae", title = "근태관리", url = "/Kuntae/index.html", icon = "M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z", isVisible = true, sortOrder = 4 },
                    new { key = "todo", title = "할일관리", url = "/Todo/index.html", icon = "M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2M12 12l2 2 4-4", isVisible = true, sortOrder = 5 },
                    new { key = "project", title = "프로젝트", url = "/Project/index.html", icon = "M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10", isVisible = true, sortOrder = 6 }
                };

                return JsonConvert.SerializeObject(new { Success = true, Data = menuItems, Message = "메뉴 정보를 성공적으로 가져왔습니다." });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Data = (object)null, Message = "메뉴 정보를 가져오는 중 오류가 발생했습니다: " + ex.Message });
            }
        }

        /// <summary>
        /// 공용코드 그룹 목록 조회
        /// </summary>
        public string Common_GetGroups()
        {
            try
            {
                var sql = "select code, svalue, memo from common WITH (nolock) " +
                         "where gcode = @gcode and grp = '99' " +
                         "order by code";

                var cs = Properties.Settings.Default.gwcs;
                var cn = new SqlConnection(cs);
                var cmd = new SqlCommand(sql, cn);
                cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);

                var da = new SqlDataAdapter(cmd);
                var dt = new DataTable();
                da.Fill(dt);
                da.Dispose();
                cmd.Dispose();
                cn.Dispose();

                return JsonConvert.SerializeObject(dt, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Common_GetGroups 오류: {ex.Message}");
                return "[]";
            }
        }

        /// <summary>
        /// 공용코드 목록 조회
        /// </summary>
        public string Common_GetList(string grp)
        {
            try
            {
                if (string.IsNullOrEmpty(grp)) grp = "99";

                var sql = "select * from common where gcode = @gcode and grp = @grp order by code, svalue";

                var cs = Properties.Settings.Default.gwcs;
                var cn = new SqlConnection(cs);
                var cmd = new SqlCommand(sql, cn);
                cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                cmd.Parameters.AddWithValue("@grp", grp);

                var da = new SqlDataAdapter(cmd);
                var dt = new DataTable();
                da.Fill(dt);
                da.Dispose();
                cmd.Dispose();
                cn.Dispose();

                return JsonConvert.SerializeObject(dt, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Common_GetList 오류: {ex.Message}");
                return "[]";
            }
        }

        /// <summary>
        /// 공용코드 저장
        /// </summary>
        public string Common_Save(int idx, string grp, string code, string svalue, int ivalue, float fvalue, string svalue2, string memo)
        {
            try
            {
                var cs = Properties.Settings.Default.gwcs;
                var cn = new SqlConnection(cs);
                var sql = string.Empty;
                var cmd = new SqlCommand();
                cmd.Connection = cn;

                if (idx > 0)
                {
                    // 업데이트
                    sql = @"UPDATE common SET
                            grp = @grp,
                            code = @code,
                            svalue = @svalue,
                            ivalue = @ivalue,
                            fvalue = @fvalue,
                            svalue2 = @svalue2,
                            memo = @memo,
                            wuid = @wuid,
                            wdate = GETDATE()
                            WHERE idx = @idx AND gcode = @gcode";
                }
                else
                {
                    // 신규 추가
                    sql = @"INSERT INTO common (gcode, grp, code, svalue, ivalue, fvalue, svalue2, memo, wuid, wdate)
                            VALUES (@gcode, @grp, @code, @svalue, @ivalue, @fvalue, @svalue2, @memo, @wuid, GETDATE())";
                }

                cmd.CommandText = sql;
                cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                cmd.Parameters.AddWithValue("@grp", grp ?? "");
                cmd.Parameters.AddWithValue("@code", code ?? "");
                cmd.Parameters.AddWithValue("@svalue", svalue ?? "");
                cmd.Parameters.AddWithValue("@ivalue", ivalue);
                cmd.Parameters.AddWithValue("@fvalue", fvalue);
                cmd.Parameters.AddWithValue("@svalue2", svalue2 ?? "");
                cmd.Parameters.AddWithValue("@memo", memo ?? "");
                cmd.Parameters.AddWithValue("@wuid", info.Login.no);

                if (idx > 0)
                {
                    cmd.Parameters.AddWithValue("@idx", idx);
                }

                cn.Open();
                var result = cmd.ExecuteNonQuery();
                cn.Close();

                cmd.Dispose();
                cn.Dispose();

                return JsonConvert.SerializeObject(new { Success = result > 0, Message = result > 0 ? "저장되었습니다." : "저장에 실패했습니다." });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "오류가 발생했습니다: " + ex.Message });
            }
        }

        /// <summary>
        /// 공용코드 삭제
        /// </summary>
        public string Common_Delete(int idx)
        {
            try
            {
                var cs = Properties.Settings.Default.gwcs;
                var cn = new SqlConnection(cs);
                var sql = "DELETE FROM common WHERE idx = @idx AND gcode = @gcode";
                var cmd = new SqlCommand(sql, cn);

                cmd.Parameters.AddWithValue("@idx", idx);
                cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);

                cn.Open();
                var result = cmd.ExecuteNonQuery();
                cn.Close();

                cmd.Dispose();
                cn.Dispose();

                return JsonConvert.SerializeObject(new { Success = result > 0, Message = result > 0 ? "삭제되었습니다." : "삭제에 실패했습니다." });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "오류가 발생했습니다: " + ex.Message });
            }
        }

        /// <summary>
        /// 현재 로그인 사용자 정보 조회
        /// </summary>
        public string GetCurrentUser()
        {
            try
            {
                if (string.IsNullOrEmpty(info.Login.no))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인되지 않은 상태입니다." });
                }

                return JsonConvert.SerializeObject(new
                {
                    Success = true,
                    Data = new
                    {
                        id = info.Login.no,
                        name = info.Login.nameK,
                        userName = info.Login.nameK,
                        email = info.Login.email,
                        dept = info.Login.dept,
                        gcode = info.Login.gcode
                    }
                });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 즐겨찾기 목록 조회 (grp=17)
        /// memo가 표시명, svalue가 URL
        /// </summary>
        public string Favorite_GetList()
        {
            try
            {
                var sql = "select isnull(code,'') as code, isnull(memo,'') as name, isnull(svalue,'') as url " +
                         "from common WITH (nolock) " +
                         "where gcode = @gcode and grp = '17' and isnull(code,'') <> '' " +
                         "order by code";

                var cs = Properties.Settings.Default.gwcs;
                var cn = new SqlConnection(cs);
                var cmd = new SqlCommand(sql, cn);
                cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);

                var da = new SqlDataAdapter(cmd);
                var dt = new DataTable();
                da.Fill(dt);
                da.Dispose();
                cmd.Dispose();
                cn.Dispose();

                var result = new System.Collections.Generic.List<object>();
                foreach (DataRow dr in dt.Rows)
                {
                    result.Add(new
                    {
                        name = dr["name"]?.ToString() ?? "",
                        url = dr["url"]?.ToString() ?? ""
                    });
                }

                return JsonConvert.SerializeObject(new { Success = true, Data = result });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Favorite_GetList 오류: {ex.Message}");
                return JsonConvert.SerializeObject(new { Success = false, Data = new object[] { }, Message = ex.Message });
            }
        }

        #endregion

        #region Items API

        /// <summary>
        /// 품목 카테고리 목록 조회
        /// </summary>
        public string Items_GetCategories()
        {
            try
            {
                var sql = "SELECT DISTINCT cate FROM Items WITH (NOLOCK) WHERE gcode = @gcode AND ISNULL(cate,'') <> '' ORDER BY cate";

                var cs = Properties.Settings.Default.gwcs;
                var cn = new SqlConnection(cs);
                var cmd = new SqlCommand(sql, cn);
                cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);

                var da = new SqlDataAdapter(cmd);
                var dt = new DataTable();
                da.Fill(dt);
                da.Dispose();
                cmd.Dispose();
                cn.Dispose();

                var result = new System.Collections.Generic.List<string>();
                foreach (DataRow dr in dt.Rows)
                {
                    result.Add(dr["cate"]?.ToString() ?? "");
                }

                return JsonConvert.SerializeObject(new { Success = true, Data = result });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "카테고리 조회 실패: " + ex.Message });
            }
        }

        /// <summary>
        /// 품목 목록 조회
        /// </summary>
        public string Items_GetList(string category, string searchKey)
        {
            try
            {
                var cateSearch = string.IsNullOrEmpty(category) || category == "all" ? "%" : category;
                var skey = string.IsNullOrEmpty(searchKey) || searchKey == "%" ? "%" : $"%{searchKey}%";

                var sql = @"SELECT idx, sid, cate, name, model, scale, unit, price, supply, manu, storage, disable, memo
                    FROM Items WITH (NOLOCK)
                    WHERE gcode = @gcode
                    AND ISNULL(cate,'') LIKE @cate
                    AND (ISNULL(sid,'') LIKE @search OR ISNULL(name,'') LIKE @search OR ISNULL(model,'') LIKE @search)
                    ORDER BY sid, name";

                var cs = Properties.Settings.Default.gwcs;
                var cn = new SqlConnection(cs);
                var cmd = new SqlCommand(sql, cn);
                cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                cmd.Parameters.AddWithValue("@cate", cateSearch);
                cmd.Parameters.AddWithValue("@search", skey);

                var da = new SqlDataAdapter(cmd);
                var dt = new DataTable();
                da.Fill(dt);
                da.Dispose();
                cmd.Dispose();
                cn.Dispose();

                return JsonConvert.SerializeObject(dt, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "품목 조회 실패: " + ex.Message });
            }
        }

        /// <summary>
        /// 품목 저장
        /// </summary>
        public string Items_Save(int idx, string sid, string cate, string name, string model,
            string scale, string unit, decimal price, string supply, string manu, string storage, bool disable, string memo)
        {
            try
            {
                var cs = Properties.Settings.Default.gwcs;
                var cn = new SqlConnection(cs);
                var sql = string.Empty;
                var cmd = new SqlCommand();
                cmd.Connection = cn;

                // 신규 추가 시 SID 중복 체크
                if (idx == 0 && !string.IsNullOrEmpty(sid))
                {
                    var checkSql = "SELECT COUNT(*) FROM Items WITH (NOLOCK) WHERE gcode = @gcode AND sid = @sid";
                    var checkCmd = new SqlCommand(checkSql, cn);
                    checkCmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                    checkCmd.Parameters.AddWithValue("@sid", sid);

                    cn.Open();
                    var count = (int)checkCmd.ExecuteScalar();
                    cn.Close();
                    checkCmd.Dispose();

                    if (count > 0)
                    {
                        cn.Dispose();
                        return JsonConvert.SerializeObject(new { Success = false, Message = $"이미 존재하는 SID입니다: {sid}" });
                    }
                }

                if (idx > 0)
                {
                    sql = @"UPDATE Items SET
                            sid = @sid, cate = @cate, name = @name, model = @model,
                            scale = @scale, unit = @unit, price = @price, supply = @supply,
                            manu = @manu, storage = @storage, disable = @disable, memo = @memo,
                            wuid = @wuid, wdate = GETDATE()
                            WHERE idx = @idx AND gcode = @gcode";
                }
                else
                {
                    sql = @"INSERT INTO Items (gcode, sid, cate, name, model, scale, unit, price, supply, manu, storage, disable, memo, wuid, wdate)
                            VALUES (@gcode, @sid, @cate, @name, @model, @scale, @unit, @price, @supply, @manu, @storage, @disable, @memo, @wuid, GETDATE())";
                }

                cmd.CommandText = sql;
                cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                cmd.Parameters.AddWithValue("@sid", sid ?? "");
                cmd.Parameters.AddWithValue("@cate", cate ?? "");
                cmd.Parameters.AddWithValue("@name", name ?? "");
                cmd.Parameters.AddWithValue("@model", model ?? "");
                cmd.Parameters.AddWithValue("@scale", scale ?? "");
                cmd.Parameters.AddWithValue("@unit", unit ?? "");
                cmd.Parameters.AddWithValue("@price", price);
                cmd.Parameters.AddWithValue("@supply", supply ?? "");
                cmd.Parameters.AddWithValue("@manu", manu ?? "");
                cmd.Parameters.AddWithValue("@storage", storage ?? "");
                cmd.Parameters.AddWithValue("@disable", disable);
                cmd.Parameters.AddWithValue("@memo", memo ?? "");
                cmd.Parameters.AddWithValue("@wuid", info.Login.no);

                if (idx > 0)
                {
                    cmd.Parameters.AddWithValue("@idx", idx);
                }

                cn.Open();
                var result = cmd.ExecuteNonQuery();
                cn.Close();

                cmd.Dispose();
                cn.Dispose();

                return JsonConvert.SerializeObject(new { Success = result > 0, Message = result > 0 ? "저장되었습니다." : "저장에 실패했습니다." });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "저장 실패: " + ex.Message });
            }
        }

        /// <summary>
        /// 품목 삭제
        /// </summary>
        public string Items_Delete(int idx)
        {
            try
            {
                var cs = Properties.Settings.Default.gwcs;
                var cn = new SqlConnection(cs);
                var sql = "DELETE FROM Items WHERE idx = @idx AND gcode = @gcode";
                var cmd = new SqlCommand(sql, cn);

                cmd.Parameters.AddWithValue("@idx", idx);
                cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);

                cn.Open();
                var result = cmd.ExecuteNonQuery();
                cn.Close();

                cmd.Dispose();
                cn.Dispose();

                return JsonConvert.SerializeObject(new { Success = result > 0, Message = result > 0 ? "삭제되었습니다." : "삭제에 실패했습니다." });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "삭제 실패: " + ex.Message });
            }
        }

        /// <summary>
        /// 품목 이미지 조회 (Base64 반환)
        /// </summary>
        public string Items_GetImage(int idx)
        {
            try
            {
                var cs = Properties.Settings.Default.gwcs;
                using (var cn = new SqlConnection(cs))
                using (var cmd = new SqlCommand("SELECT image FROM Items WHERE idx = @idx AND gcode = @gcode", cn))
                {
                    cmd.Parameters.AddWithValue("@idx", idx);
                    cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);

                    cn.Open();
                    var data = cmd.ExecuteScalar() as byte[];

                    if (data != null && data.Length > 0)
                    {
                        var base64 = Convert.ToBase64String(data);
                        return JsonConvert.SerializeObject(new { Success = true, Data = base64 });
                    }

                    return JsonConvert.SerializeObject(new { Success = true, Data = (string)null });
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "이미지 조회 실패: " + ex.Message });
            }
        }

        /// <summary>
        /// 품목 이미지 저장 (Base64 입력)
        /// </summary>
        public string Items_SaveImage(int idx, string base64Image)
        {
            try
            {
                byte[] imageData = null;

                if (!string.IsNullOrEmpty(base64Image))
                {
                    // data:image/png;base64, 형식 제거
                    if (base64Image.Contains(","))
                    {
                        base64Image = base64Image.Substring(base64Image.IndexOf(",") + 1);
                    }
                    imageData = Convert.FromBase64String(base64Image);

                    // 이미지 크기 조정 (640x480 제한, WinForms과 동일)
                    using (var ms = new System.IO.MemoryStream(imageData))
                    using (var img = System.Drawing.Image.FromStream(ms))
                    {
                        System.Drawing.Image resized = img;
                        bool needResize = false;

                        if (img.Width > 640)
                        {
                            var newRate = 640.0 / img.Width;
                            var newHeight = (int)(img.Height * newRate);
                            resized = new System.Drawing.Bitmap(640, newHeight);
                            using (var g = System.Drawing.Graphics.FromImage(resized))
                            {
                                g.DrawImage(img, new System.Drawing.Rectangle(0, 0, 640, newHeight));
                            }
                            needResize = true;
                        }
                        else if (img.Height > 480)
                        {
                            var newRate = 480.0 / img.Height;
                            var newWidth = (int)(img.Width * newRate);
                            resized = new System.Drawing.Bitmap(newWidth, 480);
                            using (var g = System.Drawing.Graphics.FromImage(resized))
                            {
                                g.DrawImage(img, new System.Drawing.Rectangle(0, 0, newWidth, 480));
                            }
                            needResize = true;
                        }

                        using (var outMs = new System.IO.MemoryStream())
                        {
                            resized.Save(outMs, System.Drawing.Imaging.ImageFormat.Jpeg);
                            imageData = outMs.ToArray();
                        }

                        if (needResize)
                        {
                            resized.Dispose();
                        }
                    }
                }

                var cs = Properties.Settings.Default.gwcs;
                using (var cn = new SqlConnection(cs))
                using (var cmd = new SqlCommand("UPDATE Items SET image = @image, wuid = @wuid, wdate = GETDATE() WHERE idx = @idx AND gcode = @gcode", cn))
                {
                    cmd.Parameters.AddWithValue("@idx", idx);
                    cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                    cmd.Parameters.AddWithValue("@wuid", info.Login.no);

                    if (imageData != null)
                    {
                        cmd.Parameters.Add("@image", SqlDbType.VarBinary, -1).Value = imageData;
                    }
                    else
                    {
                        cmd.Parameters.Add("@image", SqlDbType.VarBinary, -1).Value = DBNull.Value;
                    }

                    cn.Open();
                    var result = cmd.ExecuteNonQuery();

                    return JsonConvert.SerializeObject(new { Success = result > 0, Message = result > 0 ? "이미지가 저장되었습니다." : "이미지 저장에 실패했습니다." });
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "이미지 저장 실패: " + ex.Message });
            }
        }

        /// <summary>
        /// 품목 이미지 삭제
        /// </summary>
        public string Items_DeleteImage(int idx)
        {
            return Items_SaveImage(idx, null);
        }

        /// <summary>
        /// 품목의 공급처 담당자 조회
        /// </summary>
        public string Items_GetSupplierStaff(int supplyIdx)
        {
            try
            {
                if (supplyIdx <= 0)
                {
                    return JsonConvert.SerializeObject(new { Success = true, Data = new object[] { } });
                }

                var sql = @"SELECT idx, name, grade, dept, tel, email, memo
                            FROM Staff WITH (NOLOCK)
                            WHERE gcode = @gcode AND cid = @cid";

                var cs = Properties.Settings.Default.gwcs;
                using (var cn = new SqlConnection(cs))
                using (var cmd = new SqlCommand(sql, cn))
                {
                    cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);
                    cmd.Parameters.AddWithValue("@cid", supplyIdx);

                    var da = new SqlDataAdapter(cmd);
                    var dt = new DataTable();
                    da.Fill(dt);

                    var result = new System.Collections.Generic.List<object>();
                    foreach (DataRow dr in dt.Rows)
                    {
                        var name = dr["name"]?.ToString() ?? "";
                        var grade = dr["grade"]?.ToString() ?? "";
                        if (!string.IsNullOrEmpty(grade))
                        {
                            name += $"({grade})";
                        }
                        result.Add(new
                        {
                            idx = Convert.ToInt32(dr["idx"]),
                            name = name,
                            tel = dr["tel"]?.ToString() ?? "",
                            email = dr["email"]?.ToString() ?? "",
                            dept = dr["dept"]?.ToString() ?? ""
                        });
                    }

                    return JsonConvert.SerializeObject(new { Success = true, Data = result });
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "담당자 조회 실패: " + ex.Message });
            }
        }

        /// <summary>
        /// 품목의 최근 입고내역 조회 (indate 기준)
        /// </summary>
        public string Items_GetIncomingHistory(int itemIdx)
        {
            try
            {
                var sql = @"SELECT TOP 10 idx, indate, request, pumqty, pumprice, state
                            FROM Purchase WITH (NOLOCK)
                            WHERE pumidx = @pumidx
                            AND ISNULL(indate, '') <> ''
                            AND ISNULL(isdel, 0) = 0
                            ORDER BY indate DESC";

                var cs = Properties.Settings.Default.gwcs;
                using (var cn = new SqlConnection(cs))
                using (var cmd = new SqlCommand(sql, cn))
                {
                    cmd.Parameters.AddWithValue("@pumidx", itemIdx);

                    var da = new SqlDataAdapter(cmd);
                    var dt = new DataTable();
                    da.Fill(dt);

                    var result = new System.Collections.Generic.List<object>();
                    foreach (DataRow dr in dt.Rows)
                    {
                        var date = dr["indate"]?.ToString() ?? "";
                        // 년도 2자리로 표시 (2024-01-01 -> 24-01-01)
                        if (date.Length > 9) date = date.Substring(2);

                        result.Add(new
                        {
                            idx = Convert.ToInt32(dr["idx"]),
                            date = date,
                            request = dr["request"]?.ToString() ?? "",
                            qty = dr["pumqty"] == DBNull.Value ? 0 : Convert.ToInt32(dr["pumqty"]),
                            price = dr["pumprice"] == DBNull.Value ? 0m : Convert.ToDecimal(dr["pumprice"]),
                            state = dr["state"]?.ToString() ?? ""
                        });
                    }

                    return JsonConvert.SerializeObject(new { Success = true, Data = result });
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "입고내역 조회 실패: " + ex.Message });
            }
        }

        /// <summary>
        /// 품목의 발주내역 조회 (pdate 기준)
        /// </summary>
        public string Items_GetOrderHistory(int itemIdx)
        {
            try
            {
                var sql = @"SELECT TOP 10 idx, pdate, request, pumqty, pumprice, state
                            FROM Purchase WITH (NOLOCK)
                            WHERE pumidx = @pumidx
                            AND state <> 'Cancled'
                            AND ISNULL(isdel, 0) = 0
                            ORDER BY pdate DESC";

                var cs = Properties.Settings.Default.gwcs;
                using (var cn = new SqlConnection(cs))
                using (var cmd = new SqlCommand(sql, cn))
                {
                    cmd.Parameters.AddWithValue("@pumidx", itemIdx);

                    var da = new SqlDataAdapter(cmd);
                    var dt = new DataTable();
                    da.Fill(dt);

                    var result = new System.Collections.Generic.List<object>();
                    foreach (DataRow dr in dt.Rows)
                    {
                        var date = dr["pdate"]?.ToString() ?? "";
                        // 년도 2자리로 표시 (2024-01-01 -> 24-01-01)
                        if (date.Length > 9) date = date.Substring(2);

                        result.Add(new
                        {
                            idx = Convert.ToInt32(dr["idx"]),
                            date = date,
                            request = dr["request"]?.ToString() ?? "",
                            qty = dr["pumqty"] == DBNull.Value ? 0 : Convert.ToInt32(dr["pumqty"]),
                            price = dr["pumprice"] == DBNull.Value ? 0m : Convert.ToDecimal(dr["pumprice"]),
                            state = dr["state"]?.ToString() ?? ""
                        });
                    }

                    return JsonConvert.SerializeObject(new { Success = true, Data = result });
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "발주내역 조회 실패: " + ex.Message });
            }
        }

        /// <summary>
        /// 품목 상세 정보 조회 (supplyidx 포함)
        /// </summary>
        public string Items_GetDetail(int idx)
        {
            try
            {
                var sql = @"SELECT idx, sid, cate, name, model, scale, unit, price, supply, supplyidx, manu, storage, disable, memo
                            FROM Items WITH (NOLOCK)
                            WHERE idx = @idx AND gcode = @gcode";

                var cs = Properties.Settings.Default.gwcs;
                using (var cn = new SqlConnection(cs))
                using (var cmd = new SqlCommand(sql, cn))
                {
                    cmd.Parameters.AddWithValue("@idx", idx);
                    cmd.Parameters.AddWithValue("@gcode", info.Login.gcode);

                    cn.Open();
                    using (var reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            var item = new
                            {
                                idx = reader.GetInt32(reader.GetOrdinal("idx")),
                                sid = reader["sid"]?.ToString() ?? "",
                                cate = reader["cate"]?.ToString() ?? "",
                                name = reader["name"]?.ToString() ?? "",
                                model = reader["model"]?.ToString() ?? "",
                                scale = reader["scale"]?.ToString() ?? "",
                                unit = reader["unit"]?.ToString() ?? "",
                                price = reader["price"] == DBNull.Value ? 0m : Convert.ToDecimal(reader["price"]),
                                supply = reader["supply"]?.ToString() ?? "",
                                supplyidx = reader["supplyidx"] == DBNull.Value ? -1 : Convert.ToInt32(reader["supplyidx"]),
                                manu = reader["manu"]?.ToString() ?? "",
                                storage = reader["storage"]?.ToString() ?? "",
                                disable = reader["disable"] != DBNull.Value && Convert.ToBoolean(reader["disable"]),
                                memo = reader["memo"]?.ToString() ?? ""
                            };

                            return JsonConvert.SerializeObject(new { Success = true, Data = item });
                        }
                        else
                        {
                            return JsonConvert.SerializeObject(new { Success = false, Message = "품목을 찾을 수 없습니다." });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "품목 상세 조회 실패: " + ex.Message });
            }
        }

        #endregion
    }
}
