using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.Text.RegularExpressions;
using System.Web;

namespace WorkShop_Services
{
    public partial class Service1 : IService1
    {
        public String IInventory_GetEntry(String type, String json)
        {
            JObject json_Object = null;
            String data = "";
            String query = "";
            if (json != String.Empty)
            {
                json_Object = JObject.Parse(json);
            }

            if (type == "CO")
            {

                query = GetQuery(json_Object["type"].ToString(), json_Object);
                data = IList_GetTable(query);

            }
            return data;
        }

        public int IInventory_Delete(String type, String json)
        {
            JObject json_Object = null;
            if (json != String.Empty)
            {
                json_Object = JObject.Parse(json);
            }
            int delete = 0;

            if (type == "CO")
            {

                delete = Order_Delete(Convert.ToInt32(json_Object["entry"].ToString()), json_Object["type"].ToString(),
                json_Object["user"].ToString(), json_Object["system"].ToString());

            }
            return delete;
        }

        String GetQuery(String type, JObject json_Object)
        {
            String query = "";
            if (type == "CO Entry")
            {
                query = " Select  om.zone,om.supervisor,om.saleman,om.town,om.customer,om.remarks,om.transport,om.com,om.extfreight,om.bilty,om.posted,om.edate,od.*, cast( round(od.pcs_box*od.to_pcs*od.qty,0) as decimal(10,2)) as trade ,om.refno,isnull(od.com,0) as comrate,isnull(od.to_target,0) as totarget,om.warehouse"
                + " from OrderMaster om  inner join order_detail od on om.Entry=od.MEntry inner join product p on p.code=od.pcode Where om.estatus='CO' and  om.Entry=" + Convert.ToInt32(json_Object["Entry"].ToString()) + " order by od.id";

            }
            return query;
        }

        public int Order_Delete(int entry, String type, String UserName, String System)
        {
            int IsDelete = 0;
            String Xml = "";

            String Master = "select distinct om.* from OrderMaster om,order_detail od where om.Entry=od.Mentry and om.Entry=" + entry;
            String Child = ";Select od.* from OrderMaster om,order_detail od where om.Entry=od.Mentry and om.Entry=" + entry;
            String Insert_Log = "insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + entry + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + System + "','" + UserName + "','Delete Entry','" + Xml + "')";
            String Delete = "DELETE  FROM order_detail WHERE Mentry=" + entry + "; DELETE FROM OrderMaster where Entry=" + entry;
            SqlTransaction trans = null;
            String json = "";
            DataTable dt = new DataTable(entry.ToString());
            DataSet ds = new DataSet();

            try
            {
                using (con = new SqlConnection(cs))
                {
                    con.Open();
                    using (adp = new SqlDataAdapter(Master + Child, con))
                    {
                        cmd = new SqlCommandBuilder(adp);
                        adp.Fill(ds);
                        json = JsonConvert.SerializeObject(ds.Tables[0]);
                        var obj = new { Master = json, Child = JsonConvert.SerializeObject(ds.Tables[1]) };
                        json = JsonConvert.SerializeObject(obj);
                    }

                    trans = con.BeginTransaction();

                    using (cm = new SqlCommand("Insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + entry + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + System + "','" + UserName + "','Delete Entry','" + json + "')", con, trans))
                    {

                        cm.ExecuteNonQuery();

                    }


                    using (cm = new SqlCommand(Delete, con, trans))
                    {
                        int a = cm.ExecuteNonQuery();
                        if (a > 0)
                        {
                            trans.Commit();
                            IsDelete = entry;

                        }
                        else
                        {
                            trans.Rollback();
                            IsDelete = 0;

                        }
                    }

                }

            }
            catch (SqlException ex)
            {
                excp(ex.Message);

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
            return IsDelete;
        }

        public String IList_Supervisor(int zone, int supervisor, int saleman, int town, int customer, int transport)
        {
            String query = "";
            String json = "";
            if (zone > 0)
            {
                query = "select * from SUPERVISOR where active=1 and  City=" + zone;
                json = IList_GetTable(query);
            }
            if (supervisor > 0)
            {
                query = "select * from So where so.active=1 and SO.SUPERVISOR=" + supervisor;
                json = IList_GetTable(query);
            }
            if (saleman > 0)
            {
                query = "select distinct t.CODE as CODE,t.NAME from ac a inner join TOWN t on t.CODE=a.TOWN ";
                query += " inner join SO on so.CODE=a.SO where a.SO is not null and t.ACTIVE=1 and so.code=" + saleman + " order by t.NAME";
                json = IList_GetTable(query);
            }
            if (town > 0)
            {
                query = "select distinct a.acode,a.TITLE from ac a inner join TOWN t on t.CODE=a.TOWN  ";
                query += " inner join SO on so.CODE=a.SO where a.ACTIVE=1 and so.code=" + saleman + " and t.code=" + town + "  and a.acode not in(select SOUL from ac where SOUL is not null) order by a.title;";
                query += ";select distinct t.CODE,t.NAME from TRANSPORT t inner join TRANS_PROFILE tp on t.CODE=tp.TRANS_CODE ";
                query += " where TOWN_CODE=" + town;

                json = IList_GetDataSet(query);
            }

            if (customer > 0)
            {

                query = " select distinct isnull(ac.COM,0) as bill_com,ac.RATELIST,p.code as pcode,p.NAME,u.Code as Ucode,u.Qty,rd.Pcs,rd.rate as [PCS RATE],p.UNIT,rd.TO_RATE as[T.O],rd.TARG as[SCH QTY],rd.Discount ,RD.SCHEME,isnull(rd.com ,0) as com,isnull(to_target ,0) as to_target,u.bag,tr.RATE as freight ";
                query += "  from ac inner join RATELIST rl on rl.CODE=ac.RATELIST inner join RATEDETAIL rd on rd.RateList=rl.CODE inner join PRODUCT p on p.CODE=rd.PCODE  inner join Units u on u.Code=rd.Units  ";
                query += " left join TRANS_PROFILE tr on tr.TOWN_CODE=" + town + " and tr.TRANS_CODE=" + transport + " and tr.SIZE=u.Code where ac.acode=" + customer;

                json = IList_GetTable(query);

            }

            return json;
        }

        public String Order_Load(String type)
        {
            DataSet ds = new DataSet();
            String query = "";
            if (type == "CO" || type == "DC" || type == "SV")
            {
                String zone = " select C.CODE,C.NAME  from CITY C order by Name;";
                String supervisor = "select i.CODE,i.NAME,i.City from SUPERVISOR i  order by Name;";
                String so = "select i.CODE,i.NAME,i.SUPERVISOR from SO i  order by Name;";
                String town = "select CODE,NAME from TOWN ORDER BY NAME";
                String customers = " select i.acode,i.TITLE,i.TOWN,t.NAME,i.SO,i.RATELIST,i.Soul,i.Com from AC i,town t  where   t.CODE=i.TOWN order by TITLE;";

                String Product = " select p.CODE,p.NAME,p.UNIT,p.QTY from PRODUCT p where p.TYPE=1 order by name;";
                String units = "Select code,qty from units;";
                String transport = "select CODE,NAME from TRANSPORT ORDER BY NAME;";
                String invoice = " select distinct om.entry from OrderMaster om,order_detail od where om.Entry=od.MEntry and om.estatus='" + type + "' order by om.Entry;";
                String warehouse = " Select Code,Name from warehouse Order By Name;";
                query = zone + supervisor + so + town + customers + Product + units + transport + invoice + warehouse;
            }
            return IList_GetDataSet(query);

        }

        public String IInventory_Order_Insert(String type, String json)
        {
            JObject json_object = JObject.Parse(json);

            DataTable table = (DataTable)JsonConvert.DeserializeObject(json_object["Child"].ToString(), (typeof(DataTable)));
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int entryno = 0;
            int invno = 0;
            int acode = Convert.ToInt32(json_object["Customer"].ToString());
            String response = "";
            DataSet dt = new DataSet();

            DataTable ds = new DataTable();
            dt.Tables.Add(ds);
            SqlTransaction trans = null;
            String LastOrder = "select TOP 1 Entry+1 from Log where type='" + json_object["estatus"] + "' ORDER BY Entry DESC";
            String detail = "insert into order_detail(Mentry,pcode,bag,ucode,qty,dozen,pcs_rate,pcs_box,unit,scheme,targ,to_pcs,disc,urate,sch_pcs,total_pcs,less,com,to_target) values(@entry,@pcode,@bag,@ucode,@qty,@dozen,@prate,@pbox,@unit,@scheme,@targ,@to_pcs,@disc,@URate,@sch_pcs,@total_pcs,@less,@com,@to_target)";
            String Order1 = "insert into ordermaster(zone,supervisor,saleman,town,customer,transport,warehouse,com,amount,remarks,estatus,edate,sysdate,freight,extfreight,bilty,comamount,Posted,RefNo,entry2)  values";
            String Order2 = " (@zone,@supervisor,@so,@town,@cus,@trans,@warehouse,@com,@amt,@remarks,@estatus,@edate,@sysdate,@freight,@ext,@bilty,@comamount,@posted,@ref,@entry); SELECT SCOPE_IDENTITY() AS CODE";
            String OrderMaster = Order1 + Order2;
            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();
                    using (cm = new SqlCommand(LastOrder, con, trans))
                    {

                        invno = Convert.ToInt32(cm.ExecuteScalar());
                    }
                    using (cm = new SqlCommand("select top 1 isnull(ent_no,0)+1 from Ledger order by ent_no desc", con, trans))
                    {

                        entryno = Convert.ToInt32(cm.ExecuteScalar());
                    }
                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {


                        cm.Parameters.AddWithValue("Zone", Convert.ToInt32(json_object["Zone"]).ToString());
                        cm.Parameters.AddWithValue("Supervisor", Convert.ToInt32(json_object["Supervisor"]).ToString());
                        cm.Parameters.AddWithValue("so", Convert.ToInt32(json_object["Saleman"]).ToString());
                        cm.Parameters.AddWithValue("town", Convert.ToInt32(json_object["Town"]).ToString());
                        cm.Parameters.AddWithValue("cus", Convert.ToInt32(json_object["Customer"]).ToString());
                        cm.Parameters.AddWithValue("trans", Convert.ToInt32(json_object["Transport"]) == -1 ? (Object)DBNull.Value : Convert.ToInt32(json_object["Transport"]).ToString());
                        cm.Parameters.AddWithValue("warehouse", Convert.ToInt32(json_object["Warehouse"].ToString()));
                        cm.Parameters.AddWithValue("com", Convert.ToDecimal(json_object["com"]).ToString());
                        cm.Parameters.AddWithValue("comamount", Convert.ToDecimal(json_object["Com_Amount"]).ToString());
                        cm.Parameters.AddWithValue("freight", Convert.ToDecimal(json_object["freight"]).ToString());
                        cm.Parameters.AddWithValue("ext", Convert.ToDecimal(json_object["extfreight"]).ToString());
                        cm.Parameters.AddWithValue("bilty", json_object["Bilty"].ToString());
                        cm.Parameters.AddWithValue("amt", Convert.ToDecimal(json_object["NetAmount"]).ToString());
                        cm.Parameters.AddWithValue("remarks", json_object["Remarks"].ToString());
                        cm.Parameters.AddWithValue("estatus", json_object["Estatus"].ToString());
                        cm.Parameters.AddWithValue("edate", json_object["Edate"].ToString());
                        cm.Parameters.AddWithValue("sysdate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        cm.Parameters.AddWithValue("posted", Convert.ToInt32(json_object["Posted"]).ToString());
                        cm.Parameters.AddWithValue("ref", Convert.ToInt32(json_object["ChallanNo"]) == -1 ? (Object)DBNull.Value : Convert.ToInt32(json_object["ChallanNo"].ToString()).ToString());
                        cm.Parameters.AddWithValue("entry", entryno);
                        invno = Convert.ToInt32(cm.ExecuteScalar());

                    }
                    if (invno > 0)
                    {
                        using (cm = new SqlCommand(detail, con, trans))
                        {
                            cm.Parameters.Add("entry", SqlDbType.Int);
                            cm.Parameters.Add("pcode", SqlDbType.Int);
                            cm.Parameters.Add("bag", SqlDbType.Int);
                            cm.Parameters.Add("ucode", SqlDbType.Int);
                            cm.Parameters.Add("qty", SqlDbType.Int);
                            cm.Parameters.Add("dozen", SqlDbType.Int);
                            cm.Parameters.Add("prate", SqlDbType.Decimal);
                            cm.Parameters.Add("pbox", SqlDbType.Int);
                            cm.Parameters.Add("unit", SqlDbType.VarChar);
                            cm.Parameters.Add("scheme", SqlDbType.Int);
                            cm.Parameters.Add("targ", SqlDbType.Int);
                            cm.Parameters.Add("to_pcs", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("URate", SqlDbType.Decimal);
                            cm.Parameters.Add("sch_pcs", SqlDbType.Int);
                            cm.Parameters.Add("total_pcs", SqlDbType.Int);
                            cm.Parameters.Add("less", SqlDbType.Decimal);
                            cm.Parameters.Add("com", SqlDbType.Decimal);
                            cm.Parameters.Add("to_target", SqlDbType.Decimal);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters[0].Value = invno;
                                cm.Parameters[1].Value = Convert.ToInt32(row["pcode"]);
                                cm.Parameters[2].Value = Convert.ToInt32(row["bag"]);
                                cm.Parameters[3].Value = Convert.ToInt32(row["ucode"]);
                                cm.Parameters[4].Value = Convert.ToInt32(row["qty"]);
                                cm.Parameters[5].Value = Convert.ToInt32(row["dozen"]);
                                cm.Parameters[6].Value = Convert.ToDecimal(row["prate"]);
                                cm.Parameters[7].Value = Convert.ToInt32(row["pbox"]);
                                cm.Parameters[8].Value = (row["unit"]);
                                cm.Parameters[9].Value = Convert.ToInt32(row["scheme"]);
                                cm.Parameters[10].Value = Convert.ToInt32(row["targ"]);
                                cm.Parameters[11].Value = Convert.ToDecimal(row["to_pcs"]);
                                cm.Parameters[12].Value = Convert.ToDecimal(row["disc"]);
                                cm.Parameters[13].Value = Convert.ToDecimal(row["URate"]);
                                cm.Parameters[14].Value = Convert.ToInt32(row["sch_pcs"]);
                                cm.Parameters[15].Value = Convert.ToDecimal(row["total_pcs"]);
                                cm.Parameters[16].Value = DBNull.Value;
                                cm.Parameters[17].Value = (row["com"]);
                                cm.Parameters[18].Value = (row["to_target"]);
                                rowseffected += cm.ExecuteNonQuery();

                            }


                        }

                        if (rowseffected > 0)
                        {

                            using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invno + ",'SV','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + (json_object["s_user"]) + "','" + (json_object["l_user"]) + "','New Entry','" + json + "')", con, trans))
                            {

                                rows = cm.ExecuteNonQuery();

                            }

                            if (rows > 0)
                            {

                                trans.Commit();
                                IsInsert = invno;
                            }
                            else
                            {
                                trans.Rollback();
                                IsInsert = 0;
                            }

                        }
                        else
                        {
                            trans.Rollback();
                            IsInsert = 0;
                        }

                    }
                    else
                    {
                        trans.Rollback();
                        IsInsert = 0;

                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                response = ex.Message;
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }

            if (IsInsert > 0)
            {
                String invoice = " select distinct om.entry from OrderMaster om,order_detail od where om.Entry=od.MEntry and om.estatus='SV' order by om.Entry;";
                response = IList_GetTable(invoice);
            }
            return response;


        }

        public int IInventory_Order_Update(String type, String json)
        {
            JObject json_object = JObject.Parse(json);

            DataTable table = (DataTable)JsonConvert.DeserializeObject(json_object["Child"].ToString(), (typeof(DataTable)));
            int rowseffected = 0;
            int rows = 0;
            int entryno = 0;
            int invno = Convert.ToInt32(json_object["Entry"].ToString());
            int acode = Convert.ToInt32(json_object["Customer"].ToString());
            int response = 0;
            DataSet dt = new DataSet();
            int delete = 0;
            DataTable ds = new DataTable();
            dt.Tables.Add(ds);
            SqlTransaction trans = null;
            String detail = "insert into order_detail(Mentry,pcode,bag,ucode,qty,dozen,pcs_rate,pcs_box,unit,scheme,targ,to_pcs,disc,urate,sch_pcs,total_pcs,less,com,to_target) values(@entry,@pcode,@bag,@ucode,@qty,@dozen,@prate,@pbox,@unit,@scheme,@targ,@to_pcs,@disc,@URate,@sch_pcs,@total_pcs,@less,@com,@to_target)";
            String OrderMaster = "update OrderMaster set zone=@Zone,supervisor=@Supervisor,saleman=@so,town=@town,customer=@cus,transport=@trans,freight=@freight,extfreight=@ext" +
             ",warehouse=@warehouse,com=@com,comamount=@comamount,amount=@amt,remarks=@remarks,bilty=@bilty,edate=@edate,posted=@posted,Refno=@ref where entry=@entry and LTRIM(RTRIM(estatus))=@estatus";


            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();

                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {


                        cm.Parameters.AddWithValue("Zone", Convert.ToInt32(json_object["Zone"]).ToString());
                        cm.Parameters.AddWithValue("Supervisor", Convert.ToInt32(json_object["Supervisor"]).ToString());
                        cm.Parameters.AddWithValue("so", Convert.ToInt32(json_object["Saleman"]).ToString());
                        cm.Parameters.AddWithValue("town", Convert.ToInt32(json_object["Town"]).ToString());
                        cm.Parameters.AddWithValue("cus", Convert.ToInt32(json_object["Customer"]).ToString());
                        cm.Parameters.AddWithValue("trans", Convert.ToInt32(json_object["Transport"]) == -1 ? (Object)DBNull.Value : Convert.ToInt32(json_object["Transport"]).ToString());
                        cm.Parameters.AddWithValue("warehouse", Convert.ToInt32(json_object["Warehouse"].ToString()));
                        cm.Parameters.AddWithValue("com", Convert.ToDecimal(json_object["com"]).ToString());
                        cm.Parameters.AddWithValue("comamount", Convert.ToDecimal(json_object["Com_Amount"]).ToString());
                        cm.Parameters.AddWithValue("freight", Convert.ToDecimal(json_object["freight"]).ToString());
                        cm.Parameters.AddWithValue("ext", Convert.ToDecimal(json_object["extfreight"]).ToString());
                        cm.Parameters.AddWithValue("bilty", json_object["Bilty"].ToString());
                        cm.Parameters.AddWithValue("amt", Convert.ToDecimal(json_object["NetAmount"]).ToString());
                        cm.Parameters.AddWithValue("remarks", json_object["Remarks"].ToString());
                        cm.Parameters.AddWithValue("estatus", json_object["Estatus"].ToString().Trim());
                        cm.Parameters.AddWithValue("edate", json_object["Edate"].ToString());
                        cm.Parameters.AddWithValue("posted", Convert.ToInt32(json_object["Posted"]).ToString());
                        cm.Parameters.AddWithValue("ref", Convert.ToInt32(json_object["ChallanNo"]) == -1 ? (Object)DBNull.Value : Convert.ToInt32(json_object["ChallanNo"].ToString()).ToString());
                        cm.Parameters.AddWithValue("entry", invno);
                        entryno = cm.ExecuteNonQuery();

                    }
                    if (entryno > 0)
                    {

                        using (cm = new SqlCommand("delete from order_detail where mentry=" + invno, con, trans))
                        {
                            delete = cm.ExecuteNonQuery();
                        }

                    }

                    if (delete > 0)
                    {


                        using (cm = new SqlCommand(detail, con, trans))
                        {
                            cm.Parameters.Add("entry", SqlDbType.Int);
                            cm.Parameters.Add("pcode", SqlDbType.Int);
                            cm.Parameters.Add("bag", SqlDbType.Int);
                            cm.Parameters.Add("ucode", SqlDbType.Int);
                            cm.Parameters.Add("qty", SqlDbType.Int);
                            cm.Parameters.Add("dozen", SqlDbType.Int);
                            cm.Parameters.Add("prate", SqlDbType.Decimal);
                            cm.Parameters.Add("pbox", SqlDbType.Int);
                            cm.Parameters.Add("unit", SqlDbType.VarChar);
                            cm.Parameters.Add("scheme", SqlDbType.Int);
                            cm.Parameters.Add("targ", SqlDbType.Int);
                            cm.Parameters.Add("to_pcs", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("URate", SqlDbType.Decimal);
                            cm.Parameters.Add("sch_pcs", SqlDbType.Int);
                            cm.Parameters.Add("total_pcs", SqlDbType.Int);
                            cm.Parameters.Add("less", SqlDbType.Decimal);
                            cm.Parameters.Add("com", SqlDbType.Decimal);
                            cm.Parameters.Add("to_target", SqlDbType.Decimal);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters[0].Value = invno;
                                cm.Parameters[1].Value = Convert.ToInt32(row["pcode"]);
                                cm.Parameters[2].Value = Convert.ToInt32(row["bag"]);
                                cm.Parameters[3].Value = Convert.ToInt32(row["ucode"]);
                                cm.Parameters[4].Value = Convert.ToInt32(row["qty"]);
                                cm.Parameters[5].Value = Convert.ToInt32(row["dozen"]);
                                cm.Parameters[6].Value = Convert.ToDecimal(row["prate"]);
                                cm.Parameters[7].Value = Convert.ToInt32(row["pbox"]);
                                cm.Parameters[8].Value = (row["unit"]);
                                cm.Parameters[9].Value = Convert.ToInt32(row["scheme"]);
                                cm.Parameters[10].Value = Convert.ToInt32(row["targ"]);
                                cm.Parameters[11].Value = Convert.ToDecimal(row["to_pcs"]);
                                cm.Parameters[12].Value = Convert.ToDecimal(row["disc"]);
                                cm.Parameters[13].Value = Convert.ToDecimal(row["URate"]);
                                cm.Parameters[14].Value = Convert.ToInt32(row["sch_pcs"]);
                                cm.Parameters[15].Value = Convert.ToDecimal(row["total_pcs"]);
                                cm.Parameters[16].Value = DBNull.Value;
                                cm.Parameters[17].Value = (row["com"]);
                                cm.Parameters[18].Value = (row["to_target"]);
                                rowseffected += cm.ExecuteNonQuery();

                            }


                        }

                        if (rowseffected > 0)
                        {

                            using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invno + ",'SV','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + (json_object["s_user"]) + "','" + (json_object["l_user"]) + "','New Entry','" + json + "')", con, trans))
                            {

                                rows = cm.ExecuteNonQuery();

                            }

                            if (rows > 0)
                            {

                                trans.Commit();
                                response = invno;
                            }
                            else
                            {
                                trans.Rollback();
                                response = 0;
                            }

                        }
                        else
                        {
                            trans.Rollback();
                            response = 0;
                        }

                    }
                    else
                    {
                        trans.Rollback();
                        response = 0;

                    }
                }
            }
            catch (SqlException ex)
            {

                excp(ex.Message);
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }


            return response;


        }

        public String GetInvoice(String type, String json)
        {
            String query = "";
            String data = "";
            String table = type;
            String where = "";
            String child = "";

            JObject json_Object = null;

            if (json != String.Empty)
            {
                json_Object = JObject.Parse(json);

                String token = json_Object["token"] == null ? "" : json_Object["token"].ToString();
                if (token != "")
                {
                    if (Authorization(token) <= 0)
                    {
                        json = "In-Valid";
                        return json;
                    }
                }


                if (Convert.ToString(json_Object["type"]) != String.Empty)
                {
                    where += " and ac.iden='" + Convert.ToString(json_Object["type"]) + "' ";
                }
                if (Convert.ToString(json_Object["from"]).Trim() != String.Empty)
                {
                    where += "  and CAST(sm.date AS DATE) >= CAST( '" + Convert.ToString(json_Object["from"]) + "' AS DATE) ";

                }

                if (Convert.ToString(json_Object["to"]).Trim() != String.Empty)
                {
                    where += "  AND CAST(sm.date AS DATE) <= CAST( '" + Convert.ToString(json_Object["to"]) + "' AS DATE) ";

                }
                if (Convert.ToString(json_Object["invoice"]) != String.Empty)
                {
                    where += " and sm.invoice_no=" + Convert.ToString(json_Object["invoice"]) + " ";
                }

                if (Convert.ToString(json_Object["bookno"]) != String.Empty)
                {
                    where += " and sm.mrdminv_no='" + Convert.ToString(json_Object["bookno"]) + "' ";
                }

                if (Convert.ToString(json_Object["netamount"]) != String.Empty)
                {
                    where += " and sm.ttlamtnet=" + Convert.ToDecimal(json_Object["netamount"]) + " ";
                }

                if (Convert.ToString(json_Object["warehouse"]) != String.Empty)
                {

                    where += " and  sm.warehouse=" + Convert.ToInt32(json_Object["warehouse"].ToString()) + " ";
                }

                if (Convert.ToString(json_Object["city"]) != String.Empty)
                {
                    where += " and  ac.city_code='" + (json_Object["city"]) + "' ";
                }
                if (Convert.ToString(json_Object["account"]) != String.Empty)
                {
                    where += " and  ac.code='" + Convert.ToString(json_Object["account"]) + "' ";
                }
                if (Convert.ToString(json_Object["mode"]) != String.Empty)
                {
                    where += " and  sm.invtype='" + Convert.ToString(json_Object["mode"]) + "' ";
                }
            }

            if (type == "Sales")
            {
                table = "Sales_Master";
                child = " Sales_Detail";
            }

            if (type == "SalesReturn")
            {
                table = " Sales_Return_Master";
                child = " Sales_Return_Detail ";
            }

            if (type == "Purchase")
            {
                table = "Purchase_Master";
                child = " Purchase_Detail";
            }

            if (type == "PurchaseReturn")
            {
                table = "Purchase_Return_Master";
                child = " Purchase_Return_Detail ";
            }

            query = " Select " + json_Object["record"].ToString().Trim() + " sm.key_pk,sm.invoice_no as [Cmp-InvNo],sm.mrdminv_no as [Book-InvNo],Convert(varchar(11) ,sm.date,105) as [Inv-Date],ac.title as [Party-Name],ac.code as [Party-Code],sum(ISNULL(sd.qty,0)) as TotalItem,(ISNULL(sm.ttlamtnet,0))as [Total-Amt-Net],sm.invtype as Type,wh.name as GoDown,CONVERT(varchar(15),CAST(sm.clkdate AS TIME),100) as [ETime] from " + table + " as sm" +
                    " left join ac on ac.code=sm.acode left join warehouse wh on wh.id=sm.warehouse" +
                    " inner join " + child + " sd on sm.key_pk=sd.key_fk   where sm.key_pk is not null " + where + "" +
                    "  group by sm.key_pk,sm.invoice_no,sm.mrdminv_no ,ac.title,ac.code,sm.invtype,sm.date,ttlamtnet,wh.name,sm.clkdate order by sm.invoice_no desc";

            data = IList_GetTable(query);
            return data;
        }

        public String LoadInvoices(String json)
        {
            JObject json_Object = JObject.Parse(json);

            String data = "";
            String query = " Select code,name from City order by name;" +
                           " select  title,code,iden from ac where type='Child'  order by title;" +
                           " select id,name from warehouse order by name;" +
                           " select  idno,partno,linkno from itemlinked ;" +
                           " Select distinct key_pk,invoice_no from " + json_Object["Master"] + " Order By Key_pk desc;" +
                           " select USERS,USERS_NAME from USERS where ISACTIVE=1 ORDER BY USERS_NAME;" +
                           " select count(key_pk) from " + json_Object["Master"];



            data = IList_GetDataSet(query);
            return data;
        }

        public String LoadStockInvoices(String json)
        {
            JObject json_Object = JObject.Parse(json);

            String data = "";
            String query = " Select code,name from City order by name;" +
                           " select title,code,iden from ac where parent is null  order by title;" +
                           " select id,name from warehouse order by name;" +
                           " select idno,partno,linkno from itemlinked order by partno;" +
                          " Select distinct key_pk,invoice_no from " + json_Object["Master"] + " Order By Key_pk;";

            data = IList_GetDataSet(query);
            return data;
        }

        public String GetLinkedItem()
        {
            String data = "";
            String query = " Select code as Code,name as Name,short_code as Short_Code from maker order by Name;" +
                           " Select id,model.code as Code,model.name as Name,maker.name as Maker,isnull(maker.code,'') as maker_code,maker.short_code  from model left join maker on maker.code=model.maker order by model.name;" +
                           " Select code as Code,name as Name from brand order by Name;" +
                           " Select item.code as Code,item.name as Name,rf.name as Reference,isnull(rf.code,'') as Ref_code  from Item left join reference rf on rf.code=item.reference order by name;" +
                           " Select code as Code,name as Name from reference order by name;" +
                           " Select code as Code,name as Name,short_code as Short_Code from origin ;" +
                           " Select top 100 linkno,idno as Idno,desc1 as Description,partno as Partno,op_qty as Qty,op_cost as Cost,op_amt as Amount from itemlinked order by idno desc;" +
                           " Select id,name from warehouse order by name;" +
                           " Select code as Code,name as Name,short_code as Short_Code from units "+
                           " select name,mrk_default from units order by name;" +
                           " select profit,mrk_default from prft_per order by profit;";

            data = IList_GetDataSet(query);
            return data;
        }

        public String GetLinkedItemByRecords(String records)
        {
            String data = "";

            String query = "  select " + records.Trim() + " linkno,idno as Idno,desc1 as Description," +
                            " partno as Partno,br.name as brand,op_qty as Qty,op_cost as Cost,op_amt as Amount " +
                            " from itemlinked inner join brand br on br.code=brnad order by idno desc;";

            data = IList_GetTable(query);
            return data;
        }

        public String GeItemByCode(int idno, String token)
        {
            if (token != app_key)
            {
                return "404";
            }
            String data = "";
            String query = " Select im.*,br.name as brand, "+
                           " isnull((select top 1 dscrate from  Purchase_Detail sd  " +
                           "  where sd.acitno=im.idno and sd.key_fk=(Select max(key_fk) from Purchase_Detail where acitno=im.idno)),0) as [Pu_Rate]" +
                           
                           " from itemlinked im inner join brand br on br.code=im.brnad where im.idno=" + idno;
            data = IList_GetTable(query);
            return data;
        }

        public String GetGeneralEntries(String json)
        {
            JObject json_Object = null;
            String where = "";
            if (json != String.Empty)
            {
                json_Object = JObject.Parse(json);

                String token = json_Object["token"] == null ? "" : json_Object["token"].ToString();

                if (Authorization(token) <= 0)
                {
                    json = "In-Valid";
                    return json;
                }

                if (Convert.ToString(json_Object["from"]) != String.Empty)
                {
                    where += "  and CAST(date AS DATE) >= CAST( '" + Convert.ToString(json_Object["from"]) + "' AS DATE) ";

                }

                if (Convert.ToString(json_Object["to"]) != String.Empty)
                {
                    where += " and CAST(date AS DATE) <= CAST( '" + Convert.ToString(json_Object["to"]) + "' AS DATE) ";

                }

                if (Convert.ToString(json_Object["entry"]) != String.Empty)
                {
                    where += " and gjno=" + Convert.ToString(json_Object["entry"]);
                }

                if (Convert.ToString(json_Object["vouhcherno"]) != String.Empty)
                {
                    where += " and vchr_no like '%" + Convert.ToString(json_Object["vouhcherno"]) + "%'";
                }


                if (Convert.ToString(json_Object["debit"]) != String.Empty)
                {
                    where += " and d_acode='" + Convert.ToString(json_Object["debit"]) + "'";
                }

                if (Convert.ToString(json_Object["credit"]) != String.Empty)
                {
                    where += " and c_acode='" + Convert.ToString(json_Object["credit"]) + "'";
                }

                if (Convert.ToString(json_Object["netamount"]) != String.Empty)
                {
                    where += " and dramt=" + Convert.ToString(json_Object["netamount"]);
                }

            }

            String data = "";
            String query = " select " + json_Object["records"].ToString() + " gj.key_pk,gj.gjno,vchr_no,Convert(varchar(11) ,gj.clkdate,105) as [eDate],d_acode ,gj.dramt,c_acode,gj.prtclar from General_Journal gj " +
                           " where gj.key_pk>0 " + where +
                           "  order by key_pk desc";
            data = IList_GetTable(query);
            return data;
        }

        public String GetGeneralEntriesByCode(int key)
        {
            String data = "";
            String query = " select * from General_Journal where key_pk= " + key;

            data = IList_GetTable(query);
            return data;
        }

        public String LoadGeneral(String token)
        {

            String data = "";
            String query = "  select key_pk from General_Journal order by key_pk;";
                          
            query += " SELECT  CODE,NAME FROM Particulars Order By Name;";
            query += " select code,title from ac where type='Child' order by title;";
            data = IList_GetDataSet(query);
            return data;
        }

        public String Report_AdvancePayment(String json)
        {
            JObject json_Object = JObject.Parse(json);

            String query = "";
            String where = "  ";
            String token = json_Object["token"] == null ? "" : json_Object["token"].ToString();

            if (Authorization(token) <= 0)
            {
                json = "In-Valid";
                return json;
            }

            if (json_Object["acode"].ToString() != String.Empty)
            {
                where += " and ( d_acode='" + json_Object["acode"].ToString().Trim() + "' or c_acode='" + json_Object["acode"].ToString().Trim() + "') ";
            }

            if (json_Object["from"].ToString() != String.Empty)
            {
                where = " and  CAST(gj.clkdate AS DATE) >= CAST( '" + json_Object["from"].ToString() + "' AS DATE) ";

            }
            if (json_Object["to"].ToString() != String.Empty)
            {
                where = " and CAST(gj.clkdate AS DATE) <= CAST( '" + json_Object["to"].ToString() + "' AS DATE) ";

            }

            query = "     select gj.key_pk,gj.gjno as [Entry No],vchr_no as [Voucher No],Convert(varchar(11) ,gj.clkdate,105) as [Entry Date],debit.title as [Debit A/c name],gj.dramt as [Entry Amount],credit.title as [Credit A/c name],gj.prtclar as [Particulars] from General_Journal gj  " +
                    " inner join  ac debit on debit.code = gj.d_acode  inner join ac credit on credit.code = gj.c_acode where gj.transaction_type = 'AD' " + where + "  order by gj.clkdate " + json_Object["sort"].ToString() + "; ";




            return IList_GetTable(query);
        }

        public String LoadAging()
        {
            String data = "";
            String query = " select City.code,City.name,state.name as State,isnull(state.code,'') as [State Code] from City left join state on City.state=state.code order By name;" +
                           " select * from state order by name;" +
                           " select market.code,market.name,city.name as City,city.code as [City Code] from market left join city on city.code=market.city order by market.name;";


            data = IList_GetDataSet(query);
            return data;
        }

        public String Aging(String json)
        {
            String filter = "";
            String filter2 = "";
            String where = "";
            int index = 0;
            String query = "";
            if (json != null)
            {

                JObject json_Object = JObject.Parse(json);

                String token = json_Object["token"] == null ? "" : json_Object["token"].ToString();

                if (Authorization(token) <= 0)
                {
                    json = "In-Valid";
                    return json;
                }

                if (json_Object["iden"].ToString().Trim() != String.Empty)
                {
                    where += " and ac.iden='" + json_Object["iden"].ToString().Trim() + "' ";
                }

                if (json_Object["city"].ToString().Trim() != String.Empty)
                {
                    where += " and city.code='" + json_Object["city"].ToString().Trim() + "' ";
                }

                if (json_Object["market"].ToString().Trim() != String.Empty)
                {
                    where += " and market.code='" + json_Object["market"].ToString().Trim() + "' ";


                }
                if (json_Object["account"].ToString().Trim() != String.Empty)
                {
                    where += " and rtrim(ac.code)='" + json_Object["account"].ToString().Trim() + "' ";
                }

                index = Convert.ToInt32(json_Object["index"].ToString());
                filter = json_Object["status"].ToString();

                filter = filter == "Both" ? " and  (isnull(a.debit,0)-ISNULL(b.credit,0)!=0)" :
                filter == "Debit" ? " and (isnull(a.debit,0)-ISNULL(b.credit,0))>0 " : filter == "Credit" ? " and (isnull(a.debit,0)-ISNULL(b.credit,0))<0" : filter == "Nil" ? " and (isnull(a.debit,0)-ISNULL(b.credit,0))=0" : filter == "All" ? "" : "";

                filter2 = filter == "Both" ? " and  (isnull(dr.debit,0)-ISNULL(cr.credit,0)!=0)" :
                filter == "Debit" ? " and (isnull(dr.debit,0)-ISNULL(cr.credit,0))>0 " : filter == "Credit" ? " and (isnull(a.debit,0)-ISNULL(b.credit,0))<0" : filter == "Nil" ? " and (isnull(dr.debit,0)-ISNULL(cr.credit,0))=0" : filter == "All" ? "" : "";


            }
            if (index == 0)
            {
                query = "select ac.Code,ac.Title,city.name as City,market.name as Market " +
                        "  ,case when(isnull(a.debit,0)-ISNULL(b.credit,0))>0 then isnull(a.debit,0)-ISNULL(b.credit,0) end as Debit, " +
                        "     case when(isnull(a.debit,0)-ISNULL(b.credit,0))<0 then (isnull(a.debit,0)-ISNULL(b.credit,0))*-1 end as Credit, " +
                        "     Case when(isnull(a.debit,0)-ISNULL(b.credit,0))=0  then 'Nil' else case when(isnull(a.debit,0)-ISNULL(b.credit,0))>0 then 'DR' else 'CR' end end as type,null as DBalance,null as ODBalance,isnull(ac.person,'-') as [Deal Person] " +
                        "     from ac " +
                        "     left join (select d_acode,sum(isnull(d_amt,0)) as debit from Ledger group by d_acode)a on a.d_acode=ac.code " +
                        "     left join (select c_acode,sum(isnull(c_amt,0)) as credit from Ledger group by c_acode)b " +
                        "     on b.c_acode=ac.code left join city on city.code=ac.city_code left join market on market.code=ac.market " +
                        "     where ac.type='Child' " + where + filter + " order by ac.title";
            }
            else if (index == 1)
            {
                query = " declare @balance money;declare @city varchar(150);declare @market varchar(100)  " +
                              "  declare @ledger table(code char(34),edate datetime,city varchar(150),market varchar(150),d_amt money,id int,c_amt money) " +
                              "  declare @code char(34);declare @rows int,@count int ;set @rows=0;set @count =0; " +
                              "  declare @credit table(rowid int identity(1,1),acode Char(34),city varchar(150),market varchar(150),credit money ) " +
                              "  insert into @credit(acode,city,market,credit) " +

                              "  select  ac.code as c_code,city.name as City,market.name as Market,sum(isnull(cr.credit,0)) as  paid from  ac  " +
                              " left join city on city.code=ac.city_code left join market on market.code=ac.market   " +
                              "  inner join(select l.d_acode,sum(ISNULL(d_amt,0)) as debit from Ledger l group by l.d_acode)dr on dr.d_acode=ac.code " +
                              " inner join(select l.c_acode,sum(ISNULL(c_amt,0)) as credit from Ledger l group by l.c_acode)cr on cr.c_acode=ac.code " +
                              " where ac.type='Child' and (dr.debit-cr.credit)>0 " + where + "  group by ac.code,city.name,market.name  ;" +

                              " set @rows=@@ROWCOUNT; while(@rows<>@count) begin set @count=@count+1;" +
                              " set @balance=( select credit from @credit where rowid=@count);" +
                              " set @code=( select acode from @credit where rowid=@count);" +
                              " set @city=( select City from @credit where rowid=@count);" +
                              " set @market=( select market from @credit where rowid=@count);" +
                              " WITH cte AS ( SELECT id,edate,type,d_amt, SUM(d_amt) OVER (ORDER BY edate, id ASC) as CumQty FROM Ledger as running " +
                              " WHERe rtrim(d_acode)=@code ) insert into @ledger(code,edate,city,market,id,d_amt,c_amt)SELECT  @code,edate,@city,@market,id,d_amt," +
                              " CASE WHEN CumQty<@balance  THEN d_amt ELSE @balance -(CumQty-d_amt)END AS TakenOut " +
                              " FROM cte where d_amt!=( CASE  WHEN CumQty<@balance  THEN d_amt ELSE @balance -(CumQty-d_amt) END) end " +
                              " select ac.Code,ac.Title,l.City,l.Market,sum(case when c_amt<0 then d_amt else (d_amt-c_amt) end) as Debit, " +
                              " sum(case when DATEDIFF(day,cast(l.edate as Date), GETDATE()) BETWEEN ac.due_days AND ac.over_due_days  then ( case when c_amt<0 then d_amt else (d_amt-c_amt) end) end)  [DBalance], " +
                              " sum(case when DATEDIFF(day,cast(l.edate as Date), GETDATE())> ac.over_due_days  then ( case when c_amt<0 then d_amt else (d_amt-c_amt) end) end)  [ODBalance],null as Credit,isnull(ac.person,'-') as [Deal Person] " +
                              " from @ledger l inner join ac on ac.code=l.code " +
                              " group by ac.code,ac.title,l.city,l.market,ac.person order by ac.title";
            }

            else if (index == 2)
            {
                query = "    declare @balance money;declare @city varchar(150);declare @market varchar(100)  " +
                        "     declare @ledger table(code char(34),edate datetime,city varchar(150),market varchar(150),d_amt money,id int,c_amt money) " +
                        "     declare @code char(34);declare @rows int,@count int ;set @rows=0;set @count =0; " +
                        "     declare @credit table(rowid int identity(1,1),acode Char(34),city varchar(150),market varchar(150),credit money ) " +

                        "     insert into @credit(acode,city,market,credit) " +
                        "     select  ac.code as d_code,city.name as City,market.name as Market,sum(isnull(dr.debit,0)) as  paid from  ac " +
                        "     left join city on city.code=ac.city_code left join market on market.code=ac.market   " +
                        "     inner join(select l.d_acode,sum(ISNULL(d_amt,0)) as debit from Ledger l group by l.d_acode)dr on dr.d_acode=ac.code " +
                        "     inner join(select l.c_acode,sum(ISNULL(c_amt,0)) as credit from Ledger l group by l.c_acode)cr on cr.c_acode=ac.code " +
                        "     where ac.type='Child' and (dr.debit-cr.credit)<0 " + where + "  group by ac.code,city.name,market.name  ;" +


                        "     set @rows=@@ROWCOUNT; while(@rows<>@count) begin set @count=@count+1;" +
                        "     set @balance=( select credit from @credit where rowid=@count);" +
                        "     set @code=( select acode from @credit where rowid=@count);" +
                        "     set @city=( select City from @credit where rowid=@count);" +
                        "     set @market=( select market from @credit where rowid=@count);" +

                        "     WITH cte AS ( SELECT id,edate,type,c_amt, SUM(c_amt) OVER (ORDER BY edate, id ASC) as CumQty FROM Ledger as running " +
                        "     WHERe rtrim(c_acode)=@code ) insert into @ledger(code,edate,city,market,id,d_amt,c_amt)SELECT  @code,edate,@city,@market,id,c_amt," +
                        "     CASE WHEN CumQty<@balance  THEN c_amt ELSE @balance -(CumQty-c_amt)END AS TakenOut " +
                        "     FROM cte " +
                        "	where c_amt!=( CASE  WHEN CumQty<@balance  THEN c_amt ELSE @balance -(CumQty-c_amt) END) end " +
                        "	select ac.Code,ac.Title,l.City,l.Market,sum(case when c_amt<0 then d_amt else (d_amt-c_amt) end) as Credit, " +
                        "    sum(case when DATEDIFF(day,cast(l.edate as Date), GETDATE()) BETWEEN ac.due_days AND ac.over_due_days  then ( case when c_amt<0 then d_amt else (d_amt-c_amt) end) end)  [Balance], " +
                        "    sum(case when DATEDIFF(day,cast(l.edate as Date), GETDATE()) >ac.over_due_days   then ( case when c_amt<0 then d_amt else (d_amt-c_amt) end) end)  [ODBalance],null as Debit,isnull(ac.person,'-') as [Deal Person] " +
                        "    from @ledger l inner join ac on ac.code=l.code " +
                        "    group by ac.code,ac.title,l.city,l.market,ac.person order by ac.title";
            }
            return IList_GetTable(query);
        }

        public String WeeklySheet(String json)
        {
            JObject json_Object = JObject.Parse(json);
            DataTable table = (DataTable)JsonConvert.DeserializeObject(json_Object["ac"].ToString(), (typeof(DataTable)));
            String where = "";
            int valid = 0;
            foreach (DataRow row in table.Rows)
            {
                if (valid == 0)
                {
                    where += "  ac.code='" + row[0].ToString() + "' ";
                    valid = 1;
                }
                else
                {
                    where += " or ac.code='" + row[0].ToString() + "' ";
                }

            }
            String query = "";
            query = "declare @from char(10);declare @to char(10);set @from='" + json_Object["from"] + "';set @to='" + json_Object["to"] + "'" +
                     "  select ac.code,ac.title,isnull(op.Opening,0) as Opening,isnull(si.Sales,0) as Sales,isnull( sr.Sales_Return,0) as Sales_Return,Isnull( pu.Purchase,0) as Purchase,Isnull( pr.Purchase_Return,0) as Purchase_Return,isnull( total.other_dr,0) as other_dr,isnull(total.other_cr,0) as other_cr," +
                     "  (isnull(op.Opening,0)+isnull(si.Sales,0)-isnull(sr.Sales_Return,0)+isnull(pu.Purchase,0)-isnull(pr.Purchase_Return,0)+isnull(total.other_dr,0)-isnull(total.other_cr,0)) as Ending_bl from ac " +
                     " left join(select sm.acode,sum(sm.ttlamtnet) as Sales from Sales_Master sm where cast(clkdate as Date)>=@from and cast(clkdate as Date)<=@to group by sm.acode)si on si.acode=ac.code" +
                     " left join(select sm.acode,sum(sm.ttlamtnet) as Sales_Return from Sales_Return_Master sm where cast(clkdate as Date)>=@from and cast(clkdate as Date)<=@to group by sm.acode)sr on sr.acode=ac.code" +
                     " left join(select sm.acode,sum(sm.ttlamtnet) as Purchase from Purchase_Master sm where cast(clkdate as Date)>=@from and cast(clkdate as Date)<=@to group by sm.acode)pu on pu.acode=ac.code" +
                     " left join(select sm.acode,sum(sm.ttlamtnet) as Purchase_Return from Purchase_Return_Master sm where cast(clkdate as Date)>=@from and cast(clkdate as Date)<=@to group by sm.acode)pr on pr.acode=ac.code" +
                     " left join(select ac.code,(isnull(dr.Debit,0)-isnull(cr.Credit,0)) as Opening from ac " +
                     " left join(select d_acode,sum(ISNULL(d_amt,0)) as Debit from Ledger where cast(edate as Date)<@from group by d_acode)dr on dr.d_acode=ac.code" +
                     " left join(select c_acode,sum(ISNULL(c_amt,0)) as Credit from Ledger where cast(edate as Date)<@from  group by c_acode)cr on cr.c_acode=ac.code)op on op.code=ac.code" +
                     " left join(select ac.code,dr.Debit as other_dr,cr.Credit as other_cr from ac " +
                     " left join(select d_acode,sum(ISNULL(d_amt,0)) as Debit from Ledger " +
                     " where cast(edate as Date)>=@from and cast(edate as Date)<=@to and (type!='SI' and type!='SR' and type!='PI' and type!='PR') group by d_acode)dr on dr.d_acode=ac.code" +
                     " left join(select c_acode,sum(ISNULL(c_amt,0)) as Credit from Ledger " +
                     " where cast(edate as Date)>=@from and cast(edate as Date)<=@to and ( type!='SI' and type!='SR' and type!='PI' and type!='PR') group by c_acode)cr on cr.c_acode=ac.code)total on total.code=ac.code" +
                     " where ac.code is not null and ( " + where + " ) order by title";

            return IList_GetTable(query);
        }

        public String Transaction_Detail(String json)
        {

            JObject json_Object = JObject.Parse(json);
            DataTable table = (DataTable)JsonConvert.DeserializeObject(json_Object["ac"].ToString(), (typeof(DataTable)));
            String where1 = ""; String where2 = ""; String where3 = ""; int valid = 0;
            String from = json_Object["from"].ToString();
            String to = json_Object["to"].ToString();
            String from2 = DateTime.ParseExact(from, "yyyy-MM-dd", CultureInfo.InvariantCulture).ToString("MM-dd-yyyy");
            String to2 = DateTime.ParseExact(to, "yyyy-MM-dd", CultureInfo.InvariantCulture).ToString("MM-dd-yyyy");

            foreach (DataRow row in table.Rows)
            {
                if (valid == 0) { where2 += "  d_acode='" + row[0].ToString() + "' "; valid = 1; }
                else { where2 += " or d_acode='" + row[0].ToString() + "' "; }
            }
            valid = 0;

            foreach (DataRow row in table.Rows)
            {
                if (valid == 0) { where3 += "  c_acode='" + row[0].ToString() + "' "; valid = 1; }
                else { where3 += " or c_acode='" + row[0].ToString() + "' "; }
            }

            valid = 0;
            foreach (DataRow row in table.Rows)
            {
                if (valid == 0) { where1 += "  ac.code='" + row[0].ToString() + "' "; valid = 1; }
                else { where1 += " or ac.code='" + row[0].ToString() + "' "; }
            }
            int index = Convert.ToInt32(json_Object["index"].ToString());
            String query = "";
            if (index == 0)
            {


                query = "	 declare @from char(10);declare @to char(10);set @from='" + from + "';set @to='" + to + "'; " +
                                " declare @table table(code char(34),Title varchar(300),Period char(6)) " +
                                " declare @trans table(code char(34),sno int,Period char(6),Opening numeric(14,2),debit numeric(14,2),credit numeric(14,2)) " +

                                " insert into @table select ac.code,ac.title,nm.Name from ac,NameOfMonth('" + from2 + "','" + to2 + "') nm " +
                                " where ac.type='Child' and ( " + where1 + " ) group by ac.code,ac.title,nm.Name " +

                                " insert into @trans " +
                                " select ac.code,0 as sno,(YEAR(@from)*100 + MONTH(@from)) as D_Period,(isnull(dr.op_Debit,0)-isnull(cr.op_Credit,0)) as Opening,null as Debit,null as Credit from ac  left join(select d_acode,sum(ISNULL(d_amt,0)) as op_Debit from Ledger where cast(edate as Date)<@from group by d_acode)dr on dr.d_acode=ac.code left join(select c_acode,sum(ISNULL(c_amt,0)) as op_Credit from Ledger where cast(edate as Date)<@from  group by c_acode)cr on cr.c_acode=ac.code where  ac.type='Child' " +
                                " and(" + where1 + ") " +

                                " insert into @trans" +
                                " select l.d_acode,1 as sno,(YEAR(l.edate)*100 + MONTH(l.edate)) as D_Period,null as Op,sum(isnull(d_amt,0)) as Debit,null as Credit from ledger l where cast(edate as Date)>=@from and cast(edate as Date)<=@to " +
                                " and(" + where2 + ") group by l.d_acode,(YEAR(l.edate)*100 + MONTH(l.edate)) " +

                                " insert into @trans " +
                                " select l.c_acode,1 as sno,(YEAR(l.edate)*100 + MONTH(l.edate)) as C_Period,null as Op,null as Debit,sum(isnull(c_amt,0)) as Credit from ledger l where cast(edate as Date)>=@from and cast(edate as Date)<=@to and cast(edate as Date)<=@to  " +
                                "  and(" + where3 + ") group by l.c_acode,(YEAR(l.edate)*100 + MONTH(l.edate)) " +

                                " select t1.Title as NAME,t1.Period as Year,sno,isnull(sum(Opening),0) as Opening,isnull(sum(debit),0) as Debit,isnull(sum(credit),0) as Credit " +
                                " ,isnull(sum(debit),0)-isnull(sum(credit),0) as Diff from @table t1 left join @trans tr on tr.code=t1.code and tr.Period=t1.Period " +
                                " group by t1.title,t1.Period,sno order by t1.title,t1.Period,sno ";

            }
            else if (index == 1)
            {
                query = "declare @from char(10);declare @to char(10);set @from='" + from + "';set @to='" + to + "'; " +
                      "   declare @table table(code char(34),Title varchar(300),Period char(6)) " +
                      "   declare @trans table(code char(34),sno int,Period char(6),Opening numeric(14,2),debit numeric(14,2),credit numeric(14,2),city char(10))  " +
                      "   declare @ac table(acode char(34),city char(10)) " +

                      "   insert into @table select City.code,City.name as City,nm.Name from city,NameOfMonth('" + from2 + "','" + to2 + "') nm  " +
                      "   group by City.code,City.name,nm.Name " +

                      "   insert into @trans   " +
                      "   select ac.code,0 as sno,(YEAR(@from)*100 +MONTH(@from)) as D_Period,(isnull(dr.op_Debit,0)-isnull(cr.op_Credit,0)) as Opening,null as Debit,null as Credit,ac.city_code from ac  " +
                      "   left join(select d_acode,sum(ISNULL(d_amt,0)) as op_Debit from Ledger where cast(edate as Date)<@from group by d_acode)dr on dr.d_acode=ac.code " +
                      "   left join(select c_acode,sum(ISNULL(c_amt,0)) as op_Credit from Ledger where cast(edate as Date)<@from  group by c_acode)cr on cr.c_acode=ac.code where  ac.type='Child'  " +
                      "   and ac.city_code is not null  " +

                      "   insert into @trans " +
                      "   select l.d_acode,1 as sno,(YEAR(l.edate)*100 +MONTH(l.edate)) as D_Period,null as Op,sum(isnull(d_amt,0)) as Debit,null as Credit,ac.city_code from ledger l " +
                      "   inner join ac on ac.code=l.d_acode " +
                      "   where cast(l.edate as Date)>=@from and cast(l.edate as Date)<=@to  " +
                      "   and ac.city_code is not null group by l.d_acode,ac.city_code,(YEAR(l.edate)*100 +MONTH(l.edate))  " +

                      "   insert into @trans  " +
                      "   select l.c_acode,1 as sno,(YEAR(l.edate)*100 +MONTH(l.edate)) as C_Period,null as Op,null as Debit,sum(isnull(c_amt,0)) as Credit,ac.city_code from  ledger l " +
                      "   inner join ac on ac.code=l.c_acode " +
                      "   where cast(l.edate as Date)>=@from and cast(l.edate as Date)<=@to and cast(l.edate as Date)<=@to   " +
                      "    and ac.city_code is not null group by l.c_acode,ac.city_code,(YEAR(l.edate)*100 +MONTH(l.edate))  " +

                      "   select t1.Title as NAME,t1.Period as Year,sno,isnull(sum(Opening),0) as Opening,isnull(sum(debit),0) as Debit,isnull(sum(credit),0) as Credit  " +
                      "   ,isnull(sum(debit),0)-isnull(sum(credit),0) as Diff from @table t1 left join @trans tr on tr.city=t1.code and tr.Period=t1.Period  " +
                      "   group by tr.city,t1.Title,t1.Period,sno order by Name,t1.Period,sno ;";

            }
            return IList_GetTable(query);
        }

        public String GetLedger(String json)
        {
            String where1 = "";
            String where2 = "";
            String orderby = "";
            JObject json_Object = JObject.Parse(json);
            String token = json_Object["token"] == null ? "" : json_Object["token"].ToString();

            if (Authorization(token) <= 0)
            {
                json = "In-Valid";
                return json;
            }

            if (json_Object["sort"] != null)
            {

                orderby = json_Object["sort"].ToString();
            }
            else
            {
                orderby = "desc";
            }

            if (json_Object["from"].ToString().Trim() != String.Empty)
            {
                where1 += " where CAST(t.edate AS DATE) >= CAST( '" + json_Object["from"].ToString().Trim() + "' AS DATE)  AND CAST(t.edate AS DATE) <= CAST( '" + json_Object["to"].ToString().Trim() + "' AS DATE)";
            }

            if (json_Object["from"].ToString().Trim() != String.Empty)
            {
                where2 += " where CAST(edate AS DATE) < CAST( '" + json_Object["from"].ToString().Trim() + "' AS DATE)  ";
            }

            String query = "";

            query = " declare @code varchar(100);  declare @from char(10);declare @to char(10); " +
                    " set @code='" + json_Object["code"].ToString().Trim() + "' " +
                    " declare @table table(code char(34),id int,edate datetime,entryno int,description varchar(max),type char(3),ref int,mrd varchar(100),debit numeric (14,2),credit numeric (14,2),opposite varchar(350),pidno int) " +
                    " insert into @table select * from(  " +
                    " Select  d_acode,id,edate,entryno,description,type,ref,mrd,d_amt as debit,null as credit,(select title from ac where ac.code=c_acode) as Opposite,pidno from Ledger where (d_acode)=@code   " +
                    " union all  " +
                    " Select  c_acode,id,edate,entryno,description,type,ref,mrd,null,c_amt as credit,(select title from ac where ac.code=d_acode)as Opposite,pidno from Ledger where (c_acode)=@code   " +
                    " )a  order by a.edate " + orderby + ",a.entryno " + orderby + ",a.id asc; select * from ac where code=@code; ";

            if (json_Object["from"].ToString().Trim() != String.Empty)
            {
                query += " select * from ( " +
                             " select code,null as id,null as edate,null as entryno,'BALANCE BF' as description,null as type,null as ref,null as mrd, " +
                             " case when sum(ISNULL(debit,0))-sum(ISNULL(credit,0))>=0 then  sum(ISNULL(debit,0))-sum(ISNULL(credit,0)) else null end as debit, " +
                             " case when sum(ISNULL(debit,0))-sum(ISNULL(credit,0))<0 then ( sum(ISNULL(debit,0))-sum(ISNULL(credit,0)))*-1 else null end as credit,null as opposite,null as pidno from  @table " + where2 + " group by code   " +
                             " union all select * from @table t  " + where1 +
                             " ) a order by a.edate " + orderby + ",a.entryno " + orderby + ",a.id asc";
            }
            else
            {
                query += " Select a.*,isnull(gj.gjno,0) as insp_payment from @table a " +
                         " left join (select gjno from general_journal where insp_id is not null)gj on gj.gjno=a.ref and a.type='GJ' "+
                         " order by a.edate " + orderby + ",a.entryno " + orderby + ",a.id asc";
            }

          
            return IList_GetDataSet(query);
        }

        public String InsertVoucher(String json)
        {
            JObject json_object = JObject.Parse(json);

            int rowseffected = 0;
            int rows = 0;
            int entryno = 0;
            int invno = 0;
            int voucher_no = 0;
            String vno = "";
            String response = "";
            DataSet dt = new DataSet();

            DataTable ds = new DataTable();
            dt.Tables.Add(ds);
            SqlTransaction trans = null;
            String LastOrder = "select top 1 gjno from General_Journal order by gjno desc ";
            String Insert1 = "insert into General_Journal(entrynat,clkdate,date,gjno,vchr_no,dramt,cramt,bopr,type_no,type_dt,prtclar,d_acode,c_acode,op_type,transaction_type,tnr,insp_id,insp_inv) values";
            String Insert2 = " (@entrynat,@clkdate,@date,@gjno,@vchr_no,@dramt,@cramt,@bopr,@type_no,@type_dt,@prtclar,@d_acode,@c_acode,@op_type,@t_type,@narration,@insp_id,@insp_inv); SELECT SCOPE_IDENTITY() AS CODE";
            String OrderMaster = Insert1 + Insert2;
            String LastVoucher = " select top 1 vchr_no from General_Journal order by key_pk desc ";
            String Ledger1 = " Insert Into Ledger(edate,description,details,type,ref,mrd,d_acode,d_amt,c_acode,c_amt,pidno,posted)" +
                             " values(@edate,@desc,@details,@type,@ref,@mrd,@d_acode,@d_amt,@c_acode,@c_amt,@pidno,@posted) ; SELECT SCOPE_IDENTITY() AS CODE";
            String query_valid = "select id from cash_book where cast(edate as date)='"+ json_object["edate"].ToString() + "'";
            int isvalid = IList_ExecuteScalerValue(query_valid);
            if (isvalid>0)
            {
                return "-2";
            }
            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();
                    using (cm = new SqlCommand(LastOrder, con, trans))
                    {

                        invno = Convert.ToInt32(cm.ExecuteScalar()) + 1;
                    }
                    using (cm = new SqlCommand(LastVoucher, con, trans))
                    {

                        vno = Convert.ToString((cm.ExecuteScalar()));
                    }
                    if (vno != String.Empty)
                    {
                        voucher_no = Convert.ToInt16(Regex.Replace(vno, "[A-Za-z ]", "")) + 1;
                    }

                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {

                        cm.Parameters.AddWithValue("entrynat", "DG");
                        cm.Parameters.AddWithValue("clkdate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("date", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("gjno", invno);
                        cm.Parameters.AddWithValue("vchr_no", "VN " + voucher_no);
                        cm.Parameters.AddWithValue("dramt", Convert.ToDecimal(json_object["amount"].ToString()).ToString());
                        cm.Parameters.AddWithValue("cramt", Convert.ToDecimal(json_object["amount"].ToString()).ToString());
                        cm.Parameters.AddWithValue("bopr", (json_object["bopr"]).ToString());
                        cm.Parameters.AddWithValue("type_no", (json_object["chq_no"]).ToString());
                        cm.Parameters.AddWithValue("type_dt", (json_object["chq_date"]).ToString().Trim() == String.Empty ? (Object)DBNull.Value : (json_object["chq_date"]).ToString().Trim());
                        cm.Parameters.AddWithValue("prtclar", (json_object["particular"]).ToString());
                        cm.Parameters.AddWithValue("narration", (json_object["narration"]).ToString());
                        cm.Parameters.AddWithValue("d_acode", (json_object["debit"]).ToString());
                        cm.Parameters.AddWithValue("c_acode", (json_object["credit"]).ToString());
                        cm.Parameters.AddWithValue("op_type", json_object["e_type"].ToString());
                        cm.Parameters.AddWithValue("t_type", json_object["t_type"].ToString());
                        cm.Parameters.AddWithValue("insp_id", json_object["insp_id"].ToString().Trim()==""?(Object)DBNull.Value: json_object["insp_id"].ToString().Trim());
                        cm.Parameters.AddWithValue("insp_inv", json_object["insp_inv_id"].ToString().Trim() == "" ? (Object)DBNull.Value : json_object["insp_inv_id"].ToString().Trim());
                        entryno = Convert.ToInt32(cm.ExecuteScalar());

                    }
                    if (entryno > 0)
                    {

                        using (cm = new SqlCommand(Ledger1, con, trans))
                        {

                            cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                            cm.Parameters.AddWithValue("desc", json_object["particular"].ToString());
                            cm.Parameters.AddWithValue("details", json_object["particular"].ToString());
                            cm.Parameters.AddWithValue("type", "GJ");
                            cm.Parameters.AddWithValue("ref", invno);
                            cm.Parameters.AddWithValue("mrd", json_object["voucherno"].ToString());
                            cm.Parameters.AddWithValue("d_acode", (json_object["debit"]).ToString());
                            cm.Parameters.AddWithValue("c_acode", (json_object["credit"]).ToString());
                            cm.Parameters.AddWithValue("d_amt", Convert.ToDecimal(json_object["amount"].ToString()).ToString());
                            cm.Parameters.AddWithValue("c_amt", Convert.ToDecimal(json_object["amount"].ToString()).ToString());
                            cm.Parameters.AddWithValue("pidno", entryno);
                            cm.Parameters.AddWithValue("posted", json_object["posted"].ToString());


                            rowseffected = Convert.ToInt32(cm.ExecuteScalar());


                        }
                        if (rowseffected > 0)
                        {

                            DataTable db = new DataTable();
                            db.TableName = "Master";
                            using (adp = new SqlDataAdapter("Select * from General_Journal where key_pk=" + entryno, con))
                            {
                                adp.SelectCommand.Transaction = trans;
                                cmd = new SqlCommandBuilder(adp);
                                adp.Fill(db);

                            }

                            String JSONString = JsonConvert.SerializeObject(db);
                            using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invno + ",'GJ','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + (json_object["system"]) + "','" + (json_object["user"]) + "','New Entry','" + JSONString + "')", con, trans))
                            {

                                rows = cm.ExecuteNonQuery();

                            }

                            if (rows > 0)
                            {

                                trans.Commit();
                                response = invno.ToString();
                            }
                            else
                            {
                                trans.Rollback();
                                response = "0";
                            }

                        }
                        else
                        {
                            trans.Rollback();
                            response = "0";
                        }



                    }
                    else
                    {
                        trans.Rollback();
                        response = "0";

                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                response = ex.Message;
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }

            /*  if (IsInsert > 0)
              {
                  String invoice = " select distinct om.entry from OrderMaster om,order_detail od where om.Entry=od.MEntry and om.estatus='SV' order by om.Entry;";
                  response = IList_GetTable(invoice);
              }*/
            return response;
        }

        public String UpdateVoucher(String json)
        {
            JObject json_object = JObject.Parse(json);

            int rowseffected = 0;
            int rows = 0;
            int entryno = Convert.ToInt32(json_object["id"].ToString());
            String response = "";
            DataSet dt = new DataSet();
            int invno = Convert.ToInt32(json_object["invno"].ToString());
            DataTable ds = new DataTable();
            dt.Tables.Add(ds);
            SqlTransaction trans = null;

            String OrderMaster = "  Update General_Journal set clkdate=@clkdate,date=@edate,vchr_no=@vchr_no,dramt=@dramt,cramt=@cramt,bopr=@bopr" +
                                 "  ,type_no=@type_no,type_dt=@type_dt,prtclar=@prtclar,d_acode=@d_acode,c_acode=@c_acode,tnr=@narration,transaction_type=@t_type, " +
                                 " op_type=@op_type,insp_id=@insp_id,insp_inv=@insp_inv "  +
                                 "  where key_pk=@idno";


            String Ledger1 = "  Update  Ledger set edate=@edate,description=@desc,details=@details,mrd=@mrd,d_acode=@d_acode,d_amt=@d_amt,c_acode=@c_acode,c_amt=@c_amt,posted=@posted " +
                                "  where type='GJ' and pidno=@idno";

            
            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();

                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {


                        cm.Parameters.AddWithValue("clkdate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("vchr_no", (json_object["voucherno"]).ToString());
                        cm.Parameters.AddWithValue("dramt", Convert.ToDecimal(json_object["amount"].ToString()).ToString());
                        cm.Parameters.AddWithValue("cramt", Convert.ToDecimal(json_object["amount"].ToString()).ToString());
                        cm.Parameters.AddWithValue("bopr", (json_object["bopr"]).ToString());
                        cm.Parameters.AddWithValue("type_no", (json_object["chq_no"]).ToString());
                        cm.Parameters.AddWithValue("type_dt", (json_object["chq_date"]).ToString().Trim() == String.Empty ? (Object)DBNull.Value : (json_object["chq_date"]).ToString().Trim());
                        cm.Parameters.AddWithValue("prtclar", (json_object["particular"]).ToString());
                        cm.Parameters.AddWithValue("t_type", json_object["t_type"].ToString());
                        cm.Parameters.AddWithValue("narration", (json_object["narration"]).ToString());
                        cm.Parameters.AddWithValue("d_acode", (json_object["debit"]).ToString());
                        cm.Parameters.AddWithValue("c_acode", (json_object["credit"]).ToString());
                        cm.Parameters.AddWithValue("idno", entryno);
                        cm.Parameters.AddWithValue("op_type", json_object["e_type"].ToString());
                        cm.Parameters.AddWithValue("insp_id", json_object["insp_id"].ToString().Trim() == "" ? (Object)DBNull.Value : json_object["insp_id"].ToString().Trim());
                        cm.Parameters.AddWithValue("insp_inv", json_object["insp_inv_id"].ToString().Trim() == "" ? (Object)DBNull.Value : json_object["insp_inv_id"].ToString().Trim());

                        rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());

                    }
                    if (rowseffected > 0)
                    {
                        rowseffected = 0;
                        using (cm = new SqlCommand(Ledger1, con, trans))
                        {

                            cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                            cm.Parameters.AddWithValue("desc", json_object["particular"].ToString());
                            cm.Parameters.AddWithValue("details", json_object["particular"].ToString());
                            cm.Parameters.AddWithValue("mrd", json_object["voucherno"].ToString());
                            cm.Parameters.AddWithValue("d_acode", (json_object["debit"]).ToString());
                            cm.Parameters.AddWithValue("c_acode", (json_object["credit"]).ToString());
                            cm.Parameters.AddWithValue("d_amt", Convert.ToDecimal(json_object["amount"].ToString()).ToString());
                            cm.Parameters.AddWithValue("c_amt", Convert.ToDecimal(json_object["amount"].ToString()).ToString());
                            cm.Parameters.AddWithValue("idno", json_object["id"].ToString());
                            cm.Parameters.AddWithValue("posted", json_object["posted"].ToString());
                            rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());

                        }
                        if (rowseffected > 0)
                        {

                            DataTable db = new DataTable();
                            db.TableName = "Master";
                            using (adp = new SqlDataAdapter("Select * from General_Journal where key_pk=" + entryno, con))
                            {
                                adp.SelectCommand.Transaction = trans;
                                cmd = new SqlCommandBuilder(adp);
                                adp.Fill(db);

                            }

                            String JSONString = JsonConvert.SerializeObject(db);
                            using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invno + ",'GJ','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + (json_object["system"]) + "','" + (json_object["user"]) + "','Modifed Entry','" + json + "')", con, trans))
                            {

                                rows = cm.ExecuteNonQuery();

                            }

                            if (rows > 0)
                            {

                                trans.Commit();
                                response = entryno.ToString();
                            }
                            else
                            {
                                trans.Rollback();
                                response = "0";
                            }

                        }
                        else
                        {
                            trans.Rollback();
                            response = "0";
                        }



                    }
                    else
                    {
                        trans.Rollback();
                        response = "0";

                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                response = ex.Message;
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }

            /*  if (IsInsert > 0)
              {
                  String invoice = " select distinct om.entry from OrderMaster om,order_detail od where om.Entry=od.MEntry and om.estatus='SV' order by om.Entry;";
                  response = IList_GetTable(invoice);
              }*/
            return response;
        }

        public String InvoiceReload(String type)
        {
            String query = "";
            if (type == "SI")
            {

                query = "select distinct key_pk,invoice_no from Sales_Master order by invoice_no";
            }
            else if (type == "SR")
            {

                query = "select distinct key_pk,invoice_no from Sales_Return_Master order by invoice_no";
            }
            else if (type == "PI")
            {

                query = "select distinct key_pk,invoice_no from Purchase_Master order by invoice_no";
            }
            else if (type == "PR")
            {

                query = "select distinct key_pk,invoice_no from Purchase_Return_Master order by invoice_no";

            }
            else if (type == "PO")
            {

                query = "select distinct key_pk,invoice_no from Purchase_Order order by invoice_no";
            }
            else if (type == "SO")
            {

                query = "select distinct key_pk,invoice_no from Order_Master order by invoice_no";
            }
            else if (type == "QO")
            {

                query = "select distinct key_pk,invoice_no from Quotation_Master order by invoice_no";
            }

            return IList_GetDataSet(query);
        }

        public String filter_product(String where)
        {

            String query = "select top 1  iteml.idno as [Itemno],iteml.partno as Partno,brand.name as Brand,iteml.desc1 as Description,iteml.model_cr as Models,iteml.vcode as [VendorCode],item.code as Part," +
                           " maker.code as Maker,brand.code as Brand,origin.code as Origin,iteml.linkno as [LinkNo] from itemlinked iteml  " +
                           " left join origin on origin.code=iteml.origin " +
                           " left join brand on brand.code=iteml.brnad " +
                           " left join item on item.code=iteml.partno " +
                           " left join model on model.id=iteml.model_maker " +
                           " left join maker on maker.code=model.maker;";

            query += " Select code as Code,name as Name,short_code as Short_Code from maker order by Name;" +
                     "  select code as Code,name as Name from brand order by Name;" +
                     "  Select item.code as Code,item.name as Name  from Item  order by name;" +
                     " Select code as Code,name as Name,short_code as Short_Code from origin ;" +
                     " select Code,Name from reference;" +
                     " Select * from Model;";




            return IList_GetDataSet(query);

        }

        public String Invoice_Insert(String json)
        {

            JObject json_object = JObject.Parse(json);

            String token = json_object["token"].ToString();
            if (token != app_key)
            {
                json = "In-Valid";
                return json;
            }

            String child = json_object["Child"].ToString();
            DataTable table = (DataTable)JsonConvert.DeserializeObject(child, (typeof(DataTable)));
            DataTable table_ledger = (DataTable)JsonConvert.DeserializeObject(json_object["Ledger"].ToString(), (typeof(DataTable)));
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            String type = json_object["Type"].ToString();
            String date = json_object["edate"].ToString();
            String UserId = json_object["UserId"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int invno = 0;
            int key = 0;
            int entryno = 0;
            String response = "";

            DataSet dt = new DataSet();

            SqlTransaction trans = null;

            String detail = " insert into " + json_object["Detail"] + "(key_fk,citmno,acitno,prtno,bn,invdesc,subdesc,qty,rate,amt,dscrate,dscr_p,disc,ntamt) values "
                             + " (@key,@sno,@item,@partno,@brand,@desc,@sub,@qty,@rate,@amt,@disc_rate,@disc_p,@disc,@amount)";

            String stock = "insert into stock(pidno,cidno,edate,refno,estatus,product,description,subdesc,rec,loose_rec,iss,loose_iss,rate,gross_amount,disc_rate,disc_p,disc,net_amount,acode,inv_disc) " +
                           "  values (@key,(select SCOPE_IDENTITY()),@edate,@refno,@type,@item,@desc,@sub,@rec,@loose_rec,@iss,@loose_iss,@rate,@amt,@disc_rate,@disc_p,@disc,@amount,@acode,@inv_disc)";

            String Order1 = " insert into " + json_object["Master"] + "(key_pk,usrno__,invtype,clkdate,date,invoice_no,mrdminv_no,acode,c_code,duedate,days,prtclar,amtgrs,disc,dscr_p,expmnininv,courier,amtnet,gstp,gsta,amtnetwgst,itp,ita,na_w_itax,ttlamtnet,citmno,closed,users,collection,balance) values ";
            String Order2 = " (@key_pk,@userno,@invtype,@edate,@date,@invoice,@vno,@debit,@credit,@duedate,@days,@remarks,@gross,@disc,@dscr_p,@expense,@courier,@net,@gstp,@gsta,@gst_amt,@itp,@itpa,@itp_amt,@total,@qty,@closed,@users,@collection,@balance); ";
            String OrderMaster = Order1 + Order2;

            String ledger = " insert into ledger(edate,description,details,type,ref,mrd,d_acode,d_amt,c_acode,c_amt,pidno,per,posted,entryno) " +
                            " values(@edate,@desc,@det,@type,@ref,@mrd,@d_acode,@d_amt,@c_acode,@c_amt,@pidno,@per,@posted,@entryno);";

            String Select_Master = "select distinct  sm.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=";

            String Select_Child = "select distinct  sd.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=";

            String remarks = json_object["remarks"].ToString().Trim();
            try
            {
                if (type == "SI")
                {
                    DataTable dm = getBalance(json_object["debit"].ToString());
                    if (dm.Rows.Count > 0)
                    {

                        decimal limit = Convert.ToDecimal(dm.Rows[0]["d_limit"]);
                        decimal balance = Convert.ToDecimal(dm.Rows[0]["balance"]) + Convert.ToDecimal(json_object["total"].ToString());

                        if (balance > limit)
                        {
                            return "402";
                        }
                    }
                }

                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();

                    using (cm = new SqlCommand("select top 1 isnull(entryno,0)+1 from Ledger order by entryno desc;", con, trans))
                    {

                        entryno = Convert.ToInt32(cm.ExecuteScalar());
                    }

                    using (cm = new SqlCommand(" select top 1 invoice_no from " + json_object["Master"] + " order by invoice_no desc;", con, trans))
                    {

                        invno = Convert.ToInt32(cm.ExecuteScalar()) + 1;
                    }

                    using (cm = new SqlCommand(" select top 1 key_pk from " + json_object["Master"] + " order by key_pk desc;", con, trans))
                    {

                        key = Convert.ToInt32(cm.ExecuteScalar()) + 1;
                    }

                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {

                        cm.Parameters.AddWithValue("key_pk", key);
                        cm.Parameters.AddWithValue("userno", json_object["UserId"].ToString());
                        cm.Parameters.AddWithValue("invtype", json_object["invtype"].ToString());
                        cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("date", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("invoice", invno);
                        cm.Parameters.AddWithValue("vno", json_object["vno"].ToString());
                        cm.Parameters.AddWithValue("debit", json_object["debit"].ToString());
                        cm.Parameters.AddWithValue("credit", json_object["credit"].ToString());
                        cm.Parameters.AddWithValue("duedate", json_object["days"].ToString() == String.Empty ? (Object)DBNull.Value : json_object["duedate"].ToString());
                        cm.Parameters.AddWithValue("days", json_object["days"].ToString() == String.Empty ? (Object)DBNull.Value : Convert.ToInt32(json_object["days"].ToString()));
                        cm.Parameters.AddWithValue("remarks", json_object["remarks"].ToString());

                        cm.Parameters.AddWithValue("gross", json_object["gross"].ToString());
                        cm.Parameters.AddWithValue("disc", json_object["disc_amt"].ToString());
                        cm.Parameters.AddWithValue("dscr_p", Convert.ToDecimal(json_object["disc_per"].ToString()));
                        cm.Parameters.AddWithValue("expense", json_object["freight"].ToString());
                        cm.Parameters.AddWithValue("courier", json_object["courier"].ToString());
                        cm.Parameters.AddWithValue("net", json_object["net_amt"].ToString());
                        cm.Parameters.AddWithValue("gstp", json_object["gst_per"].ToString());
                        cm.Parameters.AddWithValue("gsta", json_object["gst_val"].ToString());
                        cm.Parameters.AddWithValue("gst_amt", json_object["gstnet"].ToString());
                        cm.Parameters.AddWithValue("itp", json_object["it_per"].ToString());
                        cm.Parameters.AddWithValue("itpa", json_object["it_val"].ToString());
                        cm.Parameters.AddWithValue("itp_amt", json_object["itnet"].ToString());
                        cm.Parameters.AddWithValue("total", json_object["total"].ToString());
                        cm.Parameters.AddWithValue("qty", json_object["qty"].ToString());
                        cm.Parameters.AddWithValue("closed", (json_object["closed"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["closed"].ToString())));
                        cm.Parameters.AddWithValue("users", (json_object["UserId"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["UserId"].ToString())));
                        cm.Parameters.AddWithValue("collection", (json_object["collection"] == null ? (Object)DBNull.Value : Convert.ToDecimal(json_object["collection"].ToString())));
                        cm.Parameters.AddWithValue("balance", (json_object["balance"] == null ? (Object)DBNull.Value : Convert.ToDecimal(json_object["balance"].ToString())));

                        rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());

                    }
                    if (rowseffected > 0)
                    {

                        using (cm = new SqlCommand(detail + ";" + stock, con, trans))
                        {
                            cm.Parameters.Add("key", SqlDbType.Int);
                            cm.Parameters.Add("sno", SqlDbType.Int);
                            cm.Parameters.Add("item", SqlDbType.Int);
                            cm.Parameters.Add("partno", SqlDbType.VarChar);
                            cm.Parameters.Add("brand", SqlDbType.VarChar);
                            cm.Parameters.Add("desc", SqlDbType.VarChar);
                            cm.Parameters.Add("sub", SqlDbType.VarChar);
                            cm.Parameters.Add("qty", SqlDbType.Decimal);
                            cm.Parameters.Add("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amt", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_p", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("amount", SqlDbType.Decimal);

                            cm.Parameters.Add("edate", SqlDbType.DateTime);
                            cm.Parameters.Add("refno", SqlDbType.Int);
                            cm.Parameters.Add("type", SqlDbType.VarChar);
                            cm.Parameters.Add("rec", SqlDbType.Decimal);
                            cm.Parameters.Add("loose_rec", SqlDbType.Decimal);
                            cm.Parameters.Add("iss", SqlDbType.Decimal);
                            cm.Parameters.Add("loose_iss", SqlDbType.Decimal);
                            cm.Parameters.Add("acode", SqlDbType.VarChar);
                            cm.Parameters.Add("inv_disc", SqlDbType.Decimal);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["sno"].Value = Convert.ToInt32(row["sno"]);
                                cm.Parameters["item"].Value = Convert.ToInt32(row["item"]);
                                cm.Parameters["partno"].Value = Convert.ToString(row["partno"]);
                                cm.Parameters["brand"].Value = Convert.ToString(row["brand"]);
                                cm.Parameters["desc"].Value = Convert.ToString(row["desc"]);
                                cm.Parameters["sub"].Value = Convert.ToString(row["sub"]);
                                cm.Parameters["qty"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["rate"].Value = Convert.ToDecimal(row["rate"]);
                                cm.Parameters["amt"].Value = Convert.ToDecimal(row["amount"]);
                                cm.Parameters["disc_rate"].Value = Convert.ToDecimal(row["disc_rate"]);
                                cm.Parameters["disc_p"].Value = Convert.ToDecimal(row["disc_per"]);
                                cm.Parameters["disc"].Value = Convert.ToDecimal(row["disc_amt"]);
                                cm.Parameters["amount"].Value = Convert.ToDecimal(row["net_amt"]);

                                cm.Parameters["edate"].Value = date;
                                cm.Parameters["refno"].Value = invno;
                                cm.Parameters["type"].Value = type;
                                cm.Parameters["rec"].Value = Convert.ToDecimal(row["rec"]);
                                cm.Parameters["loose_rec"].Value = Convert.ToDecimal(row["loose_rec"]);
                                cm.Parameters["iss"].Value = Convert.ToDecimal(row["iss"]);
                                cm.Parameters["loose_iss"].Value = Convert.ToDecimal(row["loose_iss"]);
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"]);
                                cm.Parameters["inv_disc"].Value = Convert.ToDecimal(json_object["disc_per"].ToString());

                                rowseffected += cm.ExecuteNonQuery();

                            }
                        }

                        if (rowseffected > 0)
                        {
                            using (cm = new SqlCommand(ledger, con, trans))
                            {
                                cm.Parameters.Add("edate", SqlDbType.DateTime);
                                cm.Parameters.Add("desc", SqlDbType.VarChar);
                                cm.Parameters.Add("det", SqlDbType.VarChar);
                                cm.Parameters.Add("type", SqlDbType.VarChar);
                                cm.Parameters.Add("ref", SqlDbType.VarChar);
                                cm.Parameters.Add("mrd", SqlDbType.VarChar);
                                cm.Parameters.Add("d_acode", SqlDbType.VarChar);
                                cm.Parameters.Add("d_amt", SqlDbType.Decimal);
                                cm.Parameters.Add("c_acode", SqlDbType.VarChar);
                                cm.Parameters.Add("c_amt", SqlDbType.Decimal);
                                cm.Parameters.Add("pidno", SqlDbType.Int);
                                cm.Parameters.Add("per", SqlDbType.VarChar);
                                cm.Parameters.Add("posted", SqlDbType.Int);
                                cm.Parameters.Add("entryno", SqlDbType.Int);

                                foreach (DataRow row in table_ledger.Rows)
                                {

                                    cm.Parameters["edate"].Value = row["edate"];
                                    cm.Parameters["desc"].Value = row["description"] + (remarks == "" ? "" : "(" + remarks + ")");
                                    cm.Parameters["det"].Value = row["details"] + (remarks == "" ? "" : "(" + remarks + ")");
                                    cm.Parameters["type"].Value = row["type"];
                                    cm.Parameters["ref"].Value = invno;
                                    cm.Parameters["mrd"].Value = row["mrd"];
                                    cm.Parameters["d_acode"].Value = row["d_acode"].ToString().Trim();
                                    cm.Parameters["d_amt"].Value = Convert.ToDecimal(row["d_amt"]);
                                    cm.Parameters["c_acode"].Value = row["c_acode"].ToString().Trim();
                                    cm.Parameters["c_amt"].Value = Convert.ToDecimal(row["c_amt"]);
                                    cm.Parameters["pidno"].Value = key;
                                    cm.Parameters["per"].Value = (row["per"]);
                                    cm.Parameters["posted"].Value = (row["posted"]);
                                    cm.Parameters["entryno"].Value = entryno;

                                    rowseffected += cm.ExecuteNonQuery();

                                }


                            }

                            if (rowseffected > 0)
                            {
                                {
                                    Select_Master += invno;
                                    Select_Child += invno;


                                    using (adp = new SqlDataAdapter(Select_Master + ";" + Select_Child, con))
                                    {
                                        adp.SelectCommand.Transaction = trans;
                                        cmd = new SqlCommandBuilder(adp);
                                        adp.Fill(dt);
                                        dt.Tables[0].TableName = "Master";
                                        dt.Tables[1].TableName = "Child";

                                    }

                                    String JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                                    using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data,users_id) values(" + invno + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + (User) + "','" + (system) + "','New Entry',''," + UserId + ")", con, trans))
                                    {

                                        rows = cm.ExecuteNonQuery();

                                    }

                                    if (rows > 0)
                                    {

                                        trans.Commit();
                                        IsInsert = key;

                                    }
                                    else
                                    {
                                        trans.Rollback();
                                        IsInsert = 0;
                                    }
                                }


                            }
                            else
                            {
                                trans.Rollback();
                                IsInsert = 0;
                            }
                        }
                        else
                        {
                            trans.Rollback();
                            IsInsert = 0;
                        }

                    }
                    else
                    {
                        trans.Rollback();
                        IsInsert = 0;

                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                response = ex.Message;
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }

            return IsInsert.ToString();


        }

        public String Invoice_Update(String json)
        {

            JObject json_object = JObject.Parse(json);

            String token = json_object["token"].ToString();
            if (token != app_key)
            {
                json = "In-Valid";
                return json;
            }

            String child = json_object["Child"].ToString();
            DataTable table = (DataTable)JsonConvert.DeserializeObject(child, (typeof(DataTable)));
            DataTable table_ledger = (DataTable)JsonConvert.DeserializeObject(json_object["Ledger"].ToString(), (typeof(DataTable)));
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            String UserId = json_object["UserId"].ToString();
            int key = Convert.ToInt32(json_object["key"].ToString());
            String type = json_object["Type"].ToString();
            String date = json_object["edate"].ToString();
            String warehouse = json_object["warehouse"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int entryno = 0;
            int invno = Convert.ToInt32(json_object["inv"].ToString());

            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;

            String detail = " insert into " + json_object["Detail"] + "(key_fk,citmno,acitno,prtno,bn,invdesc,subdesc,qty,rate,amt,dscrate,dscr_p,disc,ntamt) values "
                           + " (@key,@sno,@item,@partno,@brand,@desc,@sub,@qty,@rate,@amt,@disc_rate,@disc_p,@disc,@amount)";

            String stock = "insert into stock(pidno,cidno,edate,refno,estatus,product,description,subdesc,rec,loose_rec,iss,loose_iss,rate,gross_amount,disc_rate,disc_p,disc,net_amount,acode,inv_disc) " +
                           "  values (@key,(select SCOPE_IDENTITY()),@edate,@refno,@type,@item,@desc,@sub,@rec,@loose_rec,@iss,@loose_iss,@rate,@amt,@disc_rate,@disc_p,@disc,@amount,@acode,@inv_disc)";

            String OrderMaster = "  Update " + json_object["Master"] + " set invtype=@invtype,clkdate=@edate,date=@edate,mrdminv_no=@vno,acode=@debit,c_code=@credit,duedate=@duedate,days=@days,prtclar=@remarks," +
                                 "  amtgrs=@gross,disc=@disc,dscr_p=@dscr_p,expmnininv=@expense,courier=@courier,amtnet=@net,gstp=@gstp,gsta=@gsta,amtnetwgst=@gst_amt," +
                                 "  itp=@itp,ita=@itpa,na_w_itax=@itp_amt,ttlamtnet=@total,closed=@closed,collection=@collection,balance=@balance where key_pk=@key_pk";

            String ledger = " insert into ledger(edate,description,details,type,ref,mrd,d_acode,d_amt,c_acode,c_amt,pidno,per,posted,entryno) " +
                            " values(@edate,@desc,@det,@type,@ref,@mrd,@d_acode,@d_amt,@c_acode,@c_amt,@pidno,@per,@posted,@entryno);";

            String Select_Master = "select distinct  sm.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

            String Select_Child = "select distinct  sd.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

            String delete_detail = "Delete from " + json_object["Detail"] + " where key_fk=" + key + ";";

            String delete_ledger = "Delete from Ledger where type='" + json_object["Type"].ToString() + "' and ref=" + Convert.ToInt32(json_object["inv"].ToString()) + " and pidno=" + Convert.ToInt32(json_object["key"].ToString()) + ";";

            String delete_stock = "Delete from stock where estatus='" + type + "' and pidno=" + key + " and refno=" + Convert.ToInt32(json_object["inv"].ToString()) + ";";

            String delete = delete_detail + delete_stock + delete_ledger;

            DataTable st = new DataTable();


            String remarks = json_object["remarks"].ToString().Trim();


            if (type == "SI")
            {
                DataTable dm = getBalance(json_object["debit"].ToString());
                if (dm.Rows.Count > 0)
                {

                    decimal limit = Convert.ToDecimal(dm.Rows[0]["d_limit"]);
                    decimal balance = Convert.ToDecimal(dm.Rows[0]["balance"]) + Convert.ToDecimal(json_object["total"].ToString());

                    if (balance > limit)
                    {
                        return "402";
                    }
                }
            }

            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();


                    using (cm = new SqlCommand("select top 1 isnull(entryno,0) from Ledger where type='" + type + "' and ref='" + invno + "' and pidno=" + key + " order by entryno desc;", con, trans))
                    {

                        entryno = Convert.ToInt32(cm.ExecuteScalar());
                    }

                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {

                        cm.Parameters.AddWithValue("key_pk", key);
                        cm.Parameters.AddWithValue("invtype", json_object["invtype"].ToString());
                        cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("invoice", invno);
                        cm.Parameters.AddWithValue("vno", json_object["vno"].ToString());
                        cm.Parameters.AddWithValue("debit", json_object["debit"].ToString());
                        cm.Parameters.AddWithValue("credit", json_object["credit"].ToString());
                        cm.Parameters.AddWithValue("duedate", json_object["days"].ToString() == String.Empty ? (Object)DBNull.Value : json_object["duedate"].ToString());
                        cm.Parameters.AddWithValue("days", json_object["days"].ToString() == String.Empty ? (Object)DBNull.Value : Convert.ToInt32(json_object["days"].ToString()));
                        cm.Parameters.AddWithValue("remarks", json_object["remarks"].ToString());
                        cm.Parameters.AddWithValue("gross", json_object["gross"].ToString());
                        cm.Parameters.AddWithValue("dscr_p", Convert.ToDecimal(json_object["disc_per"].ToString()));
                        cm.Parameters.AddWithValue("disc", json_object["disc_amt"].ToString());
                        cm.Parameters.AddWithValue("expense", json_object["freight"].ToString());
                        cm.Parameters.AddWithValue("courier", json_object["courier"].ToString());
                        cm.Parameters.AddWithValue("net", json_object["net_amt"].ToString());
                        cm.Parameters.AddWithValue("gstp", json_object["gst_per"].ToString());
                        cm.Parameters.AddWithValue("gsta", json_object["gst_val"].ToString());
                        cm.Parameters.AddWithValue("gst_amt", json_object["gstnet"].ToString());
                        cm.Parameters.AddWithValue("itp", json_object["it_per"].ToString());
                        cm.Parameters.AddWithValue("itpa", json_object["it_val"].ToString());
                        cm.Parameters.AddWithValue("itp_amt", json_object["itnet"].ToString());
                        cm.Parameters.AddWithValue("total", json_object["total"].ToString());
                        cm.Parameters.AddWithValue("closed", (json_object["closed"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["closed"].ToString())));
                        cm.Parameters.AddWithValue("collection", (json_object["collection"] == null ? (Object)DBNull.Value : Convert.ToDecimal(json_object["collection"].ToString())));
                        cm.Parameters.AddWithValue("balance", (json_object["balance"] == null ? (Object)DBNull.Value : Convert.ToDecimal(json_object["balance"].ToString())));

                        rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());

                    }
                    if (rowseffected > 0)
                    {

                        using (cm = new SqlCommand(delete, con, trans))
                        {

                            cm.ExecuteNonQuery();

                        }

                        using (cm = new SqlCommand(detail + ";" + stock, con, trans))
                        {
                            cm.Parameters.Add("key", SqlDbType.Int);
                            cm.Parameters.Add("sno", SqlDbType.Int);
                            cm.Parameters.Add("item", SqlDbType.Int);
                            cm.Parameters.Add("partno", SqlDbType.VarChar);
                            cm.Parameters.Add("brand", SqlDbType.VarChar);
                            cm.Parameters.Add("desc", SqlDbType.VarChar);
                            cm.Parameters.Add("sub", SqlDbType.VarChar);
                            cm.Parameters.Add("qty", SqlDbType.Decimal);
                            cm.Parameters.Add("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amt", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_p", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("amount", SqlDbType.Decimal);

                            cm.Parameters.Add("edate", SqlDbType.DateTime);
                            cm.Parameters.Add("refno", SqlDbType.Int);
                            cm.Parameters.Add("type", SqlDbType.VarChar);
                            cm.Parameters.Add("rec", SqlDbType.Decimal);
                            cm.Parameters.Add("loose_rec", SqlDbType.Decimal);
                            cm.Parameters.Add("iss", SqlDbType.Decimal);
                            cm.Parameters.Add("loose_iss", SqlDbType.Decimal);
                            cm.Parameters.Add("acode", SqlDbType.VarChar);
                            cm.Parameters.Add("inv_disc", SqlDbType.Decimal);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["sno"].Value = Convert.ToInt32(row["sno"]);
                                cm.Parameters["item"].Value = Convert.ToInt32(row["item"]);
                                cm.Parameters["partno"].Value = Convert.ToString(row["partno"]);
                                cm.Parameters["brand"].Value = Convert.ToString(row["brand"]);
                                cm.Parameters["desc"].Value = Convert.ToString(row["desc"]);
                                cm.Parameters["sub"].Value = Convert.ToString(row["sub"]);
                                cm.Parameters["qty"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["rate"].Value = Convert.ToDecimal(row["rate"]);
                                cm.Parameters["amt"].Value = Convert.ToDecimal(row["amount"]);
                                cm.Parameters["disc_rate"].Value = Convert.ToDecimal(row["disc_rate"]);
                                cm.Parameters["disc_p"].Value = Convert.ToDecimal(row["disc_per"]);
                                cm.Parameters["disc"].Value = Convert.ToDecimal(row["disc_amt"]);
                                cm.Parameters["amount"].Value = Convert.ToDecimal(row["net_amt"]);

                                cm.Parameters["edate"].Value = date;
                                cm.Parameters["refno"].Value = invno;
                                cm.Parameters["type"].Value = type;
                                cm.Parameters["rec"].Value = Convert.ToDecimal(row["rec"]);
                                cm.Parameters["loose_rec"].Value = Convert.ToDecimal(row["loose_rec"]);
                                cm.Parameters["iss"].Value = Convert.ToDecimal(row["iss"]);
                                cm.Parameters["loose_iss"].Value = Convert.ToDecimal(row["loose_iss"]);
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"]);

                                cm.Parameters["inv_disc"].Value = Convert.ToDecimal(json_object["disc_per"].ToString());


                                rowseffected += cm.ExecuteNonQuery();

                            }


                        }

                        if (rowseffected > 0)
                        {
                            using (cm = new SqlCommand(ledger, con, trans))
                            {
                                cm.Parameters.Add("edate", SqlDbType.DateTime);
                                cm.Parameters.Add("desc", SqlDbType.VarChar);
                                cm.Parameters.Add("det", SqlDbType.VarChar);
                                cm.Parameters.Add("type", SqlDbType.VarChar);
                                cm.Parameters.Add("ref", SqlDbType.VarChar);
                                cm.Parameters.Add("mrd", SqlDbType.VarChar);
                                cm.Parameters.Add("d_acode", SqlDbType.VarChar);
                                cm.Parameters.Add("d_amt", SqlDbType.Decimal);
                                cm.Parameters.Add("c_acode", SqlDbType.VarChar);
                                cm.Parameters.Add("c_amt", SqlDbType.Decimal);
                                cm.Parameters.Add("pidno", SqlDbType.Int);
                                cm.Parameters.Add("per", SqlDbType.VarChar);
                                cm.Parameters.Add("posted", SqlDbType.Int);
                                cm.Parameters.Add("entryno", SqlDbType.Int);

                                foreach (DataRow row in table_ledger.Rows)
                                {

                                    cm.Parameters["edate"].Value = row["edate"];
                                    cm.Parameters["desc"].Value = row["description"] + (remarks == "" ? "" : "(" + remarks + ")");
                                    cm.Parameters["det"].Value = row["details"] + (remarks == "" ? "" : "(" + remarks + ")");
                                    cm.Parameters["type"].Value = row["type"];
                                    cm.Parameters["ref"].Value = invno;
                                    cm.Parameters["mrd"].Value = row["mrd"];
                                    cm.Parameters["d_acode"].Value = row["d_acode"].ToString().Trim();
                                    cm.Parameters["d_amt"].Value = Convert.ToDecimal(row["d_amt"]);
                                    cm.Parameters["c_acode"].Value = row["c_acode"].ToString().Trim();
                                    cm.Parameters["c_amt"].Value = Convert.ToDecimal(row["c_amt"]);
                                    cm.Parameters["pidno"].Value = key;
                                    cm.Parameters["per"].Value = (row["per"]);
                                    cm.Parameters["posted"].Value = (row["posted"]);
                                    cm.Parameters["entryno"].Value = entryno == 0 ? (Object)DBNull.Value : entryno;
                                    rowseffected += cm.ExecuteNonQuery();

                                }


                            }

                            if (rowseffected > 0)
                            {
                                {

                                    using (adp = new SqlDataAdapter(Select_Master + ";" + Select_Child, con))
                                    {
                                        adp.SelectCommand.Transaction = trans;

                                        cmd = new SqlCommandBuilder(adp);
                                        adp.Fill(dt);
                                        dt.Tables[0].TableName = "Master";
                                        dt.Tables[1].TableName = "Child";

                                    }

                                    String JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                                    using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data,users_id) values(" + invno + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + User + "','" + system + "','Modified Entry','" + JSONString + "'," + UserId + ")", con, trans))
                                    {

                                        rows = cm.ExecuteNonQuery();

                                    }

                                    if (rows > 0)
                                    {

                                        trans.Commit();
                                        IsInsert = key;

                                    }
                                    else
                                    {
                                        trans.Rollback();
                                        IsInsert = 0;
                                    }
                                }


                            }
                            else
                            {
                                trans.Rollback();
                                IsInsert = 0;
                            }
                        }
                        else
                        {
                            trans.Rollback();
                            IsInsert = 0;
                        }

                    }
                    else
                    {
                        trans.Rollback();
                        IsInsert = 0;

                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                response = ex.Message;
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }


            return IsInsert.ToString();


        }

        public String Purchase_Invoice_Insert(String json)
        {

            JObject json_object = JObject.Parse(json);

            String token = json_object["token"] == null ? "" : json_object["token"].ToString();
            if (token != "")
            {
                if (Authorization(token) <= 0)
                {
                    json = "In-Valid";
                    return json;
                }
            }

            String child = json_object["Child"].ToString();
            DataTable table = (DataTable)JsonConvert.DeserializeObject(child, (typeof(DataTable)));
            DataTable table_ledger = (DataTable)JsonConvert.DeserializeObject(json_object["Ledger"].ToString(), (typeof(DataTable)));
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            String type = json_object["Type"].ToString();
            String date = json_object["edate"].ToString();
            String warehouse = json_object["warehouse"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int invno = 0;
            int key = 0;
            int entryno = 0;
            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;

            String detail = " insert into " + json_object["Detail"] + "(key_fk,citmno,acitno,prtno,bn,invdesc,subdesc,qty,rate,amt,dscrate,dscr_p,disc,ntamt,line_warehouse,arrival_no,arrival_key) values "
                             + " (@key,@sno,@item,@partno,@brand,@desc,@sub,@qty,@rate,@amt,@disc_rate,@disc_p,@disc,@amount,@line_warehouse,@arrival_no,@arrival_key)";

            String stock = "insert into stock(pidno,cidno,edate,refno,estatus,product,description,subdesc,rec,loose_rec,iss,loose_iss,rate,gross_amount,disc_rate,disc_p,disc,net_amount,acode,warehouse,inv_disc) " +
                           "  values (@key,(select SCOPE_IDENTITY()),@edate,@refno,@type,@item,@desc,@sub,@rec,@loose_rec,@iss,@loose_iss,@rate,@amt,@disc_rate,@disc_p,@disc,@amount,@acode,@warehouse,@inv_disc)";

            String Order1 = " insert into " + json_object["Master"] + "(key_pk,usrno__,invtype,clkdate,date,invoice_no,mrdminv_no,acode,c_code,duedate,days,prtclar,warehouse,amtgrs,disc,dscr_p,expmnininv,courier,amtnet,gstp,gsta,amtnetwgst,itp,ita,na_w_itax,ttlamtnet,citmno,auth_by,closed,users,quotation_no,collection,balance) values ";
            String Order2 = " (@key_pk,@userno,@invtype,@edate,@date,@invoice,@vno,@debit,@credit,@duedate,@days,@remarks,@warehouse,@gross,@disc,@dscr_p,@expense,@courier,@net,@gstp,@gsta,@gst_amt,@itp,@itpa,@itp_amt,@total,@qty,@auth_by,@closed,@users,@quotation_no,@collection,@balance); ";
            String OrderMaster = Order1 + Order2;

            String ledger = " insert into ledger(edate,description,details,type,ref,mrd,d_acode,d_amt,c_acode,c_amt,pidno,per,posted,entryno) " +
                            " values(@edate,@desc,@det,@type,@ref,@mrd,@d_acode,@d_amt,@c_acode,@c_amt,@pidno,@per,@posted,@entryno);";

            String Select_Master = "select distinct  sm.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=";

            String Select_Child = "select distinct  sd.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=";

            String remarks = json_object["remarks"].ToString().Trim();
            try
            {


                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();

                    using (cm = new SqlCommand("select top 1 isnull(entryno,0)+1 from Ledger order by entryno desc;", con, trans))
                    {

                        entryno = Convert.ToInt32(cm.ExecuteScalar());
                    }

                    using (cm = new SqlCommand(" select top 1 invoice_no from " + json_object["Master"] + " order by invoice_no desc;", con, trans))
                    {

                        invno = Convert.ToInt32(cm.ExecuteScalar()) + 1;
                    }

                    using (cm = new SqlCommand(" select top 1 key_pk from " + json_object["Master"] + " order by key_pk desc;", con, trans))
                    {

                        key = Convert.ToInt32(cm.ExecuteScalar()) + 1;
                    }

                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {

                        cm.Parameters.AddWithValue("key_pk", key);
                        cm.Parameters.AddWithValue("userno", json_object["UserId"].ToString());
                        cm.Parameters.AddWithValue("invtype", json_object["invtype"].ToString());
                        cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("date", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("invoice", invno);
                        cm.Parameters.AddWithValue("vno", json_object["vno"].ToString());
                        cm.Parameters.AddWithValue("debit", json_object["debit"].ToString());
                        cm.Parameters.AddWithValue("credit", json_object["credit"].ToString());
                        cm.Parameters.AddWithValue("duedate", json_object["days"].ToString() == String.Empty ? (Object)DBNull.Value : json_object["duedate"].ToString());
                        cm.Parameters.AddWithValue("days", json_object["days"].ToString() == String.Empty ? (Object)DBNull.Value : Convert.ToInt32(json_object["days"].ToString()));
                        cm.Parameters.AddWithValue("remarks", json_object["remarks"].ToString());
                        cm.Parameters.AddWithValue("warehouse", warehouse == String.Empty ? (Object)DBNull.Value : warehouse);
                        cm.Parameters.AddWithValue("quotation_no", json_object["quotation_no"].ToString() == String.Empty ? (Object)DBNull.Value : Convert.ToInt32(json_object["quotation_no"].ToString()));

                        cm.Parameters.AddWithValue("gross", json_object["gross"].ToString());
                        cm.Parameters.AddWithValue("disc", json_object["disc_amt"].ToString());
                        cm.Parameters.AddWithValue("dscr_p", Convert.ToDecimal(json_object["disc_per"].ToString()));
                        cm.Parameters.AddWithValue("expense", json_object["freight"].ToString());
                        cm.Parameters.AddWithValue("courier", json_object["courier"].ToString());
                        cm.Parameters.AddWithValue("net", json_object["net_amt"].ToString());
                        cm.Parameters.AddWithValue("gstp", json_object["gst_per"].ToString());
                        cm.Parameters.AddWithValue("gsta", json_object["gst_val"].ToString());
                        cm.Parameters.AddWithValue("gst_amt", json_object["gstnet"].ToString());
                        cm.Parameters.AddWithValue("itp", json_object["it_per"].ToString());
                        cm.Parameters.AddWithValue("itpa", json_object["it_val"].ToString());
                        cm.Parameters.AddWithValue("itp_amt", json_object["itnet"].ToString());
                        cm.Parameters.AddWithValue("total", json_object["total"].ToString());
                        cm.Parameters.AddWithValue("qty", json_object["qty"].ToString());
                        cm.Parameters.AddWithValue("auth_by", (json_object["auth_by"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["auth_by"].ToString()) == -1 ? (Object)DBNull.Value : Convert.ToInt32(json_object["auth_by"].ToString())));
                        cm.Parameters.AddWithValue("closed", (json_object["closed"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["closed"].ToString())));
                        cm.Parameters.AddWithValue("users", (json_object["UserId"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["UserId"].ToString())));
                        cm.Parameters.AddWithValue("collection", (json_object["collection"] == null ? (Object)DBNull.Value : Convert.ToDecimal(json_object["collection"].ToString())));
                        cm.Parameters.AddWithValue("balance", (json_object["balance"] == null ? (Object)DBNull.Value : Convert.ToDecimal(json_object["balance"].ToString())));

                        rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());

                    }
                    if (rowseffected > 0)
                    {

                        using (cm = new SqlCommand(detail + ";" + stock, con, trans))
                        {
                            cm.Parameters.Add("key", SqlDbType.Int);
                            cm.Parameters.Add("sno", SqlDbType.Int);
                            cm.Parameters.Add("item", SqlDbType.Int);
                            cm.Parameters.Add("partno", SqlDbType.VarChar);
                            cm.Parameters.Add("brand", SqlDbType.VarChar);
                            cm.Parameters.Add("desc", SqlDbType.VarChar);
                            cm.Parameters.Add("sub", SqlDbType.VarChar);
                            cm.Parameters.Add("qty", SqlDbType.Decimal);
                            cm.Parameters.Add("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amt", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_p", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("amount", SqlDbType.Decimal);
                            cm.Parameters.Add("line_warehouse", SqlDbType.Int);
                            cm.Parameters.Add("arrival_no", SqlDbType.Int);
                            cm.Parameters.Add("arrival_key", SqlDbType.Int);

                            cm.Parameters.Add("edate", SqlDbType.DateTime);
                            cm.Parameters.Add("refno", SqlDbType.Int);
                            cm.Parameters.Add("type", SqlDbType.VarChar);
                            cm.Parameters.Add("rec", SqlDbType.Decimal);
                            cm.Parameters.Add("loose_rec", SqlDbType.Decimal);
                            cm.Parameters.Add("iss", SqlDbType.Decimal);
                            cm.Parameters.Add("loose_iss", SqlDbType.Decimal);
                            cm.Parameters.Add("acode", SqlDbType.VarChar);
                            cm.Parameters.Add("warehouse", SqlDbType.Int);
                            cm.Parameters.Add("inv_disc", SqlDbType.Decimal);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["sno"].Value = Convert.ToInt32(row["sno"]);
                                cm.Parameters["item"].Value = Convert.ToInt32(row["item"]);
                                cm.Parameters["partno"].Value = Convert.ToString(row["partno"]);
                                cm.Parameters["brand"].Value = Convert.ToString(row["brand"]);
                                cm.Parameters["desc"].Value = Convert.ToString(row["desc"]);
                                cm.Parameters["sub"].Value = Convert.ToString(row["sub"]);
                                cm.Parameters["qty"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["rate"].Value = Convert.ToDecimal(row["rate"]);
                                cm.Parameters["amt"].Value = Convert.ToDecimal(row["amount"]);
                                cm.Parameters["disc_rate"].Value = Convert.ToDecimal(row["disc_rate"]);
                                cm.Parameters["disc_p"].Value = Convert.ToDecimal(row["disc_per"]);
                                cm.Parameters["disc"].Value = Convert.ToDecimal(row["disc_amt"]);
                                cm.Parameters["amount"].Value = Convert.ToDecimal(row["net_amt"]);
                                cm.Parameters["line_warehouse"].Value = warehouse.Trim() != String.Empty ? warehouse : row["warehouse"].ToString() == String.Empty ? (Object)DBNull.Value : Convert.ToInt32(row["warehouse"]);
                                cm.Parameters["arrival_no"].Value = row["arrival_no"].ToString() == String.Empty ? (Object)DBNull.Value : Convert.ToInt32(row["arrival_no"]);
                                cm.Parameters["arrival_key"].Value = row["arrival_key"].ToString() == String.Empty ? (Object)DBNull.Value : Convert.ToInt32(row["arrival_key"]);

                                cm.Parameters["edate"].Value = date;
                                cm.Parameters["refno"].Value = invno;
                                cm.Parameters["type"].Value = type;
                                cm.Parameters["rec"].Value = Convert.ToDecimal(row["rec"]);
                                cm.Parameters["loose_rec"].Value = Convert.ToDecimal(row["loose_rec"]);
                                cm.Parameters["iss"].Value = Convert.ToDecimal(row["iss"]);
                                cm.Parameters["loose_iss"].Value = Convert.ToDecimal(row["loose_iss"]);
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"]);
                                cm.Parameters["warehouse"].Value = warehouse.Trim() != String.Empty ? warehouse : row["warehouse"].ToString() == String.Empty ? (Object)DBNull.Value : Convert.ToInt32(row["warehouse"]);
                                cm.Parameters["inv_disc"].Value = Convert.ToDecimal(json_object["disc_per"].ToString());

                                rowseffected += cm.ExecuteNonQuery();

                            }
                        }

                        if (rowseffected > 0)
                        {
                            using (cm = new SqlCommand(ledger, con, trans))
                            {
                                cm.Parameters.Add("edate", SqlDbType.DateTime);
                                cm.Parameters.Add("desc", SqlDbType.VarChar);
                                cm.Parameters.Add("det", SqlDbType.VarChar);
                                cm.Parameters.Add("type", SqlDbType.VarChar);
                                cm.Parameters.Add("ref", SqlDbType.VarChar);
                                cm.Parameters.Add("mrd", SqlDbType.VarChar);
                                cm.Parameters.Add("d_acode", SqlDbType.VarChar);
                                cm.Parameters.Add("d_amt", SqlDbType.Decimal);
                                cm.Parameters.Add("c_acode", SqlDbType.VarChar);
                                cm.Parameters.Add("c_amt", SqlDbType.Decimal);
                                cm.Parameters.Add("pidno", SqlDbType.Int);
                                cm.Parameters.Add("per", SqlDbType.VarChar);
                                cm.Parameters.Add("posted", SqlDbType.Int);
                                cm.Parameters.Add("entryno", SqlDbType.Int);

                                foreach (DataRow row in table_ledger.Rows)
                                {

                                    cm.Parameters["edate"].Value = row["edate"];
                                    cm.Parameters["desc"].Value = row["description"] + (remarks == "" ? "" : "(" + remarks + ")");
                                    cm.Parameters["det"].Value = row["details"] + (remarks == "" ? "" : "(" + remarks + ")");
                                    cm.Parameters["type"].Value = row["type"];
                                    cm.Parameters["ref"].Value = invno;
                                    cm.Parameters["mrd"].Value = row["mrd"];
                                    cm.Parameters["d_acode"].Value = row["d_acode"].ToString().Trim();
                                    cm.Parameters["d_amt"].Value = Convert.ToDecimal(row["d_amt"]);
                                    cm.Parameters["c_acode"].Value = row["c_acode"].ToString().Trim();
                                    cm.Parameters["c_amt"].Value = Convert.ToDecimal(row["c_amt"]);
                                    cm.Parameters["pidno"].Value = key;
                                    cm.Parameters["per"].Value = (row["per"]);
                                    cm.Parameters["posted"].Value = (row["posted"]);
                                    cm.Parameters["entryno"].Value = entryno;

                                    rowseffected += cm.ExecuteNonQuery();

                                }


                            }

                            if (rowseffected > 0)
                            {
                                {
                                    Select_Master += invno;
                                    Select_Child += invno;


                                    using (adp = new SqlDataAdapter(Select_Master + ";" + Select_Child, con))
                                    {
                                        adp.SelectCommand.Transaction = trans;
                                        cmd = new SqlCommandBuilder(adp);
                                        adp.Fill(dt);
                                        dt.Tables[0].TableName = "Master";
                                        dt.Tables[1].TableName = "Child";

                                    }

                                    String JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                                    using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invno + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + (User) + "','" + (system) + "','New Entry','" + JSONString + "')", con, trans))
                                    {

                                        rows = cm.ExecuteNonQuery();

                                    }

                                    if (rows > 0)
                                    {

                                        trans.Commit();
                                        Update_Stock(table);
                                        IsInsert = invno;

                                    }
                                    else
                                    {
                                        trans.Rollback();
                                        IsInsert = 0;
                                    }
                                }


                            }
                            else
                            {
                                trans.Rollback();
                                IsInsert = 0;
                            }
                        }
                        else
                        {
                            trans.Rollback();
                            IsInsert = 0;
                        }

                    }
                    else
                    {
                        trans.Rollback();
                        IsInsert = 0;

                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                response = ex.Message;
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }

            /* if (IsInsert > 0)
             {
                 String invoice = " select distinct om.entry from OrderMaster om,order_detail od where om.Entry=od.MEntry and om.estatus='SV' order by om.Entry;";
                 response = IList_GetTable(invoice);
             }*/
            return IsInsert.ToString();


        }

        public String Purchase_Invoice_Update(String json)
        {

            JObject json_object = JObject.Parse(json);

            String token = json_object["token"] == null ? "" : json_object["token"].ToString();
            if (token != "")
            {
                if (Authorization(token) <= 0)
                {
                    json = "In-Valid";
                    return json;
                }
            }

            String child = json_object["Child"].ToString();
            DataTable table = (DataTable)JsonConvert.DeserializeObject(child, (typeof(DataTable)));
            DataTable table_ledger = (DataTable)JsonConvert.DeserializeObject(json_object["Ledger"].ToString(), (typeof(DataTable)));
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            int key = Convert.ToInt32(json_object["key"].ToString());
            String type = json_object["Type"].ToString();
            String date = json_object["edate"].ToString();
            String warehouse = json_object["warehouse"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int entryno = 0;
            int invno = Convert.ToInt32(json_object["inv"].ToString());

            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;

            String detail = " insert into " + json_object["Detail"] + "(key_fk,citmno,acitno,prtno,bn,invdesc,subdesc,qty,rate,amt,dscrate,dscr_p,disc,ntamt,line_warehouse,arrival_no,arrival_key) values "
                           + " (@key,@sno,@item,@partno,@brand,@desc,@sub,@qty,@rate,@amt,@disc_rate,@disc_p,@disc,@amount,@warehouse,@arrival_no,@arrival_key)";

            String stock = "insert into stock(pidno,cidno,edate,refno,estatus,product,description,subdesc,rec,loose_rec,iss,loose_iss,rate,gross_amount,disc_rate,disc_p,disc,net_amount,acode,warehouse,inv_disc) " +
                           "  values (@key,(select SCOPE_IDENTITY()),@edate,@refno,@type,@item,@desc,@sub,@rec,@loose_rec,@iss,@loose_iss,@rate,@amt,@disc_rate,@disc_p,@disc,@amount,@acode,@warehouse,@inv_disc)";

            String OrderMaster = "  Update " + json_object["Master"] + " set invtype=@invtype,clkdate=@edate,date=@edate,mrdminv_no=@vno,acode=@debit,c_code=@credit,duedate=@duedate,days=@days,prtclar=@remarks," +
                                 "  warehouse=@warehouse,amtgrs=@gross,disc=@disc,dscr_p=@dscr_p,expmnininv=@expense,courier=@courier,amtnet=@net,gstp=@gstp,gsta=@gsta,amtnetwgst=@gst_amt," +
                                 "  itp=@itp,ita=@itpa,na_w_itax=@itp_amt,ttlamtnet=@total,auth_by=@auth_by,closed=@closed,collection=@collection,balance=@balance where key_pk=@key_pk";

            String ledger = " insert into ledger(edate,description,details,type,ref,mrd,d_acode,d_amt,c_acode,c_amt,pidno,per,posted,entryno) " +
                            " values(@edate,@desc,@det,@type,@ref,@mrd,@d_acode,@d_amt,@c_acode,@c_amt,@pidno,@per,@posted,@entryno);";

            String Select_Master = "select distinct  sm.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

            String Select_Child = "select distinct  sd.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

            String delete_detail = "Delete from " + json_object["Detail"] + " where key_fk=" + key + ";";

            String delete_ledger = "Delete from Ledger where type='" + json_object["Type"].ToString() + "' and ref=" + Convert.ToInt32(json_object["inv"].ToString()) + " and pidno=" + Convert.ToInt32(json_object["key"].ToString()) + ";";

            String delete_stock = "Delete from stock where estatus='" + type + "' and pidno=" + key + " and refno=" + Convert.ToInt32(json_object["inv"].ToString()) + ";";

            String delete = delete_detail + delete_stock + delete_ledger;

            DataTable st = new DataTable();

            String remarks = json_object["remarks"].ToString().Trim();

            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();


                    using (cm = new SqlCommand("select top 1 isnull(entryno,0) from Ledger where type='" + type + "' and ref='" + invno + "' and pidno=" + key + " order by entryno desc;", con, trans))
                    {

                        entryno = Convert.ToInt32(cm.ExecuteScalar());
                    }

                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {

                        cm.Parameters.AddWithValue("key_pk", key);
                        cm.Parameters.AddWithValue("invtype", json_object["invtype"].ToString());
                        cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("invoice", invno);
                        cm.Parameters.AddWithValue("vno", json_object["vno"].ToString());
                        cm.Parameters.AddWithValue("debit", json_object["debit"].ToString());
                        cm.Parameters.AddWithValue("credit", json_object["credit"].ToString());
                        cm.Parameters.AddWithValue("duedate", json_object["days"].ToString() == String.Empty ? (Object)DBNull.Value : json_object["duedate"].ToString());
                        cm.Parameters.AddWithValue("days", json_object["days"].ToString() == String.Empty ? (Object)DBNull.Value : Convert.ToInt32(json_object["days"].ToString()));
                        cm.Parameters.AddWithValue("remarks", json_object["remarks"].ToString());
                        cm.Parameters.AddWithValue("warehouse", json_object["warehouse"].ToString());
                        cm.Parameters.AddWithValue("gross", json_object["gross"].ToString());
                        cm.Parameters.AddWithValue("dscr_p", Convert.ToDecimal(json_object["disc_per"].ToString()));
                        cm.Parameters.AddWithValue("disc", json_object["disc_amt"].ToString());
                        cm.Parameters.AddWithValue("expense", json_object["freight"].ToString());
                        cm.Parameters.AddWithValue("courier", json_object["courier"].ToString());
                        cm.Parameters.AddWithValue("net", json_object["net_amt"].ToString());
                        cm.Parameters.AddWithValue("gstp", json_object["gst_per"].ToString());
                        cm.Parameters.AddWithValue("gsta", json_object["gst_val"].ToString());
                        cm.Parameters.AddWithValue("gst_amt", json_object["gstnet"].ToString());
                        cm.Parameters.AddWithValue("itp", json_object["it_per"].ToString());
                        cm.Parameters.AddWithValue("itpa", json_object["it_val"].ToString());
                        cm.Parameters.AddWithValue("itp_amt", json_object["itnet"].ToString());
                        cm.Parameters.AddWithValue("total", json_object["total"].ToString());
                        cm.Parameters.AddWithValue("auth_by", (json_object["auth_by"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["auth_by"]) == -1 ? (Object)DBNull.Value : Convert.ToInt32(json_object["auth_by"].ToString())));
                        cm.Parameters.AddWithValue("closed", (json_object["closed"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["closed"].ToString())));
                        cm.Parameters.AddWithValue("collection", (json_object["collection"] == null ? (Object)DBNull.Value : Convert.ToDecimal(json_object["collection"].ToString())));
                        cm.Parameters.AddWithValue("balance", (json_object["balance"] == null ? (Object)DBNull.Value : Convert.ToDecimal(json_object["balance"].ToString())));

                        rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());

                    }

                    if (rowseffected > 0)
                    {

                        using (cm = new SqlCommand(delete, con, trans))
                        {

                            cm.ExecuteNonQuery();

                        }

                        using (cm = new SqlCommand(detail + ";" + stock, con, trans))
                        {
                            cm.Parameters.Add("key", SqlDbType.Int);
                            cm.Parameters.Add("sno", SqlDbType.Int);
                            cm.Parameters.Add("item", SqlDbType.Int);
                            cm.Parameters.Add("partno", SqlDbType.VarChar);
                            cm.Parameters.Add("brand", SqlDbType.VarChar);
                            cm.Parameters.Add("desc", SqlDbType.VarChar);
                            cm.Parameters.Add("sub", SqlDbType.VarChar);
                            cm.Parameters.Add("qty", SqlDbType.Decimal);
                            cm.Parameters.Add("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amt", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_p", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("amount", SqlDbType.Decimal);
                            cm.Parameters.Add("arrival_no", SqlDbType.Int);
                            cm.Parameters.Add("arrival_key", SqlDbType.Int);


                            cm.Parameters.Add("edate", SqlDbType.DateTime);
                            cm.Parameters.Add("refno", SqlDbType.Int);
                            cm.Parameters.Add("type", SqlDbType.VarChar);
                            cm.Parameters.Add("rec", SqlDbType.Decimal);
                            cm.Parameters.Add("loose_rec", SqlDbType.Decimal);
                            cm.Parameters.Add("iss", SqlDbType.Decimal);
                            cm.Parameters.Add("loose_iss", SqlDbType.Decimal);
                            cm.Parameters.Add("acode", SqlDbType.VarChar);
                            cm.Parameters.Add("warehouse", SqlDbType.Int);
                            cm.Parameters.Add("inv_disc", SqlDbType.Decimal);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["sno"].Value = Convert.ToInt32(row["sno"]);
                                cm.Parameters["item"].Value = Convert.ToInt32(row["item"]);
                                cm.Parameters["partno"].Value = Convert.ToString(row["partno"]);
                                cm.Parameters["brand"].Value = Convert.ToString(row["brand"]);
                                cm.Parameters["desc"].Value = Convert.ToString(row["desc"]);
                                cm.Parameters["sub"].Value = Convert.ToString(row["sub"]);
                                cm.Parameters["qty"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["rate"].Value = Convert.ToDecimal(row["rate"]);
                                cm.Parameters["amt"].Value = Convert.ToDecimal(row["amount"]);
                                cm.Parameters["disc_rate"].Value = Convert.ToDecimal(row["disc_rate"]);
                                cm.Parameters["disc_p"].Value = Convert.ToDecimal(row["disc_per"]);
                                cm.Parameters["disc"].Value = Convert.ToDecimal(row["disc_amt"]);
                                cm.Parameters["amount"].Value = Convert.ToDecimal(row["net_amt"]);
                                cm.Parameters["arrival_no"].Value = row["arrival_no"].ToString() == String.Empty ? (Object)DBNull.Value : Convert.ToInt32(row["arrival_no"]);
                                cm.Parameters["arrival_key"].Value = row["arrival_key"].ToString() == String.Empty ? (Object)DBNull.Value : Convert.ToInt32(row["arrival_key"]);


                                cm.Parameters["edate"].Value = date;
                                cm.Parameters["refno"].Value = invno;
                                cm.Parameters["type"].Value = type;
                                cm.Parameters["rec"].Value = Convert.ToDecimal(row["rec"]);
                                cm.Parameters["loose_rec"].Value = Convert.ToDecimal(row["loose_rec"]);
                                cm.Parameters["iss"].Value = Convert.ToDecimal(row["iss"]);
                                cm.Parameters["loose_iss"].Value = Convert.ToDecimal(row["loose_iss"]);
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"]);
                                // cm.Parameters["warehouse"].Value = warehouse.Trim() != String.Empty ? warehouse : row["warehouse"].ToString() == String.Empty ? (Object)DBNull.Value : Convert.ToInt32(row["warehouse"]);
                                cm.Parameters["warehouse"].Value = row["warehouse"].ToString() == String.Empty ? (Object)DBNull.Value : Convert.ToInt32(row["warehouse"]);

                                cm.Parameters["inv_disc"].Value = Convert.ToDecimal(json_object["disc_per"].ToString());


                                rowseffected += cm.ExecuteNonQuery();

                            }


                        }

                        if (rowseffected > 0)
                        {
                            using (cm = new SqlCommand(ledger, con, trans))
                            {
                                cm.Parameters.Add("edate", SqlDbType.DateTime);
                                cm.Parameters.Add("desc", SqlDbType.VarChar);
                                cm.Parameters.Add("det", SqlDbType.VarChar);
                                cm.Parameters.Add("type", SqlDbType.VarChar);
                                cm.Parameters.Add("ref", SqlDbType.VarChar);
                                cm.Parameters.Add("mrd", SqlDbType.VarChar);
                                cm.Parameters.Add("d_acode", SqlDbType.VarChar);
                                cm.Parameters.Add("d_amt", SqlDbType.Decimal);
                                cm.Parameters.Add("c_acode", SqlDbType.VarChar);
                                cm.Parameters.Add("c_amt", SqlDbType.Decimal);
                                cm.Parameters.Add("pidno", SqlDbType.Int);
                                cm.Parameters.Add("per", SqlDbType.VarChar);
                                cm.Parameters.Add("posted", SqlDbType.Int);
                                cm.Parameters.Add("entryno", SqlDbType.Int);

                                foreach (DataRow row in table_ledger.Rows)
                                {

                                    cm.Parameters["edate"].Value = row["edate"];
                                    cm.Parameters["desc"].Value = row["description"] + (remarks == "" ? "" : "(" + remarks + ")");
                                    cm.Parameters["det"].Value = row["details"] + (remarks == "" ? "" : "(" + remarks + ")");
                                    cm.Parameters["type"].Value = row["type"];
                                    cm.Parameters["ref"].Value = invno;
                                    cm.Parameters["mrd"].Value = row["mrd"];
                                    cm.Parameters["d_acode"].Value = row["d_acode"].ToString().Trim();
                                    cm.Parameters["d_amt"].Value = Convert.ToDecimal(row["d_amt"]);
                                    cm.Parameters["c_acode"].Value = row["c_acode"].ToString().Trim();
                                    cm.Parameters["c_amt"].Value = Convert.ToDecimal(row["c_amt"]);
                                    cm.Parameters["pidno"].Value = key;
                                    cm.Parameters["per"].Value = (row["per"]);
                                    cm.Parameters["posted"].Value = (row["posted"]);
                                    cm.Parameters["entryno"].Value = entryno == 0 ? (Object)DBNull.Value : entryno;
                                    rowseffected += cm.ExecuteNonQuery();

                                }


                            }

                            if (rowseffected > 0)
                            {
                                {

                                    using (adp = new SqlDataAdapter(Select_Master + ";" + Select_Child, con))
                                    {
                                        adp.SelectCommand.Transaction = trans;

                                        cmd = new SqlCommandBuilder(adp);
                                        adp.Fill(dt);
                                        dt.Tables[0].TableName = "Master";
                                        dt.Tables[1].TableName = "Child";

                                    }

                                    String JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                                    using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invno + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + User + "','" + system + "','Modified Entry','" + JSONString + "')", con, trans))
                                    {

                                        rows = cm.ExecuteNonQuery();

                                    }

                                    if (rows > 0)
                                    {

                                        trans.Commit();
                                        Update_Stock(table);
                                        IsInsert = key;

                                    }
                                    else
                                    {
                                        trans.Rollback();
                                        IsInsert = 0;
                                    }
                                }


                            }
                            else
                            {
                                trans.Rollback();
                                IsInsert = 0;
                            }
                        }
                        else
                        {
                            trans.Rollback();
                            IsInsert = 0;
                        }

                    }
                    else
                    {
                        trans.Rollback();
                        IsInsert = 0;

                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                response = ex.Message;
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }


            return IsInsert.ToString();


        }

        public String Invoice_Print1(String json)
        {
            JObject json_object = JObject.Parse(json);
            String query = "  Select name,address,contactno from companysetup;" +
                           "  select top 1 l_user from Log where type='" + json_object["type"].ToString() + "' and Entry=" + json_object["invno"].ToString() + " order by id ;";
            if (json_object["idno"] != null)
            {
                query += "  select sm.key_pk,u.users_name as users,ac.title as Title,sm.invoice_no as Invno,sm.mrdminv_no as Bkno,sm.clkdate as Edate,c.name as City,ac.contactno as Contactno,ac.add1,ac.cell1, " +
                                               "  sm.expmnininv as Freight,sm.courier as Courier,sm.gstp,sm.gsta,sd.acitno,it.partno,it.desc_cr,br.name as Brand,it.model_cr,it.unit,sd.qty, " +
                                               "  sd.rate,sd.key_pk as sn,sd.disc,sd.invdesc,sd.dscr_p,sd.dscrate,sm.disc as in_disc,sm.dscr_p as inv_dscr_p,sm.prtclar,org.short_code as origin from " + json_object["master"].ToString() + " sm inner join " + json_object["child"].ToString() + " sd on sm.key_pk=sd.key_fk  " +
                                               "  left join ac on ac.code=sm.acode left join City c on c.code=ac.city_code " +
                                               "  left join users u on u.users=sm.usrno__ " +
                                               "  left join itemlinked it on it.idno=sd.acitno left join brand br on br.code=it.brnad" +
                                               "  left join origin org on org.code=it.origin " +
                                               "  where sm.key_pd=" + json_object["idno"].ToString() + " order by sn;";
            }
            else
            {
                query += "  select sm.key_pk,u.users_name as users,ac.title as Title,sm.invoice_no as Invno,sm.mrdminv_no as Bkno,sm.clkdate as Edate,c.name as City,ac.contactno as Contactno,ac.add1,ac.cell1, " +
                               "  sm.expmnininv as Freight,sm.courier as Courier,sm.gstp,sm.gsta,sd.acitno,it.partno,it.desc_cr,br.name as Brand,it.model_cr,it.unit,sd.qty, " +
                               "  sd.rate,sd.key_pk as sn,sd.disc,sd.invdesc,sd.dscr_p,sd.dscrate,sm.disc as in_disc,sm.dscr_p as inv_dscr_p,sm.prtclar,org.short_code as origin from " + json_object["master"].ToString() + " sm inner join " + json_object["child"].ToString() + " sd on sm.key_pk=sd.key_fk  " +
                               "  left join ac on ac.code=sm.acode left join City c on c.code=ac.city_code " +
                               "  left join users u on u.users=sm.usrno__ " +
                               "  inner join itemlinked it on it.idno=sd.acitno left join brand br on br.code=it.brnad" +
                                "  left join origin org on org.code=it.origin " +
                               "  where sm.invoice_no=" + json_object["invno"].ToString() + " order by sn;";
            }


            return IList_GetDataSet(query);
        }

        public String Quotation_Print1(String json)
        {
            JObject json_object = JObject.Parse(json);
            String query = "  Select name,address,contactno from companysetup;" +
                           "  select top 1 l_user from Log where type='" + json_object["type"].ToString() + "' and Entry=" + json_object["invno"].ToString() + " order by id ;";
            if (json_object["idno"] != null)
            {
                query += "  select sm.key_pk,u.users_name as users,ac.title as Title,sm.invoice_no as Invno,sm.mrdminv_no as Bkno,sm.clkdate as Edate,c.name as City,ac.contactno as Contactno,ac.add1,ac.cell1, " +
                                               "  sm.expmnininv as Freight,sm.courier as Courier,sm.gstp,sm.gsta,sd.acitno,it.partno,it.desc_cr,br.name as Brand,it.model_cr,it.unit,sd.qty, " +
                                               "  sd.rate,sd.key_pk as sn,sd.disc,sd.invdesc,sd.dscr_p,sd.dscrate,sm.disc as in_disc,null as inv_dscr_p,sm.prtclar,sm.days,convert(varchar,sm.duedate, 105) as duedate  from " + json_object["master"].ToString() + " sm inner join " + json_object["child"].ToString() + " sd on sm.key_pk=sd.key_fk  " +
                                               "  inner join ac on ac.code=sm.acode left join City c on c.code=ac.city_code " +
                                               " left join users u on u.users=sm.usrno__ " +
                                               "  left join itemlinked it on it.idno=sd.acitno left join brand br on br.code=it.brnad" +
                                               "  where sm.key_pd=" + json_object["idno"].ToString() + " order by sn;";
            }
            else
            {
                query += "  select sm.key_pk,u.users_name as users,ac.title as Title,sm.invoice_no as Invno,sm.mrdminv_no as Bkno,sm.clkdate as Edate,c.name as City,ac.contactno as Contactno,ac.add1,ac.cell1, " +
                               "  sm.expmnininv as Freight,sm.courier as Courier,sm.gstp,sm.gsta,sd.acitno,it.partno,it.desc_cr,br.name as Brand,it.model_cr,it.unit,sd.qty, " +
                               "  sd.rate,sd.key_pk as sn,sd.disc,sd.invdesc,sd.dscr_p,sd.dscrate,sm.disc as in_disc,null as inv_dscr_p,sm.prtclar,sm.days,convert(varchar,sm.duedate, 105) as duedate from " + json_object["master"].ToString() + " sm inner join " + json_object["child"].ToString() + " sd on sm.key_pk=sd.key_fk  " +
                               "  inner join ac on ac.code=sm.acode left join City c on c.code=ac.city_code " +
                               " left join users u on u.users=sm.usrno__ " +
                               "  left join itemlinked it on it.idno=sd.acitno left join brand br on br.code=it.brnad" +
                               "  where sm.invoice_no=" + json_object["invno"].ToString() + " order by sn;";
            }


            return IList_GetDataSet(query);
        }

        public String Invoice_Print_Batch(String json)
        {
            JObject json_object = JObject.Parse(json);
            String query = "  Select name,address,contactno from companysetup " +
                           "  select top 1 l_user from Log where type='" + json_object["type"].ToString() + "' order by id ;";

            DataTable table = (DataTable)JsonConvert.DeserializeObject(json_object["table_key"].ToString(), (typeof(DataTable)));
            String where = "";
            int val = 0;
            foreach (DataRow row in table.Rows)
            {
                if (val == 0)
                {
                    where += " where sm.invoice_no=" + row["key"].ToString();
                    val = 1;
                }
                else
                {
                    where += " or sm.invoice_no=" + row["key"].ToString();

                }
            }

            query += "  select sm.key_pk,ac.title as Title,u.users_name as users,sm.invoice_no as Invno,sm.mrdminv_no as Bkno,sm.clkdate as Edate,c.name as City,ac.contactno as Contactno,ac.add1,ac.cell1, " +
                           "  sm.expmnininv as Freight,sm.courier as Courier,sm.gstp,sm.gsta,sd.acitno,it.partno,it.desc_cr,br.name as Brand,it.model_cr,it.unit,sd.qty, " +
                           "  sd.rate,sd.key_pk as sn,sd.disc,sd.invdesc,sd.dscr_p,sd.dscrate,sm.disc as in_disc,sm.dscr_p as inv_dscr_p,sm.prtclar from " + json_object["master"].ToString() + " sm inner join " + json_object["child"].ToString() + " sd on sm.key_pk=sd.key_fk  " +
                           " left join users u on u.users=sm.usrno__ " +
                           "  inner join ac on ac.code=sm.acode left join City c on c.code=ac.city_code " +
                           "  left join itemlinked it on it.idno=sd.acitno left join brand br on br.code=it.brnad" +
                             where + " order by sm.key_pk,sn";


            return IList_GetDataSet(query);
        }

        public int Invoice_Delete(String jsondata)
        {
            int IsDelete = 0;
            JObject json_object = JObject.Parse(jsondata);

            String token = json_object["token"].ToString();
            if (token != app_key)
            {
                return 404;
            }

            int invoice = Convert.ToInt32(json_object["inv"].ToString());
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            String UserId = json_object["UserId"].ToString();
            int key = Convert.ToInt32(json_object["key"].ToString());
            String type = json_object["Type"].ToString();
            DataTable st = new DataTable();

            String Select_Master = "select distinct  sm.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

            String Select_Child = "select distinct  sd.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;


            String select = Select_Master + ";" + Select_Child;
            SqlTransaction trans = null;
            String json = "";

            DataTable table = new DataTable();

            String delete_detail = "Delete from " + json_object["Detail"] + " where key_fk=" + key + ";";

            String delete_ledger = "Delete from Ledger where type='" + type + "' and ref=" + invoice + " and pidno=" + key;

            String delete_master = "Delete from " + json_object["Master"] + " where key_pk=" + key + ";";

            String delete_stock = "Delete from stock where estatus='" + type + "' and pidno=" + key + ";";

            String delete = delete_detail + delete_stock + delete_ledger + delete_master;

            DataSet ds = new DataSet();

            try
            {
                using (con = new SqlConnection(cs))
                {
                    con.Open();

                    using (adp = new SqlDataAdapter(select, con))
                    {
                        cmd = new SqlCommandBuilder(adp);
                        adp.Fill(ds);
                        json = JsonConvert.SerializeObject(ds.Tables[0]);
                        var obj = new { Master = json, Child = JsonConvert.SerializeObject(ds.Tables[1]) };
                        json = JsonConvert.SerializeObject(obj);
                    }


                    trans = con.BeginTransaction();

                    using (cm = new SqlCommand("Insert into Log(Entry,type,edate,s_user,l_user,remarks,data,users_id) values(" + invoice + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + User + "','" + system + "','Delete Entry','" + json + "'," + UserId + ")", con, trans))
                    {
                        cm.ExecuteNonQuery();
                    }


                    using (cm = new SqlCommand(delete, con, trans))
                    {
                        int a = cm.ExecuteNonQuery();
                        if (a > 0)
                        {
                            trans.Commit();
                            IsDelete = invoice;

                        }
                        else
                        {
                            trans.Rollback();
                            IsDelete = 0;

                        }
                    }

                }

            }
            catch (SqlException ex)
            {
                excp(ex.Message);

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
            return IsDelete;
        }

        public int Arrival_Orders_Quotation_Delete(String jsondata)
        {
            int IsDelete = 0;
            JObject json_object = JObject.Parse(jsondata);

            String token = json_object["token"] == null ? "" : json_object["token"].ToString();
            if (Authorization(token) <= 0)
            {
                return 404;
            }

            int invoice = Convert.ToInt32(json_object["inv"].ToString());
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            int key = Convert.ToInt32(json_object["key"].ToString());
            String type = json_object["Type"].ToString();
            DataTable st = new DataTable();

            String Select_Master = "select distinct  sm.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

            String Select_Child = "select distinct  sd.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;



            String select = Select_Master + ";" + Select_Child;
            SqlTransaction trans = null;
            String json = "";

            String delete_detail = "Delete from " + json_object["Detail"] + " where key_fk=" + key + ";";

            String delete_master = "Delete from " + json_object["Master"] + " where key_pk=" + key + ";";


            String delete = delete_detail + delete_master;

            DataSet ds = new DataSet();

            try
            {
                using (con = new SqlConnection(cs))
                {
                    con.Open();



                    using (adp = new SqlDataAdapter(select, con))
                    {
                        cmd = new SqlCommandBuilder(adp);
                        adp.Fill(ds);
                        json = JsonConvert.SerializeObject(ds.Tables[0]);
                        var obj = new { Master = json, Child = JsonConvert.SerializeObject(ds.Tables[1]) };
                        json = JsonConvert.SerializeObject(obj);
                    }

                    trans = con.BeginTransaction();

                    using (cm = new SqlCommand("Insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invoice + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + User + "','" + system + "','Delete Entry','" + json + "')", con, trans))
                    {
                        cm.ExecuteNonQuery();
                    }


                    using (cm = new SqlCommand(delete, con, trans))
                    {
                        int a = cm.ExecuteNonQuery();
                        if (a > 0)
                        {
                            trans.Commit();
                            IsDelete = invoice;

                        }
                        else
                        {
                            trans.Rollback();
                            IsDelete = 0;

                        }
                    }

                }

            }
            catch (SqlException ex)
            {
                excp(ex.Message);

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
            return IsDelete;
        }

        public int GeneralVoucher_Delete(String jsondata)
        {
            int IsDelete = 0;
            JObject json_object = JObject.Parse(jsondata);
            int invoice = Convert.ToInt32(json_object["inv"].ToString());
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            int key = Convert.ToInt32(json_object["key"].ToString());
            String type = json_object["Type"].ToString();
            DataTable st = new DataTable();

            String select = " select * from General_Journal where key_pk=" + key;

            SqlTransaction trans = null;

            String json = "";


            String delete_ledger = "Delete from Ledger where type='" + type + "' and ref=" + invoice + " and pidno=" + key;

            String delete_master = "Delete from General_Journal where key_pk=" + key + ";";


            String delete = delete_ledger + delete_master;

            DataSet ds = new DataSet();

            try
            {
                using (con = new SqlConnection(cs))
                {
                    con.Open();



                    using (adp = new SqlDataAdapter(select, con))
                    {
                        cmd = new SqlCommandBuilder(adp);
                        adp.Fill(ds);
                        json = JsonConvert.SerializeObject(ds.Tables[0]);

                    }

                    trans = con.BeginTransaction();

                    using (cm = new SqlCommand("Insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invoice + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + User + "','" + system + "','Delete Entry','" + json + "')", con, trans))
                    {
                        cm.ExecuteNonQuery();
                    }


                    using (cm = new SqlCommand(delete, con, trans))
                    {
                        int a = cm.ExecuteNonQuery();
                        if (a > 0)
                        {
                            trans.Commit();
                            IsDelete = invoice;

                        }
                        else
                        {
                            trans.Rollback();
                            IsDelete = 0;

                        }
                    }

                }

            }
            catch (SqlException ex)
            {
                excp(ex.Message);

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
            return IsDelete;
        }

        public String Rectification_Stocks_Load()
        {

            String query = "";


            query += " Select code as Maker,name as Name,short_code as Short_Code from maker order by Name;" +
                 "  select code as Brand,name as Name from brand order by Name;" +
                 "  Select item.code as Part,item.name as Name  from Item  order by name;" +
                 " Select code as Origin,name as Name,short_code as Short_Code from origin order by name ;" +
                "  select Code as Reference,Name from reference order by name";

            return IList_GetDataSet(query);

        }

        public String Rectification_Stocks_Get(String where, String token, String partno)
        {

            if (Authorization(token) <= 0)
            {
                return "In-Valid";
            }
            if (partno.Trim() != String.Empty)
            {
                string link = " select linkno from itemlinked i where LTRIM(RTRIM(i.partno))='" + partno.Trim() + "'";
                string linkno = IList_ExecuteScalerValue_String(link);

                if (linkno.Trim() != "")
                {
                    where += " or LTRIM(RTRIM(linkno))='" + linkno.Trim() + "'";
                }
            }

            String query = "  select  p.idno as [Itemno],p.brnad as Brand,p.part as Part,p.desc1 as Description,p.unit as Unit,isnull(st.balance,0) as InHand," +
                           "  case when isnull(p.stock_value,0)>0 then cast (p.stock_value/p.inhnd as numeric(14,2)) end as [Cost Price]," +
                           "  ( select top 1 dscrate from  Sales_Detail sd  " +
                           "  where sd.acitno=p.idno and sd.key_fk=(Select max(key_fk) from Sales_Detail where acitno=p.idno)) as [Last Sa Rate]," +
                           " (select top 1 dscrate from  Purchase_Detail sd  " +
                           "  where sd.acitno=p.idno and sd.key_fk=(Select max(key_fk) from Purchase_Detail where acitno=p.idno)) as [Last Pu Rate]," +
                           "  p.model_cr as [Models(s) For Circular]," +
                           "  p.partno as [PartNumber],p.linkno as [LinkNo],p.vcode as[VendorCode],(SELECT top 1 remarks FROM stock where product=p.idno ORDER BY idno desc) as Remarks,p.kept_place as[Kept Place]," +
                           "  rtrim(p.maker) as Maker,rtrim(md.name) as Model,rtrim(p.origin) as [Origin],rtrim(p.reference) as [Reference],a.total_quotation,arrival.qty as arrival,p.size,p.engine_num,isnull(verified,0) as verified from itemlinked p " +
                           " left join model md  on md.id=p.model_maker " +
                           " left join (select product,sum(ISNULL(rec,0))-sum(ISNULL(iss,0)) as Balance from stock group by product)st on st.product=p.idno " +
                           " left join (select t1.acitno,count(*) as total_quotation from( " +
                           " select qm.key_pk, qd.acitno, sum(qd.qty) as Quotation_Qty " +
                           " from Quotation_Master qm inner join Quotation_Detail qd on qm.key_pk = qd.key_fk where closed = 0 " +
                           " group by qm.key_pk, qd.acitno)t1 left JOIN( " +
                           " select qm.key_pk, qm.quotation_no, qd.acitno, sum(qd.qty) as Sales_Qty from Sales_Master qm " +

                           " inner join Sales_Detail qd on qm.key_pk = qd.key_fk " +
                           " where qm.quotation_no is not null group by qm.quotation_no,qm.key_pk,qd.acitno)t2 on t1.key_pk = t2.quotation_no " +
                           " where(t1.Quotation_Qty - Isnull(t2.Sales_Qty, 0)) > 0  group by t1.acitno)a on a.acitno=p.idno " +
                           " left join (select ad.acitno,sum(ad.qty) as qty from Arrivals_Master am inner join Arrival_Detail ad on am.key_pk=ad.key_fk " +
                           " where am.closed = 0  group by ad.acitno)arrival on arrival.acitno=p.idno " +
                           "  where " + where + " order by p.idno";

            return IList_GetTable(query);

        }

        public String Invoice_Item_Get(String where, String token, String partno)
        {

            if (Authorization(token) <= 0)
            {
                return "In-Valid";
            }

            String query = "  select  p.idno as [Itemno],p.brnad as Brand,p.part as Part,p.desc1 as Description,p.unit as Unit,p.inhnd as InHand, " +
                           "  case when isnull(p.stock_value,0)> 0 then cast(p.stock_value/ p.inhnd as numeric(14, 2)) end as [Cost Price], " +
                           "  p.model_cr as [Models(s) For Circular], p.partno as [PartNumber],p.linkno as [LinkNo],p.vcode as[VendorCode],p.kept_place as[Kept Place], " +
                           "  rtrim(p.maker) as Maker,rtrim(p.origin) as [Origin],rtrim(p.reference) as [Reference] " +
                           " ,p.size,p.engine_num from itemlinked p " +
                           "  where p.idno>0 " + where;

            return IList_GetTable(query);

        }

        public String GetQuotationLedger(String json)
        {
            JObject json_Object = JObject.Parse(json);


            int idno = Convert.ToInt32(json_Object["idno"].ToString());
            String where = "";
            String where1 = "";
            String where2 = "";
            int itemid = Convert.ToInt32(json_Object["idno"].ToString());


            if (json_Object["closed"] != null)
            {
                if (json_Object["closed"].ToString() != String.Empty)
                {

                    where2 = " and qm.closed=" + json_Object["closed"].ToString();
                }

            }
            String query = "";

            query = "  select t1.key_pk,t1.invoice_no,ac.title,t1.date,t1.Quotation_Qty,t2.Sales_Qty,t2.Inv_Rate,u.USERS_NAME,ac.code,au.USERS_NAME as auth_by,qd.* from(  " +
                    "  select qm.key_pk,qm.invoice_no,qm.date,qm.acode,qm.users,qm.auth_by,qm.closed,qd.acitno,qd.rate, sum(qd.qty) as Quotation_Qty " +
                    "  from Quotation_Master qm inner join Quotation_Detail qd on qm.key_pk = qd.key_fk where qd.acitno= " + idno + "" + where2 + " " +
                    "  group by qm.key_pk,qm.invoice_no, qd.acitno,qd.rate,qm.date,qm.acode,qm.users,qm.closed,qm.auth_by)t1 full outer JOIN(  " +
                    "  select qm.key_pk, qm.quotation_no, qd.acitno,qd.rate as Inv_Rate, sum(qd.qty) as Sales_Qty from Sales_Master qm  " +
                    "  inner join Sales_Detail qd on qm.key_pk = qd.key_fk  " +
                    "  where acitno=" + idno + "  and quotation_no is not null group by qm.quotation_no,qm.key_pk,qd.acitno,qd.rate)t2 on t1.key_pk = t2.quotation_no   " +
                    "  left join USERS u on u.USERS=t1.users left join USERS au on au.USERS=t1.auth_by inner join ac on ac.code=t1.acode  inner join itemlinked im on im.idno=t1.acitno inner join brand br on im.brnad=br.code " +
                    "  inner join Quotation_Detail qd on qd.key_fk=t1.key_pk and qd.acitno=" + idno;




            query += " Select * from itemlinked where idno=" + idno;





            return IList_GetDataSet(query);
        }

        void Update_Stock(DataTable table)
        {
            String rows = "";
            foreach (DataRow row in table.Rows)
            {
                rows += " insert into @product(idno) values(" + row["item"] + ");";
            }


            String query = " declare @stock table(product int,pu_last numeric(14,2),Inhand numeric(14,2),stock_value numeric(14,2)) " +
                           " declare @rowid int;declare @count int;declare @pid int; " +
                           "  declare @product table(rowid int identity(1,1),idno int)" +
                           " " + rows + " " +
                           "   set @rowid=" + table.Rows.Count + ";set @count=0;" +
                           " while (@count<>@rowid)begin set @count=@count+1; set @pid=(select p.idno from @product p where p.rowid=@count) " +
                           " insert into @stock(product,pu_last,Inhand,stock_value) " +
                           " Select top 1 product,rate,cumulative, case when cumulative>0 and qty>=cumulative then cumulative*rate when cumulative>0 and qty<cumulative then qty*rate else 0 end as closing_stock from ( " +
                           " select *, sum(qty) over (order by srl) as cumulative from ( " +
                           " select 0 as srl, idno,product, 0-iss as qty, rate,edate from stock where (ISNULL(iss,0))>0 and product=@pid " +
                           " union select row_number() over(order by edate) as srl, idno,product,rec, rate,edate from stock where (ISNULL(rec,0))>0 and product=@pid " +
                           " )as tab ) as maintab order by cumulative desc,idno asc  end" +
                           "  UPDATE R SET R.last_pu=p.pu_last,R.Inhnd=p.Inhand,R.stock_value=p.stock_value " +
                           " FROM dbo.itemlinked AS R INNER JOIN @stock AS P ON R.idno = P.product ";
            IList_execute(query);
        }


        public String Report_Sales(String json)
        {
            JObject json_Object = JObject.Parse(json);
            int index = Convert.ToInt32(json_Object["index"].ToString());
            String from = json_Object["from"].ToString();
            String to = json_Object["to"].ToString();

            String from2 = DateTime.ParseExact(from, "yyyy-MM-dd", CultureInfo.InvariantCulture).ToString("MM-dd-yyyy");
            String to2 = DateTime.ParseExact(to, "yyyy-MM-dd", CultureInfo.InvariantCulture).ToString("MM-dd-yyyy");
            String query = "";
            String Master = json_Object["Master"].ToString();
            String Child = json_Object["Child"].ToString();
            String where = " where  CAST(sm.clkdate AS DATE) >= CAST( '" + from + "' AS DATE)  AND CAST(sm.clkdate AS DATE) <= CAST( '" + to + "' AS DATE) ";
            String where2 = " where  CAST(sm.clkdate AS DATE) >= CAST( ''" + from + "'' AS DATE)  AND CAST(sm.clkdate AS DATE) <= CAST( ''" + to + "'' AS DATE) ";

            if (json_Object["acode"].ToString() != String.Empty)
            {
                where += " and ac.code='" + json_Object["acode"].ToString().Trim() + "'";
                where2 += " and ac.code=''" + json_Object["acode"].ToString().Trim() + "'' ";
            }

            if (json_Object["city"].ToString() != String.Empty)
            {
                where += " and city.code='" + json_Object["city"].ToString().Trim() + "'";
                where2 += " and city.code=''" + json_Object["city"].ToString().Trim() + "'' ";
            }
            if (json_Object["item"].ToString() != String.Empty)
            {
                where += " and item.code='" + json_Object["item"].ToString().Trim() + "'";
                where2 += " and item.code=''" + json_Object["item"].ToString().Trim() + "'' ";
            }
            if (json_Object["partno"].ToString() != String.Empty)
            {
                where += " and im.idno=" + json_Object["partno"].ToString().Trim();
                where2 += " and im.idno=" + json_Object["partno"].ToString().Trim();
            }
            if (json_Object["origin"].ToString() != String.Empty)
            {
                where += " and origin.code='" + json_Object["origin"].ToString().Trim() + "'";
                where2 += " and origin.code=''" + json_Object["origin"].ToString().Trim() + "''";
            }
            if (json_Object["brand"].ToString() != String.Empty)
            {
                where += " and brand.code='" + json_Object["brand"].ToString().Trim() + "'";
                where2 += " and brand.code=''" + json_Object["brand"].ToString().Trim() + "''";
            }
            if (json_Object["model"].ToString() != String.Empty)
            {
                where += " and model.code='" + json_Object["model"].ToString().Trim() + "'";
                where2 += " and model.code=''" + json_Object["model"].ToString().Trim() + "''";
            }
            if (json_Object["maker"].ToString() != String.Empty)
            {
                where += " and maker.code='" + json_Object["maker"].ToString().Trim() + "'";
                where2 += " and maker.code=''" + json_Object["maker"].ToString().Trim() + "''";
            }
            if (json_Object["reference"].ToString() != String.Empty)
            {
                where += " and rf.code='" + json_Object["reference"].ToString().Trim() + "'";
                where2 += " and rf.code=''" + json_Object["reference"].ToString().Trim() + "''";
            }

            if (index == 0 || index == 5)
            {
                query = "  select distinct sm.key_pk as [Computrized_No],sm.invoice_no as [Invno],FORMAT(Cast( sm.clkdate as Date), 'dd-MM-yyyy') as [InvDate],city.name as [City],ac.title as [Party], " +
                        " count(*) as [Qty],sum(sd.amt) as [Amount],sum(sd.disc) as [DiscAmount],sum(gsta) as [GstAmount],sum(sd.amt-sd.disc+gsta) as [NetAmount] from " + Master + " sm inner join " + Child + " sd on sm.key_pk=sd.key_fk  " +
                        " left join ac on ac.code=sm.acode left join city on city.code=ac.city_code  left join itemlinked im on im.idno=sd.acitno " +
                        " left  join origin on origin.code=im.origin  left join brand on brand.code=im.brnad left join item on item.code=im.part " +
                        " left join model on model.id=im.model_maker  left join maker on maker.code=model.maker left join reference rf on rf.code=item.reference " +
                         where + " group by sm.key_pk,sm.invoice_no,sm.clkdate,city.name,ac.title order by Invno,InvDate";
            }

            else if (index == 1 || index == 6)
            {

                query = "  select distinct im.idno,im.partno,im.linkno,im.desc1, sum( sd.qty) as [Qty],sum(sd.amt) as [Amount],sum(sd.disc) as [DiscAmount],sum(sd.amt-sd.disc) as[NetAmount] from " + Master + " sm inner join " + Child + " sd on sm.key_pk=sd.key_fk" +
                       " inner join ac on ac.code=sm.acode left join city on city.code=ac.city_code  left join itemlinked im on im.idno=sd.acitno " +
                       " left  join origin on origin.code=im.origin  left join brand on brand.code=im.brnad left join item on item.code=im.part " +
                       " left join model on model.id=im.model_maker  left join maker on maker.code=model.maker left join reference rf on rf.code=item.reference " +
                        where + " group by im.idno,im.partno,im.linkno,im.desc1 order by im.desc1;";

            }

            else if (index == 2 || index == 7)
            {
                query = "  select idno,isnull(PartNo,'') as Partno,isnull(LinkNo,'') as LinkNo,isnull(Description,'') as Description, isnull(Jan,0) as Jan,isnull(Feb,0) as Feb,isnull(Mar,0) as Mar,isnull(Apr,0) as Apr, " +
                      "  isnull(May,0) as May,isnull(Jun,0) as Jun,isnull(Jul,0)as Jul,isnull(Aug,0) as Aug,isnull(Sep,0) as Sep,isnull(Oct,0) as Oct,isnull(Nov,0) as Nov, " +
                      "  isnull(Dec,0) as Dec, " +
                      "  isnull(Jan,0) +isnull(Feb,0)+isnull(Mar,0)+isnull(Apr,0)+isnull(May,0)+isnull(Jun,0) +isnull(Jul,0)+isnull(Aug,0) +isnull(Sep,0) " +
                      "  +isnull(Oct,0) +isnull(Nov,0) + isnull(Dec,0) as Total " +
                      "  from (select Cast( DateName( month , DateAdd( month ,MONTH(sm.clkdate) , -1 )) as Varchar(3)) as Period, " +
                      " im.idno, isnull(im.partno,'') as PartNo,isnull(im.partno,'') as LinkNo,isnull(im.desc1,'') as Description,sum( sm.ttlamtnet) as[Amount] from " + Master + " sm inner join " + Child + " sd on sm.key_pk=sd.key_fk " +
                     " inner join ac on ac.code=sm.acode left join city on city.code=ac.city_code left join itemlinked im on im.idno=sd.acitno " +
                     " left  join origin on origin.code=im.origin  left join brand on brand.code=im.brnad  left join item on item.code=im.part  " +
                     " left join model on model.id=im.model_maker left join maker on maker.code=model.maker left join reference rf on rf.code=item.reference  " +
                     where + "  group by YEAR(sm.clkdate)*100 + MONTH(sm.clkdate),Cast( DateName( month , DateAdd( month ,MONTH(sm.clkdate) , -1 )) as Varchar(3)),im.idno,im.partno,im.linkno,im.desc1" +
                     " ) t pivot (Sum(Amount) For Period IN([Jan],[Feb],[Mar],[Apr],[May],[Jun],[Jul],[Aug],[Sep],[Oct],[Nov],[Dec]) ) as pivot_table";

            }

            else if (index == 3 || index == 8)
            {

                query = "  select idno,isnull(PartNo,'') as Partno,isnull(LinkNo,'') as LinkNo,isnull(Description,'') as Description, isnull(Jan,0) as Jan,isnull(Feb,0) as Feb,isnull(Mar,0) as Mar,isnull(Apr,0) as Apr, " +
                      "  isnull(May,0) as May,isnull(Jun,0) as Jun,isnull(Jul,0)as Jul,isnull(Aug,0) as Aug,isnull(Sep,0) as Sep,isnull(Oct,0) as Oct,isnull(Nov,0) as Nov, " +
                      "  isnull(Dec,0) as Dec, " +
                      "  isnull(Jan,0) +isnull(Feb,0)+isnull(Mar,0)+isnull(Apr,0)+isnull(May,0)+isnull(Jun,0) +isnull(Jul,0)+isnull(Aug,0) +isnull(Sep,0) " +
                      "  +isnull(Oct,0) +isnull(Nov,0) + isnull(Dec,0) as Total " +
                      "  from (select Cast( DateName( month , DateAdd( month ,MONTH(sm.clkdate) , -1 )) as Varchar(3)) as Period, " +
                      " im.idno, isnull(im.partno,'') as PartNo,isnull(im.partno,'') as LinkNo,isnull(im.desc1,'') as Description,sum(sm.citmno) as[Amount] from " + Master + " sm inner join " + Child + " sd on sm.key_pk=sd.key_fk " +
                     " inner join ac on ac.code=sm.acode left join city on city.code=ac.city_code left join itemlinked im on im.idno=sd.acitno " +
                     " left  join origin on origin.code=im.origin  left join brand on brand.code=im.brnad  left join item on item.code=im.part  " +
                     " left join model on model.id=im.model_maker left join maker on maker.code=model.maker left join reference rf on rf.code=item.reference  " +
                     where + "  group by YEAR(sm.clkdate)*100 + MONTH(sm.clkdate),Cast( DateName( month , DateAdd( month ,MONTH(sm.clkdate) , -1 )) as Varchar(3)),im.idno,im.partno,im.linkno,im.desc1" +
                     " ) t pivot (Sum(Amount) For Period IN([Jan],[Feb],[Mar],[Apr],[May],[Jun],[Jul],[Aug],[Sep],[Oct],[Nov],[Dec]) ) as pivot_table";

            }

            else if (index == 4 || index == 9)
            {

                query = "  select isnull(Code,'') as Code,isnull(Title,'') as Name, isnull(Jan,0) as Jan,isnull(Feb,0) as Feb,isnull(Mar,0) as Mar,isnull(Apr,0) as Apr, " +
                      "  isnull(May,0) as May,isnull(Jun,0) as Jun,isnull(Jul,0)as Jul,isnull(Aug,0) as Aug,isnull(Sep,0) as Sep,isnull(Oct,0) as Oct,isnull(Nov,0) as Nov, " +
                      "  isnull(Dec,0) as Dec, " +
                      "  isnull(Jan,0) +isnull(Feb,0)+isnull(Mar,0)+isnull(Apr,0)+isnull(May,0)+isnull(Jun,0) +isnull(Jul,0)+isnull(Aug,0) +isnull(Sep,0) " +
                      "  +isnull(Oct,0) +isnull(Nov,0) + isnull(Dec,0) as Total " +
                      "  from (select Cast( DateName( month , DateAdd( month ,MONTH(sm.clkdate) , -1 )) as Varchar(3)) as Period, " +
                       " city.code as Code,city.name as Title,sum(sm.ttlamtnet) as[Amount] from " + Master + " sm inner join " + Child + " sd on sm.key_pk=sd.key_fk " +
                      " inner join ac on ac.code=sm.acode left join city on city.code=ac.city_code left join itemlinked im on im.idno=sd.acitno " +
                      " left  join origin on origin.code=im.origin  left join brand on brand.code=im.brnad  left join item on item.code=im.part  " +
                      " left join model on model.id=im.model_maker left join maker on maker.code=model.maker left join reference rf on rf.code=item.reference  " +
                      where + "  group by YEAR(sm.clkdate)*100 + MONTH(sm.clkdate),Cast( DateName( month , DateAdd( month ,MONTH(sm.clkdate) , -1 )) as Varchar(3)),city.code,city.name" +
                      " ) t pivot (Sum(Amount) For Period IN([Jan],[Feb],[Mar],[Apr],[May],[Jun],[Jul],[Aug],[Sep],[Oct],[Nov],[Dec]) ) as pivot_table  Order By Name";
            }

            return IList_GetTable(query);
        }

        public String Report_ReOrder2(String json)
        {
            JObject json_Object = JObject.Parse(json);
            int index = Convert.ToInt32(json_Object["index"].ToString());
            String from = json_Object["from"].ToString();
            String to = json_Object["to"].ToString();
            String type = Convert.ToString(json_Object["type"]);

            String from2 = DateTime.ParseExact(from, "yyyy-MM-dd", CultureInfo.InvariantCulture).ToString("MM-dd-yyyy");
            String to2 = DateTime.ParseExact(to, "yyyy-MM-dd", CultureInfo.InvariantCulture).ToString("MM-dd-yyyy");
            String query = "";
            String Master = json_Object["Master"].ToString();
            String Child = json_Object["Child"].ToString();
            String where = " where  CAST(sm.clkdate AS DATE) >= CAST( '" + from + "' AS DATE)  AND CAST(sm.clkdate AS DATE) <= CAST( '" + to + "' AS DATE) ";
            String where2 = " where  CAST(sm.clkdate AS DATE) >= CAST( ''" + from + "'' AS DATE)  AND CAST(sm.clkdate AS DATE) <= CAST( ''" + to + "'' AS DATE) ";

            if (json_Object["acode"].ToString() != String.Empty)
            {
                where += " and ac.code='" + json_Object["acode"].ToString().Trim() + "'";
                where2 += " and ac.code=''" + json_Object["acode"].ToString().Trim() + "'' ";
            }

            if (json_Object["city"].ToString() != String.Empty)
            {
                where += " and city.code='" + json_Object["city"].ToString().Trim() + "'";
                where2 += " and city.code=''" + json_Object["city"].ToString().Trim() + "'' ";
            }
            if (json_Object["item"].ToString() != String.Empty)
            {
                where += " and item.code='" + json_Object["item"].ToString().Trim() + "'";
                where2 += " and item.code=''" + json_Object["item"].ToString().Trim() + "'' ";
            }
            if (json_Object["partno"].ToString() != String.Empty)
            {
                where += " and im.idno=" + json_Object["partno"].ToString().Trim();
                where2 += " and im.idno=" + json_Object["partno"].ToString().Trim();
            }
            if (json_Object["origin"].ToString() != String.Empty)
            {
                where += " and origin.code='" + json_Object["origin"].ToString().Trim() + "'";
                where2 += " and origin.code=''" + json_Object["origin"].ToString().Trim() + "''";
            }
            if (json_Object["brand"].ToString() != String.Empty)
            {
                where += " and brand.code='" + json_Object["brand"].ToString().Trim() + "'";
                where2 += " and brand.code=''" + json_Object["brand"].ToString().Trim() + "''";
            }
            if (json_Object["model"].ToString() != String.Empty)
            {
                where += " and model.code='" + json_Object["model"].ToString().Trim() + "'";
                where2 += " and model.code=''" + json_Object["model"].ToString().Trim() + "''";
            }
            if (json_Object["maker"].ToString() != String.Empty)
            {
                where += " and maker.code='" + json_Object["maker"].ToString().Trim() + "'";
                where2 += " and maker.code=''" + json_Object["maker"].ToString().Trim() + "''";
            }
            if (json_Object["reference"].ToString() != String.Empty)
            {
                where += " and rf.code='" + json_Object["reference"].ToString().Trim() + "'";
                where2 += " and rf.code=''" + json_Object["reference"].ToString().Trim() + "''";
            }

            if (type.Trim() == "Pending")
            {
                where += " and sm.closed=0 ";
            }

            if (type.Trim() == "Closed")
            {
                where += " and sm.closed=1 ";
            }

            query = "  select distinct sm.key_pk as [Computrized_No],sm.invoice_no as [Invno],FORMAT(Cast( sm.clkdate as Date), 'dd-MM-yyyy') as [InvDate],city.name as [City],sd.invdesc as invDesc,sd.prtno as PartNo,sd.bn as Brand, " +
                       " sd.qty as [Qty],sd.Rate,(sd.amt) as [Amount],(sd.disc) as [DiscAmount],(sd.amt-sd.disc+gsta) as [NetAmount] from " + Master + " sm inner join " + Child + " sd on sm.key_pk=sd.key_fk  " +
                       " left join ac on ac.code=sm.acode left join city on city.code=ac.city_code  left join itemlinked im on im.idno=sd.acitno " +
                       " left  join origin on origin.code=im.origin  left join brand on brand.code=im.brnad left join item on item.code=im.part " +
                       " left join model on model.id=im.model_maker  left join maker on maker.code=model.maker left join reference rf on rf.code=item.reference " +
                        where + " order by Invno,InvDate";



            return IList_GetTable(query);
        }

        public String Report_Load_Quotation(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String iden = json_Object["iden"].ToString();

            String query = "Select code,title,city_code from ac where iden='" + iden + "' order by title;" +
                         " Select code as Code,name as Name,short_code as Short_Code from maker order by Name;" +
                         "  select code as Code,name as Name from brand order by Name;" +
                         "  Select item.code as Code,item.name as Name  from Item  order by name;" +
                         " Select code as Code,name as Name,short_code as Short_Code from origin ;" +
                         " select Code,Name from reference;" +
                         " Select * from Model;" +
                         "Select * from city order by name" +
                         " select distinct vn_number from Quotation_Master ;" +
                           " select distinct reg_number from Quotation_Master ; " +
                           " select distinct contactno from Quotation_Master ;";




            return IList_GetDataSet(query);

        }

        public String Report_Load(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String iden = json_Object["iden"].ToString();

            String query = "Select code,title,city_code from ac where iden='" + iden + "' order by title;" +
                         " Select code as Code,name as Name,short_code as Short_Code from maker order by Name;" +
                         "  select code as Code,name as Name from brand order by Name;" +
                         "  Select item.code as Code,item.name as Name  from Item  order by name;" +
                         " Select code as Code,name as Name,short_code as Short_Code from origin ;" +
                         " select Code,Name from reference;" +
                         " Select * from Model;" +
                         "Select * from city order by name";




            return IList_GetDataSet(query);

        }

        public String Order_Insert(String json)
        {

            JObject json_object = JObject.Parse(json);
            String child = json_object["Child"].ToString();
            DataTable table = (DataTable)JsonConvert.DeserializeObject(child, (typeof(DataTable)));
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            String type = json_object["Type"].ToString();
            String date = json_object["edate"].ToString();
            String warehouse = json_object["warehouse"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int invno = 0;
            int key = 0;
            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;

            String detail = " insert into " + json_object["Detail"] + "(key_fk,citmno,acitno,prtno,bn,invdesc,subdesc,qty,rate,amt,dscrate,dscr_p,disc,ntamt) values "
                             + " (@key,@sno,@item,@partno,@brand,@desc,@sub,@qty,@rate,@amt,@disc_rate,@disc_p,@disc,@amount)";

            String Order1 = " insert into " + json_object["Master"] + "(key_pk,invtype,clkdate,date,invoice_no,mrdminv_no,acode,c_code,duedate,days,prtclar,warehouse,amtgrs,disc,expmnininv,courier,amtnet,gstp,gsta,amtnetwgst,itp,ita,na_w_itax,ttlamtnet,citmno,quotation_no,closed,users) values ";
            String Order2 = " (@key_pk,@invtype,@edate,@date,@invoice,@vno,@debit,@credit,@duedate,@days,@remarks,@warehouse,@gross,@disc,@expense,@courier,@net,@gstp,@gsta,@gst_amt,@itp,@itpa,@itp_amt,@total,@qty,@quotation_no,@closed,@users); ";
            String OrderMaster = Order1 + Order2;




            String Select_Master = "select distinct  sm.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=";

            String Select_Child = "select distinct  sd.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=";
            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();



                    using (cm = new SqlCommand(" select top 1 invoice_no from " + json_object["Master"] + "  order by invoice_no desc;", con, trans))
                    {

                        invno = Convert.ToInt32(cm.ExecuteScalar()) + 1;
                    }

                    using (cm = new SqlCommand(" select top 1 key_pk from " + json_object["Master"] + " order by invoice_no desc;", con, trans))
                    {

                        key = Convert.ToInt32(cm.ExecuteScalar()) + 1;
                    }

                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {

                        cm.Parameters.AddWithValue("key_pk", key);
                        cm.Parameters.AddWithValue("invtype", json_object["invtype"].ToString());
                        cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("date", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("invoice", invno);
                        cm.Parameters.AddWithValue("vno", json_object["vno"].ToString());
                        cm.Parameters.AddWithValue("debit", json_object["debit"].ToString() == String.Empty ? (Object)DBNull.Value : json_object["debit"].ToString());
                        cm.Parameters.AddWithValue("credit", json_object["credit"].ToString());
                        cm.Parameters.AddWithValue("duedate", json_object["days"].ToString() == String.Empty ? (Object)DBNull.Value : json_object["duedate"].ToString());
                        cm.Parameters.AddWithValue("days", json_object["days"].ToString() == String.Empty ? (Object)DBNull.Value : Convert.ToInt32(json_object["days"].ToString()));
                        cm.Parameters.AddWithValue("remarks", json_object["remarks"].ToString());
                        cm.Parameters.AddWithValue("warehouse", warehouse == String.Empty ? (Object)DBNull.Value : warehouse);
                        cm.Parameters.AddWithValue("gross", json_object["gross"].ToString());
                        cm.Parameters.AddWithValue("disc", json_object["disc_amt"].ToString());
                        cm.Parameters.AddWithValue("expense", json_object["freight"].ToString());
                        cm.Parameters.AddWithValue("courier", json_object["courier"].ToString());
                        cm.Parameters.AddWithValue("net", json_object["net_amt"].ToString());
                        cm.Parameters.AddWithValue("gstp", json_object["gst_per"].ToString());
                        cm.Parameters.AddWithValue("gsta", json_object["gst_val"].ToString());
                        cm.Parameters.AddWithValue("gst_amt", json_object["gstnet"].ToString());
                        cm.Parameters.AddWithValue("itp", json_object["it_per"].ToString());
                        cm.Parameters.AddWithValue("itpa", json_object["it_val"].ToString());
                        cm.Parameters.AddWithValue("itp_amt", json_object["itnet"].ToString());
                        cm.Parameters.AddWithValue("total", json_object["total"].ToString());
                        cm.Parameters.AddWithValue("qty", json_object["qty"].ToString());
                        cm.Parameters.AddWithValue("quotation_no", json_object["quotation_no"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["quotation_no"].ToString()));
                        cm.Parameters.AddWithValue("closed", json_object["closed"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["closed"].ToString()));
                        cm.Parameters.AddWithValue("users", json_object["UserId"] == null ? (Object)DBNull.Value : Convert.ToString(json_object["UserId"].ToString()));
                        rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());

                    }
                    if (rowseffected > 0)
                    {

                        using (cm = new SqlCommand(detail, con, trans))
                        {
                            cm.Parameters.Add("key", SqlDbType.Int);
                            cm.Parameters.Add("sno", SqlDbType.Int);
                            cm.Parameters.Add("item", SqlDbType.Int);
                            cm.Parameters.Add("partno", SqlDbType.VarChar);
                            cm.Parameters.Add("brand", SqlDbType.VarChar);
                            cm.Parameters.Add("desc", SqlDbType.VarChar);
                            cm.Parameters.Add("sub", SqlDbType.VarChar);
                            cm.Parameters.Add("qty", SqlDbType.Decimal);
                            cm.Parameters.Add("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amt", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_p", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("amount", SqlDbType.Decimal);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["sno"].Value = Convert.ToInt32(row["sno"]);
                                cm.Parameters["item"].Value = Convert.ToInt32(row["item"]);
                                cm.Parameters["partno"].Value = Convert.ToString(row["partno"]);
                                cm.Parameters["brand"].Value = Convert.ToString(row["brand"]);
                                cm.Parameters["desc"].Value = Convert.ToString(row["desc"]);
                                cm.Parameters["sub"].Value = Convert.ToString(row["sub"]);
                                cm.Parameters["qty"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["rate"].Value = Convert.ToDecimal(row["rate"]);
                                cm.Parameters["amt"].Value = Convert.ToDecimal(row["amount"]);
                                cm.Parameters["disc_rate"].Value = Convert.ToDecimal(row["disc_rate"]);
                                cm.Parameters["disc_p"].Value = Convert.ToDecimal(row["disc_per"]);
                                cm.Parameters["disc"].Value = Convert.ToDecimal(row["disc_amt"]);
                                cm.Parameters["amount"].Value = Convert.ToDecimal(row["net_amt"]);

                                rowseffected += cm.ExecuteNonQuery();

                            }


                        }


                        if (rowseffected > 0)
                        {

                            Select_Master += invno;
                            Select_Child += invno;


                            using (adp = new SqlDataAdapter(Select_Master + ";" + Select_Child, con))
                            {
                                adp.SelectCommand.Transaction = trans;

                                cmd = new SqlCommandBuilder(adp);
                                adp.Fill(dt);
                                dt.Tables[0].TableName = "Master";
                                dt.Tables[1].TableName = "Child";

                            }

                            String JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                            using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invno + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + (User) + "','" + (system) + "','New Entry','" + JSONString + "')", con, trans))
                            {

                                rows = cm.ExecuteNonQuery();

                            }

                            if (rows > 0)
                            {

                                trans.Commit();
                                IsInsert = invno;

                            }
                            else
                            {
                                trans.Rollback();
                                IsInsert = 0;
                            }

                        }
                        else
                        {
                            trans.Rollback();
                            IsInsert = 0;
                        }

                    }
                    else
                    {
                        trans.Rollback();
                        IsInsert = 0;

                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                response = ex.Message;
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }

            return IsInsert.ToString();


        }

        public String Order_Update(String json)
        {

            JObject json_object = JObject.Parse(json);
            String child = json_object["Child"].ToString();
            DataTable table = (DataTable)JsonConvert.DeserializeObject(child, (typeof(DataTable)));
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            int key = Convert.ToInt32(json_object["key"].ToString());
            String type = json_object["Type"].ToString();
            String date = json_object["edate"].ToString();
            String warehouse = json_object["warehouse"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int invno = Convert.ToInt32(json_object["inv"].ToString());
            String delete_detail = "Delete from " + json_object["Detail"] + " where key_fk=" + key + ";";

            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;

            String detail = " insert into " + json_object["Detail"] + "(key_fk,citmno,acitno,prtno,bn,invdesc,subdesc,qty,rate,amt,dscrate,dscr_p,disc,ntamt) values "
                           + " (@key,@sno,@item,@partno,@brand,@desc,@sub,@qty,@rate,@amt,@disc_rate,@disc_p,@disc,@amount)";


            String OrderMaster = "  Update " + json_object["Master"] + " set invtype=@invtype,clkdate=@edate,date=@edate,mrdminv_no=@vno,acode=@debit,c_code=@credit,duedate=@duedate,days=@days,prtclar=@remarks," +
                                 "  warehouse=@warehouse,amtgrs=@gross,disc=@disc,expmnininv=@expense,courier=@courier,amtnet=@net,gstp=@gstp,gsta=@gsta,amtnetwgst=@gst_amt," +
                                 "  itp=@itp,ita=@itpa,na_w_itax=@itp_amt,ttlamtnet=@total,closed=@closed where key_pk=@key_pk";

            String Select_Master = "select distinct  sm.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

            String Select_Child = "select distinct  sd.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;



            DataTable st = new DataTable();
            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();


                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {

                        cm.Parameters.AddWithValue("key_pk", key);
                        cm.Parameters.AddWithValue("invtype", json_object["invtype"].ToString());
                        cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("invoice", invno);
                        cm.Parameters.AddWithValue("vno", json_object["vno"].ToString());
                        cm.Parameters.AddWithValue("debit", json_object["debit"].ToString() == String.Empty ? (Object)DBNull.Value : json_object["debit"].ToString());
                        cm.Parameters.AddWithValue("credit", json_object["credit"].ToString());
                        cm.Parameters.AddWithValue("duedate", json_object["days"].ToString() == String.Empty ? (Object)DBNull.Value : json_object["duedate"].ToString());
                        cm.Parameters.AddWithValue("days", json_object["days"].ToString() == String.Empty ? (Object)DBNull.Value : Convert.ToInt32(json_object["days"].ToString()));
                        cm.Parameters.AddWithValue("remarks", json_object["remarks"].ToString());
                        cm.Parameters.AddWithValue("warehouse", json_object["warehouse"].ToString());
                        cm.Parameters.AddWithValue("gross", json_object["gross"].ToString());
                        cm.Parameters.AddWithValue("disc", json_object["disc_amt"].ToString());
                        cm.Parameters.AddWithValue("expense", json_object["freight"].ToString());
                        cm.Parameters.AddWithValue("courier", json_object["courier"].ToString());
                        cm.Parameters.AddWithValue("net", json_object["net_amt"].ToString());
                        cm.Parameters.AddWithValue("gstp", json_object["gst_per"].ToString());
                        cm.Parameters.AddWithValue("gsta", json_object["gst_val"].ToString());
                        cm.Parameters.AddWithValue("gst_amt", json_object["gstnet"].ToString());
                        cm.Parameters.AddWithValue("itp", json_object["it_per"].ToString());
                        cm.Parameters.AddWithValue("itpa", json_object["it_val"].ToString());
                        cm.Parameters.AddWithValue("itp_amt", json_object["itnet"].ToString());
                        cm.Parameters.AddWithValue("total", json_object["total"].ToString());
                        cm.Parameters.AddWithValue("closed", json_object["closed"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["closed"].ToString()));


                        rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());

                    }
                    if (rowseffected > 0)
                    {

                        using (cm = new SqlCommand(delete_detail, con, trans))
                        {

                            cm.ExecuteNonQuery();

                        }
                        using (cm = new SqlCommand(detail, con, trans))
                        {
                            cm.Parameters.Add("key", SqlDbType.Int);
                            cm.Parameters.Add("sno", SqlDbType.Int);
                            cm.Parameters.Add("item", SqlDbType.Int);
                            cm.Parameters.Add("partno", SqlDbType.VarChar);
                            cm.Parameters.Add("brand", SqlDbType.VarChar);
                            cm.Parameters.Add("desc", SqlDbType.VarChar);
                            cm.Parameters.Add("sub", SqlDbType.VarChar);
                            cm.Parameters.Add("qty", SqlDbType.Decimal);
                            cm.Parameters.Add("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amt", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_p", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("amount", SqlDbType.Decimal);


                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["sno"].Value = Convert.ToInt32(row["sno"]);
                                cm.Parameters["item"].Value = Convert.ToInt32(row["item"]);
                                cm.Parameters["partno"].Value = Convert.ToString(row["partno"]);
                                cm.Parameters["brand"].Value = Convert.ToString(row["brand"]);
                                cm.Parameters["desc"].Value = Convert.ToString(row["desc"]);
                                cm.Parameters["sub"].Value = Convert.ToString(row["sub"]);
                                cm.Parameters["qty"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["rate"].Value = Convert.ToDecimal(row["rate"]);
                                cm.Parameters["amt"].Value = Convert.ToDecimal(row["amount"]);
                                cm.Parameters["disc_rate"].Value = Convert.ToDecimal(row["disc_rate"]);
                                cm.Parameters["disc_p"].Value = Convert.ToDecimal(row["disc_per"]);
                                cm.Parameters["disc"].Value = Convert.ToDecimal(row["disc_amt"]);
                                cm.Parameters["amount"].Value = Convert.ToDecimal(row["net_amt"]);
                                rowseffected += cm.ExecuteNonQuery();

                            }


                        }


                        if (rowseffected > 0)
                        {
                            {

                                using (adp = new SqlDataAdapter(Select_Master + ";" + Select_Child, con))
                                {
                                    adp.SelectCommand.Transaction = trans;

                                    cmd = new SqlCommandBuilder(adp);
                                    adp.Fill(dt);
                                    dt.Tables[0].TableName = "Master";
                                    dt.Tables[1].TableName = "Child";

                                }

                                String JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                                using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invno + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + User + "','" + system + "','Modified Entry','" + JSONString + "')", con, trans))
                                {

                                    rows = cm.ExecuteNonQuery();

                                }

                                if (rows > 0)
                                {

                                    trans.Commit();
                                    IsInsert = key;

                                }
                                else
                                {
                                    trans.Rollback();
                                    IsInsert = 0;
                                }
                            }


                        }
                        else
                        {
                            trans.Rollback();
                            IsInsert = 0;
                        }

                    }
                    else
                    {
                        trans.Rollback();
                        IsInsert = 0;

                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                response = ex.Message;
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }

            return IsInsert.ToString();


        }

        public int Order_Delete(String jsondata)
        {
            int IsDelete = 0;
            JObject json_object = JObject.Parse(jsondata);
            int invoice = Convert.ToInt32(json_object["inv"].ToString());
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            int key = Convert.ToInt32(json_object["key"].ToString());
            String type = json_object["Type"].ToString();
            DataTable st = new DataTable();

            String Select_Master = "select distinct  sm.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

            String Select_Child = "select distinct  sd.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;



            String select = Select_Master + ";" + Select_Child;
            SqlTransaction trans = null;
            String json = "";

            String delete_detail = "Delete from " + json_object["Detail"] + " where key_fk=" + key + ";";


            String delete_master = "Delete from " + json_object["Master"] + " where key_pk=" + key + ";";

            String delete = delete_detail + ";" + delete_master;

            DataSet ds = new DataSet();

            try
            {
                using (con = new SqlConnection(cs))
                {
                    con.Open();

                    using (adp = new SqlDataAdapter("Select acitno as item from " + json_object["Detail"] + " where key_fk=" + key, con))
                    {
                        adp.SelectCommand.Transaction = trans;
                        cmd = new SqlCommandBuilder(adp);
                        adp.Fill(st);

                    }

                    using (adp = new SqlDataAdapter(select, con))
                    {
                        cmd = new SqlCommandBuilder(adp);
                        adp.Fill(ds);
                        json = JsonConvert.SerializeObject(ds.Tables[0]);
                        var obj = new { Master = json, Child = JsonConvert.SerializeObject(ds.Tables[1]) };
                        json = JsonConvert.SerializeObject(obj);
                    }

                    trans = con.BeginTransaction();

                    using (cm = new SqlCommand("Insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invoice + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + User + "','" + system + "','Delete Entry','" + json + "')", con, trans))
                    {
                        cm.ExecuteNonQuery();
                    }


                    using (cm = new SqlCommand(delete, con, trans))
                    {
                        int a = cm.ExecuteNonQuery();
                        if (a > 0)
                        {
                            trans.Commit();
                            Update_Stock(st);
                            IsDelete = invoice;

                        }
                        else
                        {
                            trans.Rollback();
                            IsDelete = 0;

                        }
                    }

                }

            }
            catch (SqlException ex)
            {
                excp(ex.Message);

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
            return IsDelete;
        }

        public String Stock_Transfer_Insert(String json)
        {

            JObject json_object = JObject.Parse(json);
            String child = json_object["Child"].ToString();
            DataTable table = (DataTable)JsonConvert.DeserializeObject(child, (typeof(DataTable)));
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            String type = json_object["Type"].ToString();
            String date = json_object["edate"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int invno = 0;
            int key = 0;
            int entryno = 0;
            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;

            String detail = " insert into " + json_object["Detail"] + "(key_fk,citmno,acitno,prtno,bn,invdesc,tfq,tflctncd,ttq,ttlctncd,remarks) values "
                             + " (@key,@sno,@item,@partno,@brand,@desc,@qty,@from,@qty,@to,@remarks)";

            String stock1 = "insert into stock(pidno,cidno,edate,refno,estatus,product,description,rec,warehouse,remarks) " +
                           "  values (@key,(select SCOPE_IDENTITY()),@edate,@refno,@type,@item,@desc,@rec,@to,@remarks);";

            String stock2 = "insert into stock(pidno,cidno,edate,refno,estatus,product,description,iss,warehouse,remarks) " +
                       "  values (@key,(select SCOPE_IDENTITY()),@edate,@refno,@type,@item,@desc,@iss,@from,@remarks);";

            String stock = stock1 + stock2;

            String Order1 = " insert into " + json_object["Master"] + "(key_pk,clkdate,date,invoice_no,mrdminv_no,citmno,remarks) values ";
            String Order2 = " (@key_pk,@edate,@date,@invoice,@vno,@qty,@remarks); ";
            String OrderMaster = Order1 + Order2;


            String Select_Master = "select distinct  sm.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=";

            String Select_Child = "select distinct  sd.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=";

            //  String update_items = " update itemlinked set remarks=@remarks where idno=@item";
            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();

                    using (cm = new SqlCommand("select top 1 isnull(entryno,0)+1 from Ledger order by entryno desc;", con, trans))
                    {

                        entryno = Convert.ToInt32(cm.ExecuteScalar());
                    }

                    using (cm = new SqlCommand(" select top 1 invoice_no from " + json_object["Master"] + " order by invoice_no desc;", con, trans))
                    {

                        invno = Convert.ToInt32(cm.ExecuteScalar()) + 1;
                    }

                    using (cm = new SqlCommand(" select top 1 key_pk from " + json_object["Master"] + " order by invoice_no desc;", con, trans))
                    {

                        key = Convert.ToInt32(cm.ExecuteScalar()) + 1;
                    }

                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {
                        cm.Parameters.AddWithValue("key_pk", key);
                        cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("date", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("invoice", invno);
                        cm.Parameters.AddWithValue("vno", json_object["vno"].ToString());
                        cm.Parameters.AddWithValue("qty", json_object["qty"].ToString());
                        cm.Parameters.AddWithValue("remarks", json_object["remarks"].ToString());

                        rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());

                    }

                    if (rowseffected > 0)
                    {

                        using (cm = new SqlCommand(detail + ";" + stock, con, trans))
                        {


                            cm.Parameters.Add("key", SqlDbType.Int);
                            cm.Parameters.Add("sno", SqlDbType.Int);
                            cm.Parameters.Add("item", SqlDbType.Int);
                            cm.Parameters.Add("partno", SqlDbType.VarChar);
                            cm.Parameters.Add("brand", SqlDbType.VarChar);
                            cm.Parameters.Add("desc", SqlDbType.VarChar);
                            cm.Parameters.Add("qty", SqlDbType.Decimal);
                            cm.Parameters.Add("from", SqlDbType.Int);
                            cm.Parameters.Add("to", SqlDbType.Int);
                            cm.Parameters.Add("remarks", SqlDbType.VarChar);

                            cm.Parameters.Add("edate", SqlDbType.DateTime);
                            cm.Parameters.Add("refno", SqlDbType.Int);
                            cm.Parameters.Add("type", SqlDbType.VarChar);
                            cm.Parameters.Add("rec", SqlDbType.Decimal);
                            cm.Parameters.Add("iss", SqlDbType.Decimal);



                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["sno"].Value = Convert.ToInt32(row["sno"]);
                                cm.Parameters["item"].Value = Convert.ToInt32(row["item"]);
                                cm.Parameters["partno"].Value = Convert.ToString(row["partno"]);
                                cm.Parameters["brand"].Value = Convert.ToString(row["brand"]);
                                cm.Parameters["desc"].Value = Convert.ToString(row["desc"]);
                                cm.Parameters["qty"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["from"].Value = Convert.ToInt32(row["from_id"]);
                                cm.Parameters["to"].Value = Convert.ToInt32(row["to_id"]);
                                cm.Parameters["remarks"].Value = Convert.ToString(row["remarks"]);


                                cm.Parameters["edate"].Value = date;
                                cm.Parameters["refno"].Value = invno;
                                cm.Parameters["type"].Value = type;
                                cm.Parameters["rec"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["iss"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["from"].Value = Convert.ToInt32(row["from_id"]);
                                cm.Parameters["to"].Value = Convert.ToInt32(row["to_id"]);


                                rowseffected += cm.ExecuteNonQuery();

                            }


                        }

                        if (rowseffected > 0)
                        {
                            {
                                Select_Master += invno;
                                Select_Child += invno;


                                using (adp = new SqlDataAdapter(Select_Master + ";" + Select_Child, con))
                                {
                                    adp.SelectCommand.Transaction = trans;

                                    cmd = new SqlCommandBuilder(adp);
                                    adp.Fill(dt);
                                    dt.Tables[0].TableName = "Master";
                                    dt.Tables[1].TableName = "Child";

                                }

                                String JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                                using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invno + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + (User) + "','" + (system) + "','New Entry','" + JSONString + "')", con, trans))
                                {

                                    rows = cm.ExecuteNonQuery();

                                }

                                if (rows > 0)
                                {

                                    IsInsert = invno;
                                    trans.Commit();
                                }
                                else
                                {
                                    trans.Rollback();
                                    IsInsert = 0;
                                }
                            }


                        }

                        else
                        {
                            trans.Rollback();
                            IsInsert = 0;
                        }

                    }
                    else
                    {
                        trans.Rollback();
                        IsInsert = 0;

                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                response = ex.Message;
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }

            /* if (IsInsert > 0)
             {
                 String invoice = " select distinct om.entry from OrderMaster om,order_detail od where om.Entry=od.MEntry and om.estatus='SV' order by om.Entry;";
                 response = IList_GetTable(invoice);
             }*/
            return IsInsert.ToString();


        }

        public String Stock_Transfer_Update(String json)
        {

            JObject json_object = JObject.Parse(json);
            String child = json_object["Child"].ToString();
            DataTable table = (DataTable)JsonConvert.DeserializeObject(child, (typeof(DataTable)));
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            int key = Convert.ToInt32(json_object["key"].ToString());
            String type = json_object["Type"].ToString();
            String date = json_object["edate"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int invno = Convert.ToInt32(json_object["inv"].ToString());

            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;

            String detail = " insert into " + json_object["Detail"] + "(key_fk,citmno,acitno,prtno,bn,invdesc,tfq,tflctncd,ttq,ttlctncd,remarks) values "
                            + " (@key,@sno,@item,@partno,@brand,@desc,@qty,@from,@qty,@to,@remarks)";

            String stock1 = "insert into stock(pidno,cidno,edate,refno,estatus,product,description,rec,warehouse,remarks) " +
                           "  values (@key,(select SCOPE_IDENTITY()),@edate,@refno,@type,@item,@desc,@rec,@to,@remarks);";

            String stock2 = "insert into stock(pidno,cidno,edate,refno,estatus,product,description,iss,warehouse,remarks) " +
                       "  values (@key,(select SCOPE_IDENTITY()),@edate,@refno,@type,@item,@desc,@iss,@from,@remarks);";

            String stock = stock1 + stock2;

            String OrderMaster = "  Update " + json_object["Master"] + " set clkdate=@edate,date=@edate,mrdminv_no=@vno,remarks=@remarks,citmno=@qty" +
                                 "   where key_pk=@key_pk";


            String Select_Master = "select distinct  sm.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

            String Select_Child = "select distinct  sd.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

            String delete_detail = "Delete from " + json_object["Detail"] + " where key_fk=" + key + ";";


            String delete_stock = "Delete from stock where estatus='" + type + "' and pidno=" + key + ";";

            String delete = delete_detail + delete_stock;

            String update_items = " ";
            SqlCommand cmd2 = new SqlCommand();

            DataTable st = new DataTable();
            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();


                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {

                        cm.Parameters.AddWithValue("key_pk", key);
                        cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("date", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        cm.Parameters.AddWithValue("vno", json_object["vno"].ToString());
                        cm.Parameters.AddWithValue("qty", json_object["qty"].ToString());
                        cm.Parameters.AddWithValue("remarks", json_object["remarks"].ToString());
                        rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());

                    }
                    if (rowseffected > 0)
                    {

                        using (cm = new SqlCommand(delete, con, trans))
                        {

                            cm.ExecuteNonQuery();

                        }


                        using (cm = new SqlCommand(detail + ";" + stock, con, trans))
                        {


                            cm.Parameters.Add("key", SqlDbType.Int);
                            cm.Parameters.Add("sno", SqlDbType.Int);
                            cm.Parameters.Add("item", SqlDbType.Int);
                            cm.Parameters.Add("partno", SqlDbType.VarChar);
                            cm.Parameters.Add("brand", SqlDbType.VarChar);
                            cm.Parameters.Add("desc", SqlDbType.VarChar);
                            cm.Parameters.Add("sub", SqlDbType.VarChar);
                            cm.Parameters.Add("qty", SqlDbType.Decimal);
                            cm.Parameters.Add("from", SqlDbType.Int);
                            cm.Parameters.Add("to", SqlDbType.Int);
                            cm.Parameters.Add("remarks", SqlDbType.VarChar);

                            cm.Parameters.Add("edate", SqlDbType.DateTime);
                            cm.Parameters.Add("refno", SqlDbType.Int);
                            cm.Parameters.Add("type", SqlDbType.VarChar);
                            cm.Parameters.Add("rec", SqlDbType.Decimal);
                            cm.Parameters.Add("iss", SqlDbType.Decimal);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["sno"].Value = Convert.ToInt32(row["sno"]);
                                cm.Parameters["item"].Value = Convert.ToInt32(row["item"]);
                                cm.Parameters["partno"].Value = Convert.ToString(row["partno"]);
                                cm.Parameters["brand"].Value = Convert.ToString(row["brand"]);
                                cm.Parameters["desc"].Value = Convert.ToString(row["desc"]);
                                cm.Parameters["sub"].Value = Convert.ToString(row["sub"]);
                                cm.Parameters["qty"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["from"].Value = Convert.ToDecimal(row["from_id"]);
                                cm.Parameters["to"].Value = Convert.ToDecimal(row["to_id"]);
                                cm.Parameters["remarks"].Value = Convert.ToString(row["remarks"]);


                                cm.Parameters["edate"].Value = date;
                                cm.Parameters["refno"].Value = invno;
                                cm.Parameters["type"].Value = type;
                                cm.Parameters["rec"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["iss"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["from"].Value = Convert.ToInt32(row["from_id"]);
                                cm.Parameters["to"].Value = Convert.ToInt32(row["to_id"]);


                                rowseffected += cm.ExecuteNonQuery();

                                /*   cmd2.Connection = con;
                                   cmd2.Transaction = trans;
                                   cmd2.CommandText= "update itemlinked set remarks='"+ Convert.ToString(row["remarks"]) + "' where idno=" +Convert.ToInt32(row["item"]);
                                   cmd2.ExecuteNonQuery();*/

                            }


                        }

                        if (rowseffected > 0)
                        {
                            {

                                using (adp = new SqlDataAdapter(Select_Master + ";" + Select_Child, con))
                                {
                                    adp.SelectCommand.Transaction = trans;

                                    cmd = new SqlCommandBuilder(adp);
                                    adp.Fill(dt);
                                    dt.Tables[0].TableName = "Master";
                                    dt.Tables[1].TableName = "Child";

                                }

                                String JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                                using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invno + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + User + "','" + system + "','Modified Entry','" + JSONString + "')", con, trans))
                                {

                                    rows = cm.ExecuteNonQuery();

                                }

                                if (rows > 0)
                                {

                                    trans.Commit();
                                    Update_Stock(st);
                                    IsInsert = key;

                                }
                                else
                                {
                                    trans.Rollback();
                                    IsInsert = 0;
                                }
                            }


                        }
                        else
                        {
                            trans.Rollback();
                            IsInsert = 0;
                        }


                    }
                    else
                    {
                        trans.Rollback();
                        IsInsert = 0;

                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                response = ex.Message;
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }

            /* if (IsInsert > 0)
             {
                 String invoice = " select distinct om.entry from OrderMaster om,order_detail od where om.Entry=od.MEntry and om.estatus='SV' order by om.Entry;";
                 response = IList_GetTable(invoice);
             }*/
            return IsInsert.ToString();


        }

        public int Stock_Transfer_Delete(String jsondata)
        {
            int IsDelete = 0;
            JObject json_object = JObject.Parse(jsondata);
            int invoice = Convert.ToInt32(json_object["inv"].ToString());
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            int key = Convert.ToInt32(json_object["key"].ToString());
            String type = json_object["Type"].ToString();
            DataTable st = new DataTable();

            String Select_Master = "select distinct  sm.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

            String Select_Child = "select distinct  sd.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;


            String delete_stock = "Delete from stock where estatus='" + type + "' and pidno=" + key + ";";


            String select = Select_Master + ";" + Select_Child;
            SqlTransaction trans = null;
            String json = "";

            String delete_detail = "Delete from " + json_object["Detail"] + " where key_fk=" + key + ";";


            String delete_master = "Delete from " + json_object["Master"] + " where key_pk=" + key + ";";

            String delete = delete_stock + ";" + delete_detail + ";" + delete_master;

            DataSet ds = new DataSet();

            try
            {
                using (con = new SqlConnection(cs))
                {
                    con.Open();


                    trans = con.BeginTransaction();

                    using (cm = new SqlCommand("Insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invoice + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + User + "','" + system + "','Delete Entry','" + json + "')", con, trans))
                    {
                        cm.ExecuteNonQuery();
                    }


                    using (cm = new SqlCommand(delete, con, trans))
                    {
                        int a = cm.ExecuteNonQuery();
                        if (a > 0)
                        {
                            trans.Commit();
                            IsDelete = invoice;

                        }
                        else
                        {
                            trans.Rollback();
                            IsDelete = 0;

                        }
                    }

                }

            }
            catch (SqlException ex)
            {
                excp(ex.Message);

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
            return IsDelete;
        }

        public String LoadQuotation(String json)
        {
            JObject json_Object = JObject.Parse(json);

            String data = "";
            String query = " select id,name from warehouse order by name;" +
                           " select distinct vn_number from Quotation_Master ;" +
                           " select distinct reg_number from Quotation_Master ; " +
                           " select USERS,USERS_NAME from USERS where ISACTIVE=1 ORDER BY USERS_NAME;" +
                           " Select  1 key_pk,invoice_no from " + json_Object["Master"] + " Order By Key_pk desc;" +
                           " select count(key_pk) from " + json_Object["Master"] + ";" +
                           " select  title,code,iden from ac where type='Child'  order by title;" +
                            " select  idno,partno,linkno from itemlinked ;";

            data = IList_GetDataSet(query);
            return data;
        }


        public String Quotation_Insert(String json)
        {

            JObject json_object = JObject.Parse(json);
            String child = json_object["Child"].ToString();
            DataTable table = (DataTable)JsonConvert.DeserializeObject(child, (typeof(DataTable)));
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            String type = json_object["Type"].ToString();
            String date = json_object["edate"].ToString();
            String warehouse = json_object["warehouse"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int invno = 0;
            int key = 0;
            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;

            String detail = " insert into " + json_object["Detail"] + "(key_fk,citmno,acitno,prtno,bn,maker,model,invdesc,subdesc,qty,rate,amt,dscrate,dscr_p,disc,ntamt) values "
                             + " (@key,@sno,@item,@partno,@brand,@maker,@model,@desc,@sub,@qty,@rate,@amt,@disc_rate,@disc_p,@disc,@amount)";

            String Order1 = " insert into " + json_object["Master"] + "(key_pk,invtype,clkdate,date,invoice_no,mrdminv_no,acode,c_code,duedate,days,prtclar,warehouse,amtgrs,disc,expmnininv,courier,amtnet,gstp,gsta,amtnetwgst,itp,ita,na_w_itax,ttlamtnet,citmno,quotation_no,closed,users,vn_number,reg_number,name,contactno,email) values ";
            String Order2 = " (@key_pk,@invtype,@edate,@date,@invoice,@vno,@debit,@credit,@duedate,@days,@remarks,@warehouse,@gross,@disc,@expense,@courier,@net,@gstp,@gsta,@gst_amt,@itp,@itpa,@itp_amt,@total,@qty,@quotation_no,@closed,@users,@vn_number,@reg_number,@name,@contactno,@email); ";
            String OrderMaster = Order1 + Order2;




            String Select_Master = "select distinct  sm.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=";

            String Select_Child = "select distinct  sd.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=";
            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();



                    using (cm = new SqlCommand(" select top 1 invoice_no from " + json_object["Master"] + "  order by invoice_no desc;", con, trans))
                    {

                        invno = Convert.ToInt32(cm.ExecuteScalar()) + 1;
                    }

                    using (cm = new SqlCommand(" select top 1 key_pk from " + json_object["Master"] + " order by invoice_no desc;", con, trans))
                    {

                        key = Convert.ToInt32(cm.ExecuteScalar()) + 1;
                    }

                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {

                        cm.Parameters.AddWithValue("key_pk", key);
                        cm.Parameters.AddWithValue("invtype", json_object["invtype"].ToString());
                        cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("date", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("invoice", invno);
                        cm.Parameters.AddWithValue("vno", json_object["vno"].ToString());
                        cm.Parameters.AddWithValue("debit", json_object["debit"].ToString());
                        cm.Parameters.AddWithValue("credit", json_object["credit"].ToString());
                        cm.Parameters.AddWithValue("duedate", json_object["days"].ToString() == String.Empty ? (Object)DBNull.Value : json_object["duedate"].ToString());
                        cm.Parameters.AddWithValue("days", json_object["days"].ToString() == String.Empty ? (Object)DBNull.Value : Convert.ToInt32(json_object["days"].ToString()));
                        cm.Parameters.AddWithValue("remarks", json_object["remarks"].ToString());
                        cm.Parameters.AddWithValue("warehouse", warehouse == String.Empty ? (Object)DBNull.Value : warehouse);
                        cm.Parameters.AddWithValue("gross", json_object["gross"].ToString());
                        cm.Parameters.AddWithValue("disc", json_object["disc_amt"].ToString());
                        cm.Parameters.AddWithValue("expense", json_object["freight"].ToString());
                        cm.Parameters.AddWithValue("courier", json_object["courier"].ToString());
                        cm.Parameters.AddWithValue("net", json_object["net_amt"].ToString());
                        cm.Parameters.AddWithValue("gstp", json_object["gst_per"].ToString());
                        cm.Parameters.AddWithValue("gsta", json_object["gst_val"].ToString());
                        cm.Parameters.AddWithValue("gst_amt", json_object["gstnet"].ToString());
                        cm.Parameters.AddWithValue("itp", json_object["it_per"].ToString());
                        cm.Parameters.AddWithValue("itpa", json_object["it_val"].ToString());
                        cm.Parameters.AddWithValue("itp_amt", json_object["itnet"].ToString());
                        cm.Parameters.AddWithValue("total", json_object["total"].ToString());
                        cm.Parameters.AddWithValue("qty", json_object["qty"].ToString());
                        cm.Parameters.AddWithValue("quotation_no", json_object["quotation_no"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["quotation_no"].ToString()));
                        cm.Parameters.AddWithValue("closed", json_object["closed"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["closed"].ToString()));
                        cm.Parameters.AddWithValue("users", json_object["UserId"] == null ? (Object)DBNull.Value : Convert.ToString(json_object["UserId"].ToString()));

                        cm.Parameters.AddWithValue("vn_number", json_object["vn_number"].ToString());
                        cm.Parameters.AddWithValue("reg_number", json_object["reg_number"].ToString());
                        cm.Parameters.AddWithValue("name", json_object["name"].ToString());
                        cm.Parameters.AddWithValue("contactno", json_object["contact_no"].ToString());
                        cm.Parameters.AddWithValue("email", json_object["email"].ToString());


                        rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());

                    }
                    if (rowseffected > 0)
                    {

                        using (cm = new SqlCommand(detail, con, trans))
                        {
                            cm.Parameters.Add("key", SqlDbType.Int);
                            cm.Parameters.Add("sno", SqlDbType.Int);
                            cm.Parameters.Add("item", SqlDbType.Int);
                            cm.Parameters.Add("partno", SqlDbType.VarChar);
                            cm.Parameters.Add("brand", SqlDbType.VarChar);
                            cm.Parameters.Add("maker", SqlDbType.VarChar);
                            cm.Parameters.Add("model", SqlDbType.VarChar);
                            cm.Parameters.Add("desc", SqlDbType.VarChar);
                            cm.Parameters.Add("sub", SqlDbType.VarChar);
                            cm.Parameters.Add("qty", SqlDbType.Decimal);
                            cm.Parameters.Add("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amt", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_p", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("amount", SqlDbType.Decimal);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["sno"].Value = Convert.ToInt32(row["sno"]);
                                cm.Parameters["item"].Value = Convert.ToInt32(row["item"]) == 0 ? (Object)DBNull.Value : Convert.ToInt32(row["item"]);
                                cm.Parameters["partno"].Value = Convert.ToString(row["partno"]);
                                cm.Parameters["brand"].Value = Convert.ToString(row["brand"]);
                                cm.Parameters["maker"].Value = Convert.ToString(row["maker"]);
                                cm.Parameters["model"].Value = Convert.ToString(row["model"]);
                                cm.Parameters["desc"].Value = Convert.ToString(row["desc"]);
                                cm.Parameters["sub"].Value = Convert.ToString(row["sub"]);
                                cm.Parameters["qty"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["rate"].Value = Convert.ToDecimal(row["rate"]);
                                cm.Parameters["amt"].Value = Convert.ToDecimal(row["amount"]);
                                cm.Parameters["disc_rate"].Value = Convert.ToDecimal(row["disc_rate"]);
                                cm.Parameters["disc_p"].Value = Convert.ToDecimal(row["disc_per"]);
                                cm.Parameters["disc"].Value = Convert.ToDecimal(row["disc_amt"]);
                                cm.Parameters["amount"].Value = Convert.ToDecimal(row["net_amt"]);

                                rowseffected += cm.ExecuteNonQuery();

                            }


                        }


                        if (rowseffected > 0)
                        {

                            Select_Master += invno;
                            Select_Child += invno;


                            using (adp = new SqlDataAdapter(Select_Master + ";" + Select_Child, con))
                            {
                                adp.SelectCommand.Transaction = trans;

                                cmd = new SqlCommandBuilder(adp);
                                adp.Fill(dt);
                                dt.Tables[0].TableName = "Master";
                                dt.Tables[1].TableName = "Child";

                            }

                            String JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                            using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invno + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + (User) + "','" + (system) + "','New Entry','" + JSONString + "')", con, trans))
                            {

                                rows = cm.ExecuteNonQuery();

                            }

                            if (rows > 0)
                            {

                                trans.Commit();
                                IsInsert = invno;

                            }
                            else
                            {
                                trans.Rollback();
                                IsInsert = 0;
                            }

                        }
                        else
                        {
                            trans.Rollback();
                            IsInsert = 0;
                        }

                    }
                    else
                    {
                        trans.Rollback();
                        IsInsert = 0;

                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                response = ex.Message;
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }

            return IsInsert.ToString();


        }

        public String Quotation_Update(String json)
        {

            JObject json_object = JObject.Parse(json);
            String child = json_object["Child"].ToString();
            DataTable table = (DataTable)JsonConvert.DeserializeObject(child, (typeof(DataTable)));
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            int key = Convert.ToInt32(json_object["key"].ToString());
            String type = json_object["Type"].ToString();
            String date = json_object["edate"].ToString();
            String warehouse = json_object["warehouse"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int invno = Convert.ToInt32(json_object["inv"].ToString());
            String delete_detail = "Delete from " + json_object["Detail"] + " where key_fk=" + key + ";";

            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;

            String detail = " insert into " + json_object["Detail"] + "(key_fk,citmno,acitno,prtno,bn,maker,model,invdesc,subdesc,qty,rate,amt,dscrate,dscr_p,disc,ntamt) values "
                           + " (@key,@sno,@item,@partno,@brand,@maker,@model,@desc,@sub,@qty,@rate,@amt,@disc_rate,@disc_p,@disc,@amount)";


            String OrderMaster = "  Update " + json_object["Master"] + " set invtype=@invtype,clkdate=@edate,date=@edate,mrdminv_no=@vno,acode=@debit,c_code=@credit,duedate=@duedate,days=@days,prtclar=@remarks," +
                                 "  warehouse=@warehouse,amtgrs=@gross,disc=@disc,expmnininv=@expense,courier=@courier,amtnet=@net,gstp=@gstp,gsta=@gsta,amtnetwgst=@gst_amt," +
                                 "  itp=@itp,ita=@itpa,na_w_itax=@itp_amt,ttlamtnet=@total,closed=@closed,vn_number=@vn_number,reg_number=@reg_number,name=@name,contactno=@contactno,email=@email where key_pk=@key_pk";

            String Select_Master = "select distinct  sm.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

            String Select_Child = "select distinct  sd.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;



            DataTable st = new DataTable();
            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();


                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {

                        cm.Parameters.AddWithValue("key_pk", key);
                        cm.Parameters.AddWithValue("invtype", json_object["invtype"].ToString());
                        cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("invoice", invno);
                        cm.Parameters.AddWithValue("vno", json_object["vno"].ToString());
                        cm.Parameters.AddWithValue("debit", json_object["debit"].ToString());
                        cm.Parameters.AddWithValue("credit", json_object["credit"].ToString());
                        cm.Parameters.AddWithValue("duedate", json_object["days"].ToString() == String.Empty ? (Object)DBNull.Value : json_object["duedate"].ToString());
                        cm.Parameters.AddWithValue("days", json_object["days"].ToString() == String.Empty ? (Object)DBNull.Value : Convert.ToInt32(json_object["days"].ToString()));
                        cm.Parameters.AddWithValue("remarks", json_object["remarks"].ToString());
                        cm.Parameters.AddWithValue("warehouse", json_object["warehouse"].ToString());
                        cm.Parameters.AddWithValue("gross", json_object["gross"].ToString());
                        cm.Parameters.AddWithValue("disc", json_object["disc_amt"].ToString());
                        cm.Parameters.AddWithValue("expense", json_object["freight"].ToString());
                        cm.Parameters.AddWithValue("courier", json_object["courier"].ToString());
                        cm.Parameters.AddWithValue("net", json_object["net_amt"].ToString());
                        cm.Parameters.AddWithValue("gstp", json_object["gst_per"].ToString());
                        cm.Parameters.AddWithValue("gsta", json_object["gst_val"].ToString());
                        cm.Parameters.AddWithValue("gst_amt", json_object["gstnet"].ToString());
                        cm.Parameters.AddWithValue("itp", json_object["it_per"].ToString());
                        cm.Parameters.AddWithValue("itpa", json_object["it_val"].ToString());
                        cm.Parameters.AddWithValue("itp_amt", json_object["itnet"].ToString());
                        cm.Parameters.AddWithValue("total", json_object["total"].ToString());
                        cm.Parameters.AddWithValue("closed", json_object["closed"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["closed"].ToString()));
                        cm.Parameters.AddWithValue("vn_number", json_object["vn_number"].ToString());
                        cm.Parameters.AddWithValue("reg_number", json_object["reg_number"].ToString());
                        cm.Parameters.AddWithValue("name", json_object["name"].ToString());
                        cm.Parameters.AddWithValue("contactno", json_object["contact_no"].ToString());
                        cm.Parameters.AddWithValue("email", json_object["email"].ToString());
                        rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());

                    }
                    if (rowseffected > 0)
                    {

                        using (cm = new SqlCommand(delete_detail, con, trans))
                        {

                            cm.ExecuteNonQuery();

                        }
                        using (cm = new SqlCommand(detail, con, trans))
                        {
                            cm.Parameters.Add("key", SqlDbType.Int);
                            cm.Parameters.Add("sno", SqlDbType.Int);
                            cm.Parameters.Add("item", SqlDbType.Int);
                            cm.Parameters.Add("partno", SqlDbType.VarChar);
                            cm.Parameters.Add("brand", SqlDbType.VarChar);
                            cm.Parameters.Add("maker", SqlDbType.VarChar);
                            cm.Parameters.Add("model", SqlDbType.VarChar);
                            cm.Parameters.Add("desc", SqlDbType.VarChar);
                            cm.Parameters.Add("sub", SqlDbType.VarChar);
                            cm.Parameters.Add("qty", SqlDbType.Decimal);
                            cm.Parameters.Add("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amt", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_p", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("amount", SqlDbType.Decimal);


                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["sno"].Value = Convert.ToInt32(row["sno"]);
                                cm.Parameters["item"].Value = Convert.ToInt32(row["item"]) == 0 ? (Object)DBNull.Value : Convert.ToInt32(row["item"]);
                                cm.Parameters["partno"].Value = Convert.ToString(row["partno"]);
                                cm.Parameters["brand"].Value = Convert.ToString(row["brand"]);
                                cm.Parameters["maker"].Value = Convert.ToString(row["maker"]);
                                cm.Parameters["model"].Value = Convert.ToString(row["model"]);

                                cm.Parameters["desc"].Value = Convert.ToString(row["desc"]);
                                cm.Parameters["sub"].Value = Convert.ToString(row["sub"]);
                                cm.Parameters["qty"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["rate"].Value = Convert.ToDecimal(row["rate"]);
                                cm.Parameters["amt"].Value = Convert.ToDecimal(row["amount"]);
                                cm.Parameters["disc_rate"].Value = Convert.ToDecimal(row["disc_rate"]);
                                cm.Parameters["disc_p"].Value = Convert.ToDecimal(row["disc_per"]);
                                cm.Parameters["disc"].Value = Convert.ToDecimal(row["disc_amt"]);
                                cm.Parameters["amount"].Value = Convert.ToDecimal(row["net_amt"]);
                                rowseffected += cm.ExecuteNonQuery();

                            }


                        }


                        if (rowseffected > 0)
                        {
                            {

                                using (adp = new SqlDataAdapter(Select_Master + ";" + Select_Child, con))
                                {
                                    adp.SelectCommand.Transaction = trans;

                                    cmd = new SqlCommandBuilder(adp);
                                    adp.Fill(dt);
                                    dt.Tables[0].TableName = "Master";
                                    dt.Tables[1].TableName = "Child";

                                }

                                String JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                                using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invno + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + User + "','" + system + "','Modified Entry','" + JSONString + "')", con, trans))
                                {

                                    rows = cm.ExecuteNonQuery();

                                }

                                if (rows > 0)
                                {

                                    trans.Commit();
                                    IsInsert = key;

                                }
                                else
                                {
                                    trans.Rollback();
                                    IsInsert = 0;
                                }
                            }


                        }
                        else
                        {
                            trans.Rollback();
                            IsInsert = 0;
                        }

                    }
                    else
                    {
                        trans.Rollback();
                        IsInsert = 0;

                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                response = ex.Message;
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }

            return IsInsert.ToString();


        }

        public String Report_Quotation(String json)
        {
            JObject json_Object = JObject.Parse(json);
            int index = Convert.ToInt32(json_Object["index"].ToString());
            String from = json_Object["from"].ToString();
            String to = json_Object["to"].ToString();

            String from2 = DateTime.ParseExact(from, "yyyy-MM-dd", CultureInfo.InvariantCulture).ToString("MM-dd-yyyy");
            String to2 = DateTime.ParseExact(to, "yyyy-MM-dd", CultureInfo.InvariantCulture).ToString("MM-dd-yyyy");
            String query = "";
            String Master = json_Object["Master"].ToString();
            String Child = json_Object["Child"].ToString();
            String where = " where  CAST(sm.clkdate AS DATE) >= CAST( '" + from + "' AS DATE)  AND CAST(sm.clkdate AS DATE) <= CAST( '" + to + "' AS DATE) ";
            String where2 = " where  CAST(sm.clkdate AS DATE) >= CAST( ''" + from + "'' AS DATE)  AND CAST(sm.clkdate AS DATE) <= CAST( ''" + to + "'' AS DATE) ";

            String token = json_Object["token"] == null ? "" : json_Object["token"].ToString();
            if (Authorization(token) <= 0)
            {
                json = "In-Valid";
                return json;
            }

            if (json_Object["acode"].ToString() != String.Empty)
            {
                where += " and ac.code='" + json_Object["acode"].ToString().Trim() + "'";
            }

            if (json_Object["city"].ToString() != String.Empty)
            {
                where += " and city.code='" + json_Object["city"].ToString().Trim() + "'";
            }
            if (json_Object["item"].ToString() != String.Empty)
            {
                where += " and item.code='" + json_Object["item"].ToString().Trim() + "'";
            }
            if (json_Object["origin"].ToString() != String.Empty)
            {
                where += " and origin.code='" + json_Object["origin"].ToString().Trim() + "'";
            }
            if (json_Object["brand"].ToString() != String.Empty)
            {
                where += " and brand.code='" + json_Object["brand"].ToString().Trim() + "'";
            }
            if (json_Object["model"].ToString() != String.Empty)
            {
                where += " and model.code='" + json_Object["model"].ToString().Trim() + "'";
            }
            if (json_Object["maker"].ToString() != String.Empty)
            {
                where += " and maker.code='" + json_Object["maker"].ToString().Trim() + "'";
            }
            if (json_Object["reference"].ToString() != String.Empty)
            {
                where += " and rf.code='" + json_Object["reference"].ToString().Trim() + "'";
            }
            if (json_Object["vn_number"].ToString() != String.Empty)
            {
                where += " and sm.vn_number='" + json_Object["vn_number"].ToString().Trim() + "'";
            }
            if (json_Object["reg_number"].ToString() != String.Empty)
            {
                where += " and sm.reg_number='" + json_Object["reg_number"].ToString().Trim() + "'";
            }
            if (json_Object["contact_number"].ToString() != String.Empty)
            {
                where += " and sm.contactno='" + json_Object["contact_number"].ToString().Trim() + "'";
            }

            if (json_Object["quot_no"].ToString() != String.Empty)
            {
                where += " and sm.invoice_no=" + Convert.ToInt32(json_Object["quot_no"].ToString().Trim());
            }
            if (json_Object["invoice_no"].ToString() != String.Empty)
            {
                where += " and sales.invoice_no=" + Convert.ToInt32(json_Object["invoice_no"].ToString().Trim());
            }
            if (json_Object["entry_no"] != null)
            {
                if (json_Object["entry_no"].ToString() != String.Empty)
                {
                    where += " and sm.key_pk=" + Convert.ToInt32(json_Object["entry_no"].ToString().Trim());
                }
            }
            if (index == 0)
            {
                query = " select distinct sm.key_pk as [Computrized No],sm.invoice_no as [Quot_no],sales.invoice_no as [Inv.no],sm.contactno as [Contact_Number],sm.vn_number as [Vin Number],sm.reg_number as [Reg Number],FORMAT(Cast( sm.clkdate as Date), 'dd-MM-yyyy') as [Quot_Date],ac.title as [Party],im.desc1 as [Desc],im.partno as [PartNo],im.linkno as [LinkNo]," +
                        " sd.qty as [Qty],sd.rate as [Rate],sd.amt as [Amount],sd.dscrate as[Disc-Rate],sd.dscr_p as [Disc-Per],sd.disc as [DiscAmount],sm.gstp as [Gst-Per],sm.gsta as [GstAmount],(sd.amt-sd.disc+sm.gsta) as [NetAmount],Case when isnull(sm.closed,0)=0 then case when sales.invoice_no is null then 'Pending' else 'Completed' end else 'Closed'  end as Status" +
                        " from " + Master + " sm inner join " + Child + " sd on sm.key_pk=sd.key_fk  " +
                        " inner join ac on ac.code=sm.acode left join city on city.code=ac.city_code  left join itemlinked im on im.idno=sd.acitno " +
                        " left  join origin on origin.code=im.origin  left join brand on brand.code=im.brnad left join item on item.code=im.part " +
                        " left join model on model.id=im.model_maker  left join maker on maker.code=model.maker left join reference rf on rf.code=item.reference " +
                        " left join (select * from Sales_Master where quotation_no is not null)sales on sales.quotation_no=sm.key_pk " +
                         where + " order by [Quot_no],[Quot_Date]";
            }
            else if (index == 1)
            {
                query = " select distinct sm.key_pk as [Computrized No],sm.invoice_no as [Quot_no],sales.invoice_no as [Inv.no],sm.contactno as [Contact_Number],sm.vn_number as [Vin_Number],sm.reg_number as [Reg_Number],FORMAT(Cast( sm.clkdate as Date), 'dd-MM-yyyy') as [Quot_Date],ac.title as [Party]," +
                       " count(*) as [],sum(sd.amt) as [Amount],sum(sd.disc) as [DiscAmount], sum(sm.gsta) as [GstAmount],sum(sd.amt-sd.disc+sm.gsta) as [NetAmount],Case when isnull(sm.closed,0)=0 then case when sales.invoice_no is null then 'Pending' else 'Completed' end else 'Closed'  end as Status" +
                       " from " + Master + " sm inner join " + Child + " sd on sm.key_pk=sd.key_fk  " +
                       " inner join ac on ac.code=sm.acode left join city on city.code=ac.city_code  left join itemlinked im on im.idno=sd.acitno " +
                       " left  join origin on origin.code=im.origin  left join brand on brand.code=im.brnad left join item on item.code=im.part " +
                       " left join model on model.id=im.model_maker  left join maker on maker.code=model.maker left join reference rf on rf.code=item.reference " +
                       " left join (select * from Sales_Master where quotation_no is not null)sales on sales.quotation_no=sm.key_pk " +
                        where +
                        "  group by sm.key_pk,sm.invoice_no,sales.invoice_no,sm.clkdate,city.name,ac.title,sm.contactno,sm.vn_number,sm.reg_number,sm.closed " +
                        " order by [Quot_no],[Quot_Date]";
            }

            else if (index == 2)
            {

                query = "  select distinct im.idno as acitno,im.partno as PartNo,im.linkno,im.desc1 as [Desc], sum( sd.qty) as [Qty],sum(sd.amt) as [Amount],sum(sd.disc) as [DiscAmount],sum(sd.amt-sd.disc) as[NetAmount] from " + Master + " sm inner join " + Child + " sd on sm.key_pk=sd.key_fk" +
                       " inner join ac on ac.code=sm.acode left join city on city.code=ac.city_code  left join itemlinked im on im.idno=sd.acitno " +
                       " left  join origin on origin.code=im.origin  left join brand on brand.code=im.brnad left join item on item.code=im.part " +
                       " left join model on model.id=im.model_maker  left join maker on maker.code=model.maker left join reference rf on rf.code=item.reference " +
                        where + " group by im.idno,im.partno,im.linkno,im.desc1 ;";

            }

            else if (index == 3)
            {
                query = "  select idno,isnull(PartNo,'') as Partno,isnull(LinkNo,'') as LinkNo,isnull(Description,'') as Description, isnull(Jan,0) as Jan,isnull(Feb,0) as Feb,isnull(Mar,0) as Mar,isnull(Apr,0) as Apr, " +
                      "  isnull(May,0) as May,isnull(Jun,0) as Jun,isnull(Jul,0)as Jul,isnull(Aug,0) as Aug,isnull(Sep,0) as Sep,isnull(Oct,0) as Oct,isnull(Nov,0) as Nov, " +
                      "  isnull(Dec,0) as Dec, " +
                      "  isnull(Jan,0) +isnull(Feb,0)+isnull(Mar,0)+isnull(Apr,0)+isnull(May,0)+isnull(Jun,0) +isnull(Jul,0)+isnull(Aug,0) +isnull(Sep,0) " +
                      "  +isnull(Oct,0) +isnull(Nov,0) + isnull(Dec,0) as Total " +
                      "  from (select Cast( DateName( month , DateAdd( month ,MONTH(sm.clkdate) , -1 )) as Varchar(3)) as Period, " +
                      " im.idno, isnull(im.partno,'') as PartNo,isnull(im.partno,'') as LinkNo,isnull(im.desc1,'') as Description,sum(sm.citmno) as[Amount] from " + Master + " sm inner join " + Child + " sd on sm.key_pk=sd.key_fk " +
                     " inner join ac on ac.code=sm.acode left join city on city.code=ac.city_code left join itemlinked im on im.idno=sd.acitno " +
                     " left  join origin on origin.code=im.origin  left join brand on brand.code=im.brnad  left join item on item.code=im.part  " +
                     " left join model on model.id=im.model_maker left join maker on maker.code=model.maker left join reference rf on rf.code=item.reference  " +
                     where + "  group by YEAR(sm.clkdate)*100 + MONTH(sm.clkdate),Cast( DateName( month , DateAdd( month ,MONTH(sm.clkdate) , -1 )) as Varchar(3)),im.idno,im.partno,im.linkno,im.desc1" +
                     " ) t pivot (Sum(Amount) For Period IN([Jan],[Feb],[Mar],[Apr],[May],[Jun],[Jul],[Aug],[Sep],[Oct],[Nov],[Dec]) ) as pivot_table";
            }
            if (index == 4)
            {
                query = " select distinct sm.key_pk as [Computrized No],sm.invoice_no as [Quot.no],sm.vn_number as [Vin Number],sm.reg_number as [Reg Number],FORMAT(Cast( sm.clkdate as Date), 'dd-MM-yyyy') as [Quot.Date],ac.title as [Party],sd.invdesc as [Desc],sd.prtno as [PartNo]," +
                        " sd.qty as [Qty],sd.rate as [Rate],sd.amt as [Amount],sd.dscrate as[Disc-Rate],sd.dscr_p as [Disc-Per],sd.disc as [DiscAmount],sm.gstp as [Gst-Per],sm.gsta as [GstAmount],(sd.amt-sd.disc+sm.gsta) as [NetAmount]" +
                        " from " + Master + " sm inner join " + Child + " sd on sm.key_pk=sd.key_fk  " +
                        " inner join ac on ac.code=sm.acode left join city on city.code=ac.city_code  left join itemlinked im on im.idno=sd.acitno " +
                        " left  join origin on origin.code=im.origin  left join brand on brand.code=im.brnad left join item on item.code=im.part " +
                        " left join model on model.id=im.model_maker  left join maker on maker.code=model.maker left join reference rf on rf.code=item.reference " +
                         where + " and sd.acitno is null order by [Quot.no],[Quot.Date]";
            }


            return IList_GetTable(query);
        }

        public String Arrivals_Insert(String json)
        {

            JObject json_object = JObject.Parse(json);
            String child = json_object["Child"].ToString();
            DataTable table = (DataTable)JsonConvert.DeserializeObject(child, (typeof(DataTable)));
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            String type = json_object["Type"].ToString();
            String date = json_object["edate"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int invno = 0;
            int key = 0;
            String response = "";

            DataSet dt = new DataSet();
            SqlTransaction trans = null;

            String detail = " insert into " + json_object["Detail"] + "(key_fk,acitno,prtno,bn,maker,model,invdesc,qty,rate,amount) values "
                             + " (@key,@item,@partno,@brand,@maker,@model,@desc,@qty,@rate,@amount)";

            String Order1 = " insert into " + json_object["Master"] + "(key_pk,clkdate,date,invoice_no,prtclar,citmno,closed,users,amtgrs,disc,dscr_p,expmnininv,courier,amtnet,gstp,gsta,amtnetwgst,itp,ita,na_w_itax,ttlamtnet,acode) values ";
            String Order2 = " (@key_pk,@edate,@date,@invoice,@remarks,@qty,@closed,@users,@gross,@disc,@dscr_p,@expense,@courier,@net,@gstp,@gsta,@gst_amt,@itp,@itpa,@itp_amt,@total,@acode); ";
            String OrderMaster = Order1 + Order2;

            String Select_Master = "select distinct  sm.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=";
            String Select_Child = "select distinct  sd.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=";
            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();



                    using (cm = new SqlCommand(" select top 1 invoice_no from " + json_object["Master"] + "  order by invoice_no desc;", con, trans))
                    {

                        invno = Convert.ToInt32(cm.ExecuteScalar()) + 1;
                    }

                    using (cm = new SqlCommand(" select top 1 key_pk from " + json_object["Master"] + " order by invoice_no desc;", con, trans))
                    {

                        key = Convert.ToInt32(cm.ExecuteScalar()) + 1;
                    }

                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {

                        cm.Parameters.AddWithValue("key_pk", key);
                        cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("date", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("invoice", invno);
                        cm.Parameters.AddWithValue("acode", json_object["acode"].ToString());
                        cm.Parameters.AddWithValue("remarks", json_object["remarks"].ToString());
                        cm.Parameters.AddWithValue("qty", json_object["qty"].ToString());
                        cm.Parameters.AddWithValue("closed", json_object["closed"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["closed"].ToString()));
                        cm.Parameters.AddWithValue("users", json_object["UserId"].ToString());
                        cm.Parameters.AddWithValue("gross", json_object["gross"].ToString());
                        cm.Parameters.AddWithValue("disc", json_object["disc_amt"].ToString());
                        cm.Parameters.AddWithValue("dscr_p", Convert.ToDecimal(json_object["disc_per"].ToString()));
                        cm.Parameters.AddWithValue("expense", json_object["freight"].ToString());
                        cm.Parameters.AddWithValue("courier", json_object["courier"].ToString());
                        cm.Parameters.AddWithValue("net", json_object["net_amt"].ToString());
                        cm.Parameters.AddWithValue("gstp", json_object["gst_per"].ToString());
                        cm.Parameters.AddWithValue("gsta", json_object["gst_val"].ToString());
                        cm.Parameters.AddWithValue("gst_amt", json_object["gstnet"].ToString());
                        cm.Parameters.AddWithValue("itp", json_object["it_per"].ToString());
                        cm.Parameters.AddWithValue("itpa", json_object["it_val"].ToString());
                        cm.Parameters.AddWithValue("itp_amt", json_object["itnet"].ToString());
                        cm.Parameters.AddWithValue("total", json_object["total"].ToString());

                        rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());

                    }
                    if (rowseffected > 0)
                    {

                        using (cm = new SqlCommand(detail, con, trans))
                        {
                            cm.Parameters.Add("key", SqlDbType.Int);
                            cm.Parameters.Add("sno", SqlDbType.Int);
                            cm.Parameters.Add("item", SqlDbType.Int);
                            cm.Parameters.Add("partno", SqlDbType.VarChar);
                            cm.Parameters.Add("brand", SqlDbType.VarChar);
                            cm.Parameters.Add("maker", SqlDbType.VarChar);
                            cm.Parameters.Add("model", SqlDbType.VarChar);
                            cm.Parameters.Add("desc", SqlDbType.VarChar);
                            cm.Parameters.Add("qty", SqlDbType.Decimal);
                            cm.Parameters.Add("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amount", SqlDbType.Decimal);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["sno"].Value = Convert.ToInt32(row["sno"]);
                                cm.Parameters["item"].Value = Convert.ToInt32(row["item"]) == 0 ? (Object)DBNull.Value : Convert.ToInt32(row["item"]);
                                cm.Parameters["partno"].Value = Convert.ToString(row["partno"]);
                                cm.Parameters["brand"].Value = Convert.ToString(row["brand"]);
                                cm.Parameters["maker"].Value = Convert.ToString(row["maker"]);
                                cm.Parameters["model"].Value = Convert.ToString(row["model"]);
                                cm.Parameters["desc"].Value = Convert.ToString(row["desc"]);
                                cm.Parameters["qty"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["rate"].Value = Convert.ToDecimal(row["rate"]);
                                cm.Parameters["amount"].Value = Convert.ToDecimal(row["amount"]);

                                rowseffected += cm.ExecuteNonQuery();

                            }


                        }


                        if (rowseffected > 0)
                        {

                            Select_Master += invno;
                            Select_Child += invno;


                            using (adp = new SqlDataAdapter(Select_Master + ";" + Select_Child, con))
                            {
                                adp.SelectCommand.Transaction = trans;

                                cmd = new SqlCommandBuilder(adp);
                                adp.Fill(dt);
                                dt.Tables[0].TableName = "Master";
                                dt.Tables[1].TableName = "Child";

                            }

                            String JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                            using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invno + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + (User) + "','" + (system) + "','New Entry','" + JSONString + "')", con, trans))
                            {

                                rows = cm.ExecuteNonQuery();

                            }

                            if (rows > 0)
                            {

                                trans.Commit();
                                IsInsert = invno;

                            }
                            else
                            {
                                trans.Rollback();
                                IsInsert = 0;
                            }

                        }
                        else
                        {
                            trans.Rollback();
                            IsInsert = 0;
                        }

                    }
                    else
                    {
                        trans.Rollback();
                        IsInsert = 0;

                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                response = ex.Message;
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }

            return IsInsert.ToString();


        }

        public String Arrivals_Update(String json)
        {

            JObject json_object = JObject.Parse(json);
            String child = json_object["Child"].ToString();
            DataTable table = (DataTable)JsonConvert.DeserializeObject(child, (typeof(DataTable)));
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            int key = Convert.ToInt32(json_object["key"].ToString());
            String type = json_object["Type"].ToString();
            String date = json_object["edate"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int invno = Convert.ToInt32(json_object["inv"].ToString());
            String delete_detail = "Delete from " + json_object["Detail"] + " where key_fk=" + key + ";";

            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;

            String detail = " insert into " + json_object["Detail"] + "(key_fk,acitno,prtno,bn,maker,model,invdesc,qty,rate,amount) values "
                            + " (@key,@item,@partno,@brand,@maker,@model,@desc,@qty,@rate,@amount)";


            String OrderMaster = "  Update " + json_object["Master"] + " set acode=@acode,clkdate=@edate,date=@edate,prtclar=@remarks, closed=@closed," +
                                 "  amtgrs=@gross,disc=@disc,dscr_p=@dscr_p,expmnininv=@expense,courier=@courier,amtnet=@net,gstp=@gstp,gsta=@gsta,amtnetwgst=@gst_amt," +
                                 "  itp=@itp,ita=@itpa,na_w_itax=@itp_amt,ttlamtnet=@total where key_pk=@key_pk";


            String Select_Master = "select distinct  sm.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

            String Select_Child = "select distinct  sd.*  from " + json_object["Master"] + " sm inner join " + json_object["Detail"] + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;
            DataTable st = new DataTable();
            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();

                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {

                        cm.Parameters.AddWithValue("key_pk", key);
                        cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("date", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("invoice", invno);
                        cm.Parameters.AddWithValue("acode", json_object["acode"].ToString());
                        cm.Parameters.AddWithValue("remarks", json_object["remarks"].ToString());
                        cm.Parameters.AddWithValue("qty", json_object["qty"].ToString());
                        cm.Parameters.AddWithValue("closed", json_object["closed"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["closed"].ToString()));
                        cm.Parameters.AddWithValue("gross", json_object["gross"].ToString());
                        cm.Parameters.AddWithValue("dscr_p", Convert.ToDecimal(json_object["disc_per"].ToString()));
                        cm.Parameters.AddWithValue("disc", json_object["disc_amt"].ToString());
                        cm.Parameters.AddWithValue("expense", json_object["freight"].ToString());
                        cm.Parameters.AddWithValue("courier", json_object["courier"].ToString());
                        cm.Parameters.AddWithValue("net", json_object["net_amt"].ToString());
                        cm.Parameters.AddWithValue("gstp", json_object["gst_per"].ToString());
                        cm.Parameters.AddWithValue("gsta", json_object["gst_val"].ToString());
                        cm.Parameters.AddWithValue("gst_amt", json_object["gstnet"].ToString());
                        cm.Parameters.AddWithValue("itp", json_object["it_per"].ToString());
                        cm.Parameters.AddWithValue("itpa", json_object["it_val"].ToString());
                        cm.Parameters.AddWithValue("itp_amt", json_object["itnet"].ToString());
                        cm.Parameters.AddWithValue("total", json_object["total"].ToString());

                        rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());

                    }
                    if (rowseffected > 0)
                    {

                        using (cm = new SqlCommand(delete_detail, con, trans))
                        {

                            cm.ExecuteNonQuery();

                        }
                        using (cm = new SqlCommand(detail, con, trans))
                        {
                            cm.Parameters.Add("key", SqlDbType.Int);
                            cm.Parameters.Add("sno", SqlDbType.Int);
                            cm.Parameters.Add("item", SqlDbType.Int);
                            cm.Parameters.Add("partno", SqlDbType.VarChar);
                            cm.Parameters.Add("brand", SqlDbType.VarChar);
                            cm.Parameters.Add("maker", SqlDbType.VarChar);
                            cm.Parameters.Add("model", SqlDbType.VarChar);
                            cm.Parameters.Add("desc", SqlDbType.VarChar);
                            cm.Parameters.Add("qty", SqlDbType.Decimal);
                            cm.Parameters.Add("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amount", SqlDbType.Decimal);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["sno"].Value = Convert.ToInt32(row["sno"]);
                                cm.Parameters["item"].Value = Convert.ToInt32(row["item"]) == 0 ? (Object)DBNull.Value : Convert.ToInt32(row["item"]);
                                cm.Parameters["partno"].Value = Convert.ToString(row["partno"]);
                                cm.Parameters["brand"].Value = Convert.ToString(row["brand"]);
                                cm.Parameters["maker"].Value = Convert.ToString(row["maker"]);
                                cm.Parameters["model"].Value = Convert.ToString(row["model"]);
                                cm.Parameters["desc"].Value = Convert.ToString(row["desc"]);
                                cm.Parameters["qty"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["rate"].Value = Convert.ToDecimal(row["rate"]);
                                cm.Parameters["amount"].Value = Convert.ToDecimal(row["amount"]);

                                rowseffected += cm.ExecuteNonQuery();

                            }


                        }

                        if (rowseffected > 0)
                        {
                            {

                                using (adp = new SqlDataAdapter(Select_Master + ";" + Select_Child, con))
                                {
                                    adp.SelectCommand.Transaction = trans;

                                    cmd = new SqlCommandBuilder(adp);
                                    adp.Fill(dt);
                                    dt.Tables[0].TableName = "Master";
                                    dt.Tables[1].TableName = "Child";

                                }

                                String JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                                using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invno + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + User + "','" + system + "','Modified Entry','" + JSONString + "')", con, trans))
                                {

                                    rows = cm.ExecuteNonQuery();

                                }

                                if (rows > 0)
                                {

                                    trans.Commit();
                                    IsInsert = key;

                                }
                                else
                                {
                                    trans.Rollback();
                                    IsInsert = 0;
                                }
                            }


                        }
                        else
                        {
                            trans.Rollback();
                            IsInsert = 0;
                        }

                    }
                    else
                    {
                        trans.Rollback();
                        IsInsert = 0;

                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                response = ex.Message;
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }

            return IsInsert.ToString();


        }

        public String ReOrder_Load(String json)
        {
            JObject json_Object = JObject.Parse(json);

            String token = json_Object["token"] == null ? "" : json_Object["token"].ToString();
            if (Authorization(token) <= 0)
            {
                json = "In-Valid";
                return json;
            }

            String data = "";
            String query = " Select distinct  top 1 key_pk,invoice_no from " + json_Object["Master"] + " Order By Key_pk desc;" +
                           " select USERS,USERS_NAME from USERS where ISACTIVE=1 ORDER BY USERS_NAME;" +
                           " select count(key_pk) from " + json_Object["Master"];



            data = IList_GetDataSet(query);
            return data;
        }

        public String Report_ReOrder(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String type = Convert.ToString(json_Object["type"]);
            String from = json_Object["from"].ToString();
            String to = json_Object["to"].ToString();
            int group = Convert.ToInt32(json_Object["group"].ToString());

            String from2 = DateTime.ParseExact(from, "yyyy-MM-dd", CultureInfo.InvariantCulture).ToString("MM-dd-yyyy");
            String to2 = DateTime.ParseExact(to, "yyyy-MM-dd", CultureInfo.InvariantCulture).ToString("MM-dd-yyyy");
            String query = "";
            String Master = json_Object["Master"].ToString();
            String Child = json_Object["Child"].ToString();
            String where = " where  CAST(sm.clkdate AS DATE) >= CAST( '" + from + "' AS DATE)  AND CAST(sm.clkdate AS DATE) <= CAST( '" + to + "' AS DATE) ";

            String token = json_Object["token"] == null ? "" : json_Object["token"].ToString();
            if (Authorization(token) <= 0)
            {
                json = "In-Valid";
                return json;
            }

            if (json_Object["acode"].ToString() != String.Empty)
            {
                where += " and ac.code='" + json_Object["acode"].ToString().Trim() + "'";
            }

            if (json_Object["city"].ToString() != String.Empty)
            {
                where += " and city.code='" + json_Object["city"].ToString().Trim() + "'";
            }
            if (json_Object["item"].ToString() != String.Empty)
            {
                where += " and item.code='" + json_Object["item"].ToString().Trim() + "'";
            }
            if (json_Object["origin"].ToString() != String.Empty)
            {
                where += " and origin.code='" + json_Object["origin"].ToString().Trim() + "'";
            }
            if (json_Object["brand"].ToString() != String.Empty)
            {
                where += " and brand.code='" + json_Object["brand"].ToString().Trim() + "'";
            }
            if (json_Object["model"].ToString() != String.Empty)
            {
                where += " and model.code='" + json_Object["model"].ToString().Trim() + "'";
            }
            if (json_Object["maker"].ToString() != String.Empty)
            {
                where += " and maker.code='" + json_Object["maker"].ToString().Trim() + "'";
            }
            if (json_Object["reference"].ToString() != String.Empty)
            {
                where += " and rf.code='" + json_Object["reference"].ToString().Trim() + "'";
            }

            if (json_Object["partno"].ToString() != String.Empty)
            {
                where += " and im.idno=" + json_Object["partno"].ToString().Trim();
            }

            if (type.Trim() == "Pending")
            {
                where += " and sm.closed=0 ";
            }

            if (type.Trim() == "Closed")
            {
                where += " and sm.closed=1 ";
            }


            query = "  select distinct sm.key_pk as [Computrized No],sm.invoice_no as [Invoice.no],FORMAT(Cast( sm.clkdate as Date), 'dd-MM-yyyy') as [Date],count(*) as [Qty],Case when isnull(sm.closed,0)=0 then 'Pending' else 'Closed' end as Status,sm.prtclar as Remarks " +
                        "  from " + Master + " sm inner join " + Child + " sd on sm.key_pk=sd.key_fk  " +
                        "   left join itemlinked im on im.idno=sd.acitno " +
                        " left  join origin on origin.code=im.origin  left join brand on brand.code=im.brnad left join item on item.code=im.part " +
                        " left join model on model.id=im.model_maker  left join maker on maker.code=model.maker left join reference rf on rf.code=item.reference " +
                         where + " group by sm.key_pk,sm.invoice_no,sm.clkdate,sm.closed,sm.prtclar order by [Invoice.no],[Date]";






            return IList_GetTable(query);
        }

        public String Report_Arrival(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String type = Convert.ToString(json_Object["type"]);
            String from = json_Object["from"].ToString();
            String to = json_Object["to"].ToString();
            int group = Convert.ToInt32(json_Object["group"].ToString());

            String from2 = DateTime.ParseExact(from, "yyyy-MM-dd", CultureInfo.InvariantCulture).ToString("MM-dd-yyyy");
            String to2 = DateTime.ParseExact(to, "yyyy-MM-dd", CultureInfo.InvariantCulture).ToString("MM-dd-yyyy");
            String query = "";
            String Master = json_Object["Master"].ToString();
            String Child = json_Object["Child"].ToString();
            String where = " where  CAST(sm.clkdate AS DATE) >= CAST( '" + from + "' AS DATE)  AND CAST(sm.clkdate AS DATE) <= CAST( '" + to + "' AS DATE) ";

            String token = json_Object["token"] == null ? "" : json_Object["token"].ToString();
            if (Authorization(token) <= 0)
            {
                json = "In-Valid";
                return json;
            }

            if (json_Object["acode"].ToString() != String.Empty)
            {
                where += " and sm.acode='" + json_Object["acode"].ToString().Trim() + "'";
            }

            if (json_Object["city"].ToString() != String.Empty)
            {
                where += " and city.code='" + json_Object["city"].ToString().Trim() + "'";
            }
            if (json_Object["item"].ToString() != String.Empty)
            {
                where += " and item.code='" + json_Object["item"].ToString().Trim() + "'";
            }
            if (json_Object["origin"].ToString() != String.Empty)
            {
                where += " and origin.code='" + json_Object["origin"].ToString().Trim() + "'";
            }
            if (json_Object["brand"].ToString() != String.Empty)
            {
                where += " and brand.code='" + json_Object["brand"].ToString().Trim() + "'";
            }
            if (json_Object["model"].ToString() != String.Empty)
            {
                where += " and model.code='" + json_Object["model"].ToString().Trim() + "'";
            }
            if (json_Object["maker"].ToString() != String.Empty)
            {
                where += " and maker.code='" + json_Object["maker"].ToString().Trim() + "'";
            }
            if (json_Object["reference"].ToString() != String.Empty)
            {
                where += " and rf.code='" + json_Object["reference"].ToString().Trim() + "'";
            }

            if (json_Object["partno"].ToString() != String.Empty)
            {
                where += " and im.idno=" + json_Object["partno"].ToString().Trim();
            }

            if (type.Trim() == "Pending")
            {
                where += " and sm.closed=0 ";
            }

            if (type.Trim() == "Closed")
            {
                where += " and sm.closed=1 ";
            }


            query = "  select distinct sm.key_pk as [Computrized No],sm.invoice_no as [Invoice.no],FORMAT(Cast( sm.clkdate as Date), 'dd-MM-yyyy') as [Date],ac.Title,count(*) as [Qty]," +
                        " sm.amtgrs as [Gross_Amount],sm.dscr_p as[Disc_Per],sm.disc as [Discount],sm.expmnininv as [Freight],sm.courier as[Courier],sm.gsta as [Gst_Amount],sm.ita as[IT_Amount],sm.ttlamtnet as[Net_Amount] " +
                        ",Case when isnull(sm.closed,0)=0 then 'Pending' else 'Closed' end as Status " +
                        "  from " + Master + " sm inner join " + Child + " sd on sm.key_pk=sd.key_fk  " +
                        "   left join itemlinked im on im.idno=sd.acitno inner join ac on ac.code=sm.acode " +
                        " left  join origin on origin.code=im.origin  left join brand on brand.code=im.brnad left join item on item.code=im.part " +
                        " left join model on model.id=im.model_maker  left join maker on maker.code=model.maker left join reference rf on rf.code=item.reference " +
                         where + " group by sm.key_pk,sm.invoice_no,sm.clkdate,ac.title,sm.closed,sm.amtgrs,sm.dscr_p,sm.disc,sm.expmnininv,sm.courier,sm.gsta,sm.ita,sm.ttlamtnet order by [Invoice.no],[Date]";

            return IList_GetTable(query);
        }

        public String Pending_Authorization(String json)
        {
            JObject json_Object = JObject.Parse(json);
            int index = Convert.ToInt32(json_Object["index"].ToString());
            String from = json_Object["from"].ToString();
            String to = json_Object["to"].ToString();

            String query = "";
            String Master = json_Object["Master"].ToString();
            String Child = json_Object["Child"].ToString();
            String where = " where  CAST(sm.clkdate AS DATE) >= CAST( '" + from + "' AS DATE)  AND CAST(sm.clkdate AS DATE) <= CAST( '" + to + "' AS DATE) ";
            String where2 = " where  CAST(sm.clkdate AS DATE) >= CAST( ''" + from + "'' AS DATE)  AND CAST(sm.clkdate AS DATE) <= CAST( ''" + to + "'' AS DATE) ";

            String token = json_Object["token"] == null ? "" : json_Object["token"].ToString();
            if (Authorization(token) <= 0)
            {
                json = "In-Valid";
                return json;
            }

            if (json_Object["acode"].ToString() != String.Empty)
            {
                where += " and ac.code='" + json_Object["acode"].ToString().Trim() + "'";
            }

            if (json_Object["city"].ToString() != String.Empty)
            {
                where += " and city.code='" + json_Object["city"].ToString().Trim() + "'";
            }
            if (json_Object["item"].ToString() != String.Empty)
            {
                where += " and item.code='" + json_Object["item"].ToString().Trim() + "'";
            }
            if (json_Object["origin"].ToString() != String.Empty)
            {
                where += " and origin.code='" + json_Object["origin"].ToString().Trim() + "'";
            }
            if (json_Object["brand"].ToString() != String.Empty)
            {
                where += " and brand.code='" + json_Object["brand"].ToString().Trim() + "'";
            }
            if (json_Object["model"].ToString() != String.Empty)
            {
                where += " and model.code='" + json_Object["model"].ToString().Trim() + "'";
            }
            if (json_Object["maker"].ToString() != String.Empty)
            {
                where += " and maker.code='" + json_Object["maker"].ToString().Trim() + "'";
            }
            if (json_Object["reference"].ToString() != String.Empty)
            {
                where += " and rf.code='" + json_Object["reference"].ToString().Trim() + "'";
            }
            if (json_Object["vn_number"].ToString() != String.Empty)
            {
                where += " and sm.vn_number='" + json_Object["vn_number"].ToString().Trim() + "'";
            }
            if (json_Object["reg_number"].ToString() != String.Empty)
            {
                where += " and sm.reg_number='" + json_Object["reg_number"].ToString().Trim() + "'";
            }

            if (json_Object["contact_number"].ToString() != String.Empty)
            {
                where += " and sm.contactno='" + json_Object["contact_number"].ToString().Trim() + "'";
            }

            if (json_Object["quot_no"].ToString() != String.Empty)
            {
                where += " and sm.invoice_no=" + Convert.ToInt32(json_Object["quot_no"].ToString().Trim());
            }
            if (json_Object["invoice_no"].ToString() != String.Empty)
            {
                where += " and sales.invoice_no=" + Convert.ToInt32(json_Object["invoice_no"].ToString().Trim());
            }
            if (json_Object["entry_no"] != null)
            {
                if (json_Object["entry_no"].ToString() != String.Empty)
                {
                    where += " and sm.key_pk=" + Convert.ToInt32(json_Object["entry_no"].ToString().Trim());
                }
            }
            if (Convert.ToInt32(json_Object["closed"].ToString()) != -1)
            {
                where += " and sm.closed=" + Convert.ToInt32(json_Object["closed"].ToString().Trim());
            }

            query = " select distinct sm.key_pk as [Computrized.no],sm.invoice_no as [Quot.no],FORMAT(Cast( sm.clkdate as Date), 'dd-MM-yyyy') as [Quot.Date],ac.title as [Party],count(*) as [Items],sm.contactno as [Contact_Number],sm.Vn_Number,sm.Reg_Number,u.USERS_NAME as [Created By],au.USERS_NAME as [Auth_By] " +
                     " ,case when sm.closed=0 then '' else 'Closed' end as Status " +
                     " from " + Master + " sm inner join " + Child + " sd on sm.key_pk=sd.key_fk  " +
                     " left join ac on ac.code=sm.acode left join city on city.code=ac.city_code  left join itemlinked im on im.idno=sd.acitno " +
                     " left  join origin on origin.code=im.origin  left join brand on brand.code=im.brnad left join item on item.code=im.part " +
                     " left join model on model.id=im.model_maker  left join maker on maker.code=model.maker left join reference rf on rf.code=item.reference " +
                     " left join USERS u on u.USERS=sm.users left join USERS au on au.USERS=sm.auth_by ";


            if (index == 0)
            {
                query += where + " and sm.auth_by is not null  group by sm.key_pk,sm.invoice_no,sm.clkdate,ac.title,sm.vn_number,sm.reg_number,sm.contactno,u.USERS_NAME,au.USERS_NAME,sm.closed" +
                         " order by [Quot.no],[Quot.Date]";
            }
            else if (index == 1)
            {
                query += where + " and sm.auth_by is null  group by sm.key_pk,sm.invoice_no,sm.clkdate,ac.title,sm.vn_number,sm.reg_number,sm.contactno,u.USERS_NAME,au.USERS_NAME,sm.closed " +
                         " order by [Quot.no],[Quot.Date]";
            }
            else if (index == 2)
            {
                query += where + "   group by sm.key_pk,sm.invoice_no,sm.clkdate,ac.title,sm.vn_number,sm.reg_number,u.USERS_NAME,au.USERS_NAME,sm.closed,sm.contactno " +
                         " order by [Quot.no],[Quot.Date]";
            }

            return IList_GetTable(query);
        }

        public String Pending_ReOrder_Authorization(String json)
        {
            JObject json_Object = JObject.Parse(json);
            int index = Convert.ToInt32(json_Object["index"].ToString());
            String from = json_Object["from"].ToString();
            String to = json_Object["to"].ToString();

            String query = "";
            String Master = json_Object["Master"].ToString();
            String Child = json_Object["Child"].ToString();
            String where = " where  CAST(sm.clkdate AS DATE) >= CAST( '" + from + "' AS DATE)  AND CAST(sm.clkdate AS DATE) <= CAST( '" + to + "' AS DATE) ";
            String where2 = " where  CAST(sm.clkdate AS DATE) >= CAST( ''" + from + "'' AS DATE)  AND CAST(sm.clkdate AS DATE) <= CAST( ''" + to + "'' AS DATE) ";

            String token = json_Object["token"] == null ? "" : json_Object["token"].ToString();
            if (Authorization(token) <= 0)
            {
                json = "In-Valid";
                return json;
            }


            if (json_Object["item"].ToString() != String.Empty)
            {
                where += " and item.code='" + json_Object["item"].ToString().Trim() + "'";
            }
            if (json_Object["origin"].ToString() != String.Empty)
            {
                where += " and origin.code='" + json_Object["origin"].ToString().Trim() + "'";
            }
            if (json_Object["brand"].ToString() != String.Empty)
            {
                where += " and brand.code='" + json_Object["brand"].ToString().Trim() + "'";
            }
            if (json_Object["model"].ToString() != String.Empty)
            {
                where += " and model.code='" + json_Object["model"].ToString().Trim() + "'";
            }
            if (json_Object["maker"].ToString() != String.Empty)
            {
                where += " and maker.code='" + json_Object["maker"].ToString().Trim() + "'";
            }
            if (json_Object["reference"].ToString() != String.Empty)
            {
                where += " and rf.code='" + json_Object["reference"].ToString().Trim() + "'";
            }
            if (json_Object["quot_no"].ToString() != String.Empty)
            {
                where += " and sm.invoice_no=" + Convert.ToInt32(json_Object["quot_no"].ToString().Trim());
            }
            if (json_Object["invoice_no"].ToString() != String.Empty)
            {
                where += " and sales.invoice_no=" + Convert.ToInt32(json_Object["invoice_no"].ToString().Trim());
            }
            if (json_Object["entry_no"] != null)
            {
                if (json_Object["entry_no"].ToString() != String.Empty)
                {
                    where += " and sm.key_pk=" + Convert.ToInt32(json_Object["entry_no"].ToString().Trim());
                }
            }
            if (Convert.ToInt32(json_Object["closed"].ToString()) != -1)
            {
                where += " and sm.closed=" + Convert.ToInt32(json_Object["closed"].ToString().Trim());
            }

            query = "  select distinct sm.key_pk as [Computrized.no],sm.invoice_no as [Reorder.no],FORMAT(Cast( sm.clkdate as Date), 'dd-MM-yyyy') as [Reorder.Date],count(*) as [Items],u.USERS_NAME as [Created By],au.USERS_NAME as [Auth_By] " +
                     " ,case when sm.closed=0 then '' else 'Closed' end as Status " +
                     " from " + Master + " sm inner join " + Child + " sd on sm.key_pk=sd.key_fk  " +
                     " left join itemlinked im on im.idno=sd.acitno " +
                     " left  join origin on origin.code=im.origin  left join brand on brand.code=im.brnad left join item on item.code=im.part " +
                     " left join model on model.id=im.model_maker  left join maker on maker.code=model.maker left join reference rf on rf.code=item.reference " +
                     " left join USERS u on u.USERS=sm.users left join USERS au on au.USERS=sm.auth_by ";


            if (index == 0)
            {
                query += where + " and sm.auth_by is not null  group by sm.key_pk,sm.invoice_no,sm.clkdate,u.USERS_NAME,au.USERS_NAME,sm.closed" +
                         " order by [Reorder.no],[Reorder.Date]";
            }
            else if (index == 1)
            {
                query += where + " and sm.auth_by is null  group by sm.key_pk,sm.invoice_no,sm.clkdate,u.USERS_NAME,au.USERS_NAME,sm.closed " +
                         " order by [Reorder.no],[Reorder.Date]";
            }
            else if (index == 2)
            {
                query += where + "   group by sm.key_pk,sm.invoice_no,sm.clkdate,u.USERS_NAME,au.USERS_NAME,sm.closed " +
                         " order by [Reorder.no],[Reorder.Date]";
            }

            return IList_GetTable(query);
        }

        public int AuthorizedQuotation(String json)
        {
            String where = "";
            JObject json_Object = JObject.Parse(json);
            String type = Convert.ToString(json_Object["type"].ToString());
            String users = Convert.ToString(json_Object["users"].ToString());
            String child = json_Object["Child"].ToString();
            String Table_Master = json_Object["Table_Master"].ToString();
            String Table_Child = json_Object["Table_Child"].ToString();

            DataTable table = (DataTable)JsonConvert.DeserializeObject(child, (typeof(DataTable)));
            int val = 0;
            String query = "";
            foreach (DataRow row in table.Rows)
            {
                if (val == 0)
                {
                    where += "  key_pk=" + row[0].ToString();
                    val = 1;
                }
                where += " or key_pk=" + row[0].ToString();
            }
            if (type == "closed")
            {

                query = "Update " + Table_Master + " set closed=1 where " + where;


            }
            else
            {
                query = "Update " + Table_Master + " set auth_by=" + users + " where " + where;

            }
            return IList_execute(query);
        }

        public String Invoice_OnSales_Insert(String json)
        {

            JObject json_object = JObject.Parse(json);
            DataTable table_ledger = (DataTable)JsonConvert.DeserializeObject(json_object["Ledger"].ToString(), (typeof(DataTable)));
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int invno = 0;
            int key = 0;
            int entryno = 0;
            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;

            String Order1 = " insert into voucher_cash(key_pk,userno,userno_edit,clkdate,date,voucher_no,invoice_pk_key,d_code,c_code,description,amount) ";
            String Order2 = " values (@key_pk,@userno,@userno_edit,@clkdate,@date,@voucher_no,@invoice_pk_key,@d_code,@c_code,@description,@amount);select SCOPE_IDENTITY() as code; ";
            String OrderMaster = Order1 + Order2;

            String ledger = " insert into ledger(edate,description,details,type,ref,mrd,d_acode,d_amt,c_acode,c_amt,pidno,per,posted,entryno) " +
                            " values(@edate,@desc,@det,@type,@ref,@mrd,@d_acode,@d_amt,@c_acode,@c_amt,@pidno,@per,@posted,@entryno);";


            String Select_Master = "select distinct *  from voucher_cash where key_pk=";
            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();

                    using (cm = new SqlCommand("select top 1 isnull(entryno,0)+1 from Ledger order by entryno desc;", con, trans))
                    {

                        entryno = Convert.ToInt32(cm.ExecuteScalar());
                    }

                    using (cm = new SqlCommand(" select top 1 voucher_no from voucher_cash order by voucher_no desc;", con, trans))
                    {

                        invno = Convert.ToInt32(cm.ExecuteScalar()) + 1;
                    }

                    using (cm = new SqlCommand(" select top 1 key_pk from voucher_cash  order by key_pk desc;", con, trans))
                    {

                        key = Convert.ToInt32(cm.ExecuteScalar()) + 1;
                    }

                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {
                        cm.Parameters.AddWithValue("key_pk", key);
                        cm.Parameters.AddWithValue("userno", json_object["UserId"].ToString());
                        cm.Parameters.AddWithValue("userno_edit", json_object["UserId"].ToString());
                        cm.Parameters.AddWithValue("voucher_no", invno);
                        cm.Parameters.AddWithValue("clkdate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("date", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        cm.Parameters.AddWithValue("invoice_pk_key", json_object["inv_no"].ToString());
                        cm.Parameters.AddWithValue("d_code", json_object["debit"].ToString());
                        cm.Parameters.AddWithValue("c_code", json_object["credit"].ToString());
                        cm.Parameters.AddWithValue("description", json_object["description"].ToString());
                        cm.Parameters.AddWithValue("amount", Convert.ToDecimal(json_object["amount"]));
                        cm.Parameters.AddWithValue("type", json_object["inv_type"].ToString());

                        rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());

                    }
                    if (rowseffected > 0)
                    {
                        using (cm = new SqlCommand(ledger, con, trans))
                        {
                            cm.Parameters.Add("edate", SqlDbType.DateTime);
                            cm.Parameters.Add("desc", SqlDbType.VarChar);
                            cm.Parameters.Add("det", SqlDbType.VarChar);
                            cm.Parameters.Add("type", SqlDbType.VarChar);
                            cm.Parameters.Add("ref", SqlDbType.VarChar);
                            cm.Parameters.Add("mrd", SqlDbType.VarChar);
                            cm.Parameters.Add("d_acode", SqlDbType.VarChar);
                            cm.Parameters.Add("d_amt", SqlDbType.Decimal);
                            cm.Parameters.Add("c_acode", SqlDbType.VarChar);
                            cm.Parameters.Add("c_amt", SqlDbType.Decimal);
                            cm.Parameters.Add("pidno", SqlDbType.Int);
                            cm.Parameters.Add("per", SqlDbType.VarChar);
                            cm.Parameters.Add("posted", SqlDbType.Int);
                            cm.Parameters.Add("entryno", SqlDbType.Int);

                            foreach (DataRow row in table_ledger.Rows)
                            {

                                cm.Parameters["edate"].Value = row["edate"];
                                cm.Parameters["desc"].Value = row["description"];
                                cm.Parameters["det"].Value = row["details"];
                                cm.Parameters["type"].Value = row["type"];
                                cm.Parameters["ref"].Value = invno;
                                cm.Parameters["mrd"].Value = row["mrd"];
                                cm.Parameters["d_acode"].Value = row["d_acode"].ToString().Trim();
                                cm.Parameters["d_amt"].Value = Convert.ToDecimal(row["d_amt"]);
                                cm.Parameters["c_acode"].Value = row["c_acode"].ToString().Trim();
                                cm.Parameters["c_amt"].Value = Convert.ToDecimal(row["c_amt"]);
                                cm.Parameters["pidno"].Value = key;
                                cm.Parameters["per"].Value = (row["per"]);
                                cm.Parameters["posted"].Value = (row["posted"]);
                                cm.Parameters["entryno"].Value = entryno;

                                rowseffected += cm.ExecuteNonQuery();

                            }


                        }

                        if (rowseffected > 0)
                        {
                            {
                                Select_Master += key;


                                using (adp = new SqlDataAdapter(Select_Master, con))
                                {
                                    adp.SelectCommand.Transaction = trans;
                                    cmd = new SqlCommandBuilder(adp);
                                    adp.Fill(dt);
                                    dt.Tables[0].TableName = "Master";

                                }

                                String JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                                using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + invno + ",'IOS','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + (User) + "','" + (system) + "','New Entry','" + JSONString + "')", con, trans))
                                {

                                    rows = cm.ExecuteNonQuery();

                                }

                                if (rows > 0)
                                {

                                    trans.Commit();
                                    IsInsert = invno;

                                }
                                else
                                {
                                    trans.Rollback();
                                    IsInsert = 0;
                                }
                            }


                        }
                        else
                        {
                            trans.Rollback();
                            IsInsert = 0;
                        }
                    }
                    else
                    {
                        trans.Rollback();
                        IsInsert = 0;
                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                response = ex.Message;
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }

            /* if (IsInsert > 0)
             {
                 String invoice = " select distinct om.entry from OrderMaster om,order_detail od where om.Entry=od.MEntry and om.estatus='SV' order by om.Entry;";
                 response = IList_GetTable(invoice);
             }*/
            return IsInsert.ToString();


        }

        public String Invoice_OnSales_Update(String json)
        {

            JObject json_object = JObject.Parse(json);
            DataTable table_ledger = (DataTable)JsonConvert.DeserializeObject(json_object["Ledger"].ToString(), (typeof(DataTable)));
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int key = 0;

            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;


            String OrderMaster = " update voucher_cash set userno_edit=@userno_edit,clkdate=@clkdate,d_code=@d_code,description=@description,amount=@amount where key_pk=@key_pk and voucher_no=@voucher_no ";


            String ledger = "  Update  Ledger set edate=@edate,per=@per,description=@desc,details=@det,mrd=@mrd,d_acode=@d_acode,d_amt=@d_amt,c_acode=@c_acode,c_amt=@c_amt " +
                                             "  where type=@type and pidno=@pidno";


            String Select_Master = "select distinct *  from voucher_cash where key_pk=" + json_object["entryno"].ToString();
            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();





                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {
                        cm.Parameters.AddWithValue("key_pk", json_object["entryno"].ToString());
                        cm.Parameters.AddWithValue("userno_edit", json_object["UserId"].ToString());
                        cm.Parameters.AddWithValue("voucher_no", json_object["voucherno"].ToString());
                        cm.Parameters.AddWithValue("clkdate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("d_code", json_object["debit"].ToString());
                        cm.Parameters.AddWithValue("description", json_object["description"].ToString());
                        cm.Parameters.AddWithValue("amount", Convert.ToDecimal(json_object["amount"]));

                        key = Convert.ToInt32(cm.ExecuteNonQuery());

                    }
                    if (key > 0)
                    {
                        using (cm = new SqlCommand(ledger, con, trans))
                        {



                            cm.Parameters.Add("edate", SqlDbType.DateTime);
                            cm.Parameters.Add("desc", SqlDbType.VarChar);
                            cm.Parameters.Add("det", SqlDbType.VarChar);
                            cm.Parameters.Add("type", SqlDbType.VarChar);
                            cm.Parameters.Add("ref", SqlDbType.VarChar);
                            cm.Parameters.Add("mrd", SqlDbType.VarChar);
                            cm.Parameters.Add("d_acode", SqlDbType.VarChar);
                            cm.Parameters.Add("d_amt", SqlDbType.Decimal);
                            cm.Parameters.Add("c_acode", SqlDbType.VarChar);
                            cm.Parameters.Add("c_amt", SqlDbType.Decimal);
                            cm.Parameters.Add("pidno", SqlDbType.Int);
                            cm.Parameters.Add("per", SqlDbType.VarChar);

                            foreach (DataRow row in table_ledger.Rows)
                            {

                                cm.Parameters["edate"].Value = row["edate"];
                                cm.Parameters["desc"].Value = row["description"];
                                cm.Parameters["det"].Value = row["details"];
                                cm.Parameters["type"].Value = row["type"];
                                cm.Parameters["ref"].Value = json_object["voucherno"].ToString();
                                cm.Parameters["mrd"].Value = row["mrd"];
                                cm.Parameters["d_acode"].Value = row["d_acode"].ToString().Trim();
                                cm.Parameters["d_amt"].Value = Convert.ToDecimal(row["d_amt"]);
                                cm.Parameters["c_acode"].Value = row["c_acode"].ToString().Trim();
                                cm.Parameters["c_amt"].Value = Convert.ToDecimal(row["c_amt"]);
                                cm.Parameters["pidno"].Value = json_object["entryno"].ToString();
                                cm.Parameters["per"].Value = (row["per"]);



                                rowseffected += cm.ExecuteNonQuery();

                            }


                        }

                        if (rowseffected > 0)
                        {
                            {


                                using (adp = new SqlDataAdapter(Select_Master, con))
                                {
                                    adp.SelectCommand.Transaction = trans;
                                    cmd = new SqlCommandBuilder(adp);
                                    adp.Fill(dt);
                                    dt.Tables[0].TableName = "Master";

                                }

                                String JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                                using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + json_object["entryno"].ToString() + ",'IOS','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + (User) + "','" + (system) + "','Modified Entry','" + JSONString + "')", con, trans))
                                {

                                    rows = cm.ExecuteNonQuery();

                                }

                                if (rows > 0)
                                {

                                    trans.Commit();
                                    IsInsert = 1;

                                }
                                else
                                {
                                    trans.Rollback();
                                    IsInsert = 0;
                                }
                            }


                        }
                        else
                        {
                            trans.Rollback();
                            IsInsert = 0;
                        }
                    }
                    else
                    {
                        trans.Rollback();
                        IsInsert = 0;
                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                response = ex.Message;
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }

            /* if (IsInsert > 0)
             {
                 String invoice = " select distinct om.entry from OrderMaster om,order_detail od where om.Entry=od.MEntry and om.estatus='SV' order by om.Entry;";
                 response = IList_GetTable(invoice);
             }*/
            return IsInsert.ToString();


        }

        public int Invoice_OnSales_Delete(String jsondata)
        {
            int IsDelete = 0;
            JObject json_object = JObject.Parse(jsondata);

            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            int key = Convert.ToInt32(json_object["key_pk"].ToString());
            int voucherno = Convert.ToInt32(json_object["voucherno"].ToString());
            String type = json_object["Type"].ToString();
            DataTable st = new DataTable();

            String Select_Master = "select distinct  *  from voucher_cash where key_pk=" + key;




            String select = Select_Master;
            SqlTransaction trans = null;
            String json = "";

            String delete_voucher = "Delete from voucher_cash where key_pk=" + key + ";";

            String delete_ledger = "Delete from Ledger where type='" + type + "' and ref=" + voucherno + " and pidno=" + key + ";";

            String delete = delete_voucher + delete_ledger;

            DataSet ds = new DataSet();

            try
            {
                using (con = new SqlConnection(cs))
                {
                    con.Open();


                    using (adp = new SqlDataAdapter(select, con))
                    {
                        cmd = new SqlCommandBuilder(adp);
                        adp.Fill(ds);
                        json = JsonConvert.SerializeObject(ds.Tables[0]);


                    }

                    trans = con.BeginTransaction();

                    using (cm = new SqlCommand("Insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + key + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + User + "','" + system + "','Delete Entry','" + json + "')", con, trans))
                    {
                        cm.ExecuteNonQuery();
                    }


                    using (cm = new SqlCommand(delete, con, trans))
                    {
                        int a = cm.ExecuteNonQuery();
                        if (a > 0)
                        {
                            trans.Commit();
                            Update_Stock(st);
                            IsDelete = key;

                        }
                        else
                        {
                            trans.Rollback();
                            IsDelete = 0;

                        }
                    }

                }

            }
            catch (SqlException ex)
            {
                excp(ex.Message);

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
            return IsDelete;
        }

        public String Report_Aging(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String where = "", query = "";

            String token = json_Object["token"] == null ? "" : json_Object["token"].ToString();
            if (Authorization(token) <= 0)
            {
                json = "In-Valid";
                return json;
            }

            if (json_Object["invoice_date"].ToString() != String.Empty)
            {
                where += " and cast(sm.clkdate as Date)<='" + json_Object["invoice_date"].ToString().Trim() + "'";
            }

            if (json_Object["due_date"].ToString() != String.Empty)
            {
                where += " and  cast(sm.duedate as Date)<='" + json_Object["due_date"].ToString().Trim() + "'";
            }


            query = " select sm.key_pk,sm.invoice_no,ac.title,sm.clkdate,sm.duedate,DATEDIFF(day, sm.duedate,GETDATE()) as days," +
                    " sm.balance,isnull(voucher.recieved,0) as Recieved from Sales_Master sm " +
                    " left join(select invoice_pk_key, sum(ISNULL(amount,0)) as recieved from voucher_cash " +
                    " group by invoice_pk_key)voucher on voucher.invoice_pk_key = sm.key_pk inner join ac on ac.code=sm.acode " +
                    " where isnull(marked,0)=" + Convert.ToInt32(json_Object["marked"].ToString()) + " and sm.invtype = '" + json_Object["type"].ToString() + "' and DATEDIFF(day, sm.duedate,GETDATE())>=0 and (sm.balance-isnull(voucher.recieved,0))!=0 " + where + " order by sm.clkdate  ";




            return IList_GetTable(query);
        }

        public String Report_HotSellingProducts(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String where = "", query = "";
            int index = Convert.ToInt32(json_Object["index"].ToString());
            String token = json_Object["token"] == null ? "" : json_Object["token"].ToString();
            if (Authorization(token) <= 0)
            {
                json = "In-Valid";
                return json;
            }

            if (json_Object["idno"].ToString() != String.Empty)
            {
                where += " and im.idno=" + json_Object["idno"].ToString().Trim();
            }

            if (json_Object["item"].ToString() != String.Empty)
            {
                where += " and item.code='" + json_Object["item"].ToString().Trim() + "'";
            }
            if (json_Object["origin"].ToString() != String.Empty)
            {
                where += " and origin.code='" + json_Object["origin"].ToString().Trim() + "'";
            }
            if (json_Object["brand"].ToString() != String.Empty)
            {
                where += " and brand.code='" + json_Object["brand"].ToString().Trim() + "'";
            }
            if (json_Object["model"].ToString() != String.Empty)
            {
                where += " and model.code='" + json_Object["model"].ToString().Trim() + "'";
            }
            if (json_Object["maker"].ToString() != String.Empty)
            {
                where += " and maker.code='" + json_Object["maker"].ToString().Trim() + "'";
            }
            if (json_Object["reference"].ToString() != String.Empty)
            {
                where += " and rf.code='" + json_Object["reference"].ToString().Trim() + "'";
            }


            if (index == 0)
            {

                query = " select sd.acitno as Item_Id,im.partno as [PartNo],im.linkno,im.desc1 as [Desc],sum(sd.qty) as [Selling_Qty], " +
                        " im.inhnd as InHand,im.kept_place as[Kept Place],brand.name as brand,rtrim(maker.name) as Maker,rtrim(model.name) as Model,rtrim(origin.name) as [Origin],rtrim(rf.name) as [Reference] " +
                        " from Sales_Master sm inner join Sales_Detail sd on sm.key_pk = sd.key_fk inner join ac on ac.code = sm.acode left " +
                        " join itemlinked im on im.idno = sd.acitno left join origin on origin.code = im.origin  left join brand on brand.code = im.brnad  " +
                        " left join item on item.code = im.part left join model on model.id = im.model_maker  left join maker on maker.code = model.maker " +
                        " left join reference rf on rf.code = item.reference where DATEDIFF(day, sm.clkdate, GETDATE()) <= " + Convert.ToInt32(json_Object["days"].ToString()) + where +
                        " group by sd.acitno,im.desc1,im.partno,im.linkno,im.inhnd,im.kept_place,model.name,origin.name,rf.name,maker.name,brand.name";

            }
            else if (index == 1)
            {

                query = " select im.idno as Item_Id,im.partno as [PartNo],im.linkno,im.desc1 as [Desc],im.Inhnd as [InHand_Qty], " +
                        " im.kept_place as[Kept Place],brand.name as brand,rtrim(maker.name) as Maker,rtrim(model.name) as Model,rtrim(origin.name) as [Origin],rtrim(rf.name) as [Reference] " +
                        " from itemlinked im  left join origin on origin.code = im.origin  left join brand on brand.code = im.brnad  " +
                        " left join item on item.code = im.part left join model on model.id = im.model_maker  left join maker on maker.code = model.maker " +
                        " left join reference rf on rf.code = item.reference where im.Inhnd>0 and im.idno not in " +
                        "  ( select sd.acitno as Item_Id from Sales_Master sm inner join Sales_Detail sd on sm.key_pk = sd.key_fk " +
                        " where DATEDIFF(day, sm.clkdate, GETDATE()) < " + Convert.ToInt32(json_Object["days"].ToString()) + where + " and acitno is not null group by sd.acitno) ";

            }
            else
            {
                int days = Convert.ToInt32(json_Object["days"].ToString());

                query = " select a.Item_Id,im.partno as [PartNo],im.linkno,im.desc1 as [Desc],a.[Hot_Stock],a.[Dead_Stock],brand.name as brand,rtrim(maker.name) as Maker,rtrim(model.name) as Model,rtrim(origin.name) as [Origin],rtrim(rf.name) as [Reference] from ( " +
                      " select sd.acitno as Item_Id,im.partno as [PartNo],im.linkno,im.desc1 as [Desc],sum(sd.qty) as [Hot_Stock],null as [Dead_Stock] " +
                      " from Sales_Master sm inner join Sales_Detail sd on sm.key_pk = sd.key_fk  left  join itemlinked im on im.idno = sd.acitno  " +
                      " where sd.acitno>0   and   DATEDIFF(day, sm.clkdate, GETDATE()) <=" + days + "  group by sd.acitno,im.desc1,im.partno,im.linkno,im.kept_place " +
                      " union all " +
                      " select im.idno as Item_Id,im.partno as [PartNo],im.linkno,im.desc1 as [Desc],null as [Hot_Stock],im.Inhnd as [InHand_Qty]  " +
                      " from itemlinked im   where im.Inhnd>0 and im.idno not in  " +
                      " ( select sd.acitno as Item_Id from Sales_Master sm inner join Sales_Detail sd on sm.key_pk = sd.key_fk  " +
                      " where DATEDIFF(day, sm.clkdate, GETDATE()) < " + days + " and acitno is not null group by sd.acitno) ) a left join itemlinked im on im.idno = a.Item_Id " +
                      " left join origin on origin.code = im.origin  left join brand on brand.code = im.brnad  left join item on item.code = im.part left join model on model.id = im.model_maker  " +
                      " left join maker on maker.code = model.maker left join reference rf on rf.code = item.reference " +
                      " where a.Item_Id>0 " + where;
            }

            return IList_GetTable(query);
        }

        public String PendingQuotation(String acode)
        {

            String data = "";
            String query = " declare  @id varchar(250); set @id='" + acode + "';" +
                            " select isnull(isnull(a.debit,0)-ISNULL(b.credit,0),0) from ac " +
                            " left join (select d_acode,sum(isnull(d_amt,0)) as debit from Ledger where rtrim(d_acode)='" + acode + "' group by d_acode)a on a.d_acode=ac.code " +
                            " left join (select c_acode,sum(isnull(c_amt,0)) as credit from Ledger where rtrim(c_acode)='" + acode + "' group by c_acode)b " +
                            " on b.c_acode=ac.code left join city on city.code=ac.city_code left join market on market.code=ac.market " +
                            " where ac.type='Child' and rtrim(ac.code)='" + acode + "' order by ac.title;" +

                           " select t1.key_pk,t1.invoice_no,ac.title,t1.vn_number,t1.reg_number,t1.date,sum(t1.Quotation_Qty) as Quotation_Qty," +
                           " sum(ISNULL(t2.Sales_Qty,0)) as Sales_Qty,u.USERS_NAME,au.USERS_NAME as auth_by,t1.closed from(  " +
                           " select qm.key_pk,qm.invoice_no,qm.date,qm.acode,qm.vn_number,qm.reg_number,qm.users,qm.auth_by,qm.closed,qd.acitno, sum(qd.qty) as Quotation_Qty " +
                           " from Quotation_Master qm inner  join Quotation_Detail qd on qm.key_pk = qd.key_fk where qm.acode = @id " +
                           " group by qm.key_pk,qm.invoice_no,qm.vn_number,qm.reg_number,qm.date,qm.acode,qm.users,qm.closed,qm.auth_by, qd.acitno )t1 left JOIN( " +
                           " select qm.key_pk, qm.quotation_no, qd.acitno, sum(qd.qty) as Sales_Qty from Sales_Master qm " +
                           " inner join Sales_Detail qd on qm.key_pk = qd.key_fk " +
                           " where acode = @id  and quotation_no is not null group by qm.quotation_no, qm.key_pk, qd.acitno " +
                           " )t2 on t1.key_pk = t2.quotation_no  and t1.acitno=t2.acitno left join USERS u on u.USERS = t1.users left join USERS au on au.USERS = t1.auth_by " +
                           " inner join ac on ac.code = t1.acode where closed = 0 " +
                           " group by t1.key_pk,t1.invoice_no,ac.title,t1.vn_number,t1.reg_number,t1.date,t1.auth_by,t1.closed,U.USERS_NAME,au.USERS_NAME " +
                           " having  sum(t1.Quotation_Qty) - sum(ISNULL(t2.Sales_Qty, 0)) > 0 ";



            data = IList_GetDataSet(query);
            return data;
        }

        public String PendingQuotationByKey(String json)
        {
            JObject json_Object = JObject.Parse(json);


            int idno = Convert.ToInt32(json_Object["idno"].ToString());
            String query = "";

            query = "  select t1.invoice_no,ac.code,t1.date,t1.Quotation_Qty,isnull(t2.Sales_Qty,0) as Sales_Qty,qd.* from(  " +
                    "  select qm.key_pk,qm.invoice_no,qm.date,qm.acode,qm.users,qm.auth_by,qm.closed,qd.acitno,qd.rate, sum(qd.qty) as Quotation_Qty " +
                    "  from Quotation_Master qm inner   join Quotation_Detail qd on qm.key_pk = qd.key_fk where qm.key_pk=" + idno + " " +
                    "  group by qm.key_pk,qm.invoice_no, qd.acitno,qd.rate,qm.date,qm.acode,qm.users,qm.closed,qm.auth_by)t1 full outer JOIN(  " +
                    "  select qm.key_pk, qm.quotation_no, qd.acitno,qd.rate as Inv_Rate, sum(qd.qty) as Sales_Qty from Sales_Master qm  " +
                    "  inner join Sales_Detail qd on qm.key_pk = qd.key_fk  " +
                    "  where  quotation_no is not null group by qm.quotation_no,qm.key_pk,qd.acitno,qd.rate)t2 on t1.key_pk = t2.quotation_no  and t1.acitno=t2.acitno " +
                    "  left join USERS u on u.USERS=t1.users left join USERS au on au.USERS=t1.auth_by inner join ac on ac.code=t1.acode  inner join itemlinked im on im.idno=t1.acitno inner join brand br on im.brnad=br.code " +
                    "  inner join Quotation_Detail qd on qd.key_fk=t1.key_pk and qd.acitno=idno";

            return IList_GetDataSet(query);
        }

        public String PendingArrival()
        {


            String data = "";
            //String query = " declare  @id varchar(250); set @id='" + acode + "';" +
            String query = " " +

                      " select t1.*,ac.title,t2.key_pk as invoice_key,t2.invoice_no as purchase_no,t2.arrival_no as refno,ISNULL(t2.Purchase_Qty, 0) as Purchase_Qty," +
                      "im.idno,t1.invdesc as desc1,t1.prtno as partno,t1.bn,t1.rate from( " +

                      " select qm.key_pk, qm.invoice_no, qm.date, qm.acode, qm.users, qd.acitno,qd.prtno,qd.bn,qd.invdesc,qd.rate, sum(qd.qty) as Arrival_Qty " +
                      " from Arrivals_Master qm inner join Arrival_Detail qd on qm.key_pk = qd.key_fk " +
                      " where qm.acode is not null   and qm.closed = 0 " +
                      " group by qm.key_pk,qm.invoice_no,qm.date,qm.acode,qm.users,qm.closed, qd.acitno,qd.prtno,qd.bn,qd.invdesc,qd.rate)t1 left join( " +

                      " select qm.key_pk, qm.invoice_no, qd.arrival_no, qd.acitno,sum(qd.qty) as Purchase_Qty from Purchase_Master qm " +
                      " inner join Purchase_Detail qd on qm.key_pk = qd.key_fk " +
                      " where acode is not null and arrival_no is not null  group by  qm.key_pk,qm.invoice_no, qd.acitno,qd.arrival_no " +
                      " )t2 on t1.key_pk = t2.arrival_no and t1.acitno=t2.acitno inner join itemlinked im on im.idno = t1.acitno inner join ac on ac.code = t1.acode " +
                      " where(t1.Arrival_Qty - ISNULL(t2.Purchase_Qty, 0)) > 0 ; ";





            data = IList_GetTable(query);
            return data;
        }


        DataTable getBalance(String ac)
        {
            String query = " select  ac.code,ac.d_limit,sum(isnull(dr.debit,0))-sum(isnull(cr.credit,0)) as Balance from  ac " +
                         " inner join(select l.d_acode,sum(ISNULL(d_amt,0)) as debit from Ledger l group by l.d_acode)dr on dr.d_acode=ac.code " +
                         " inner join(select l.c_acode,sum(ISNULL(c_amt,0)) as credit from Ledger l group by l.c_acode)cr on cr.c_acode=ac.code " +
                         " where ac.type='Child' and d_limit is not null and LTRIM(RTRIM(ac.code))='" + ac.Trim() + "'  group by ac.code,ac.title,ac.d_limit ;";

            DataTable dt = new DataTable();
            try
            {
                using (con = new SqlConnection(cs))
                {
                    con.Open();


                    using (adp = new SqlDataAdapter(query, con))
                    {
                        cmd = new SqlCommandBuilder(adp);
                        adp.Fill(dt);

                    }

                }

            }
            catch (SqlException ex)
            {
                excp(ex.Message);
            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
            return dt;
        }


        public String GetAccount(String token, String json)
        {
            if (token.Trim() != app_key)
            {
                return "404";
            }

            String query = "select code,title from ac where type='Child'  order by title";
            return IList_GetTable(query);
        }

        public String GetBalance(String token, String code)
        {
            string json = "";
            if (token != "")
            {
                if (Authorization(token) <= 0)
                {
                    json = "In-Valid";
                    return json;
                }
            }

            String query = " select isnull(isnull(a.debit,0)-ISNULL(b.credit,0),0) as balance" +
                           "     from ac " +
                          "     left join (select d_acode,sum(isnull(d_amt,0)) as debit from Ledger where rtrim(d_acode)='" + code + "' group by d_acode)a on a.d_acode=ac.code " +
                          "     left join (select c_acode,sum(isnull(c_amt,0)) as credit from Ledger where rtrim(c_acode)='" + code + "' group by c_acode)b " +
                          "     on b.c_acode=ac.code  " +
                          "     where  rtrim(ac.code)='" + code + "'";

            return IList_GetTable(query);
        }

        public String GetProduct(String token)
        {
            string json = "";
            if (token.Trim() != app_key)
            {
                return "404";
            }

            String query = " select idno,partno,linkno from itemlinked;";

            return IList_GetTable(query);
        }

        public String getVerifyStock(int product, string token)
        {
            string json = "";
            if (token != "")
            {
                if (Authorization(token) <= 0)
                {
                    json = "In-Valid";
                    return json;
                }
            }
            String stock = "select product,st.warehouse,(sum(ISNULL(rec,0))-sum(ISNULL(iss,0))) as Balance from stock st " +
                           " inner join warehouse wh on wh.id = st.warehouse inner join itemlinked im on im.idno = st.product " +
                           " where im.idno = " + product + " group by product,st.warehouse  ;";

            String query = " select * from godown_verify gd inner join godown_verify_detail gdf on gd.id=gdf.pid where product=" + product + " ; " +
                           " select * from warehouse order by name; " +
                            stock;

            return IList_GetDataSet(query);
        }

        public String VerifyStock_Insert(String json)
        {

            JObject json_object = JObject.Parse(json);
            String child = json_object["Child"].ToString();
            DataTable table = (DataTable)JsonConvert.DeserializeObject(child, (typeof(DataTable)));
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            String type = json_object["Type"].ToString();
            String date = json_object["edate"].ToString();
            int product = Convert.ToInt32(json_object["product"].ToString());
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int invno = 0;
            int key = json_object["key"].ToString() == "" ? 0 : Convert.ToInt32(json_object["key"].ToString());
            String response = "";

            DataSet dt = new DataSet();
            SqlTransaction trans = null;
            String detail, Insert, Update, stock, Select_Master, Select_Child, Delete, Update_Status, stock_adjust;
            detail = Insert = Update = stock = Select_Master = Select_Child = Delete = Update_Status = stock_adjust = "";
            {
                detail = " insert into godown_verify_detail(pid,warehouse,stock_qty,adjust_qty,op_qty,rate,amount,remarks) values(@pid,@warehouse,@stock_qty,@adjust_qty,@op_qty,@rate,@amount,@remarks); ";
                Insert = " insert into godown_verify(product,edate) values(@product,@edate);select SCOPE_IDENTITY() as code; ";
                Update = " Update godown_verify set edate=@edate where product=@product;";

                stock = "insert into stock(pidno,cidno,edate,refno,estatus,product,description,rec,iss,rate,gross_amount,disc_rate,disc_p,disc,net_amount,warehouse,remarks) " +
                        "  values (@pid,(select SCOPE_IDENTITY()),@edate,@refno,@type,@item,@desc,@rec,@iss,@rate,@amt,@rate,0,0,@amount,@warehouse,@remarks);";

                Select_Master = "select distinct  *  from godown_verify  where product=" + product;
                Select_Child = "select distinct  sd.*  from godown_verify sm inner join godown_verify_detail sd on sm.id=sd.pid where sm.product=" + product;

                Delete = " delete from stock where estatus='" + type + "' and product=" + product + " and refno=" + key + ";" +
                               "  delete from godown_verify_detail where pid=" + key + ";";

                Update_Status = "update itemlinked set verified=1 where idno=" + product;

            }
            int adjust_qty, rec, iss;
            adjust_qty = rec = iss = 0;
            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();

                    if (key == 0)
                    {
                        using (cm = new SqlCommand(Insert, con, trans))
                        {

                            cm.Parameters.AddWithValue("product", json_object["product"].ToString());
                            cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                            key = Convert.ToInt32(cm.ExecuteScalar());
                            rowseffected = 1;

                        }

                    }

                    else
                    {
                        using (cm = new SqlCommand(Update, con, trans))
                        {

                            cm.Parameters.AddWithValue("product", json_object["product"].ToString());
                            cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());

                            rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());


                        }
                    }

                    if (key > 0)
                    {
                        using (cm = new SqlCommand(Delete, con, trans))
                        {

                            cm.ExecuteNonQuery();

                        }
                    }

                    if (rowseffected > 0)
                    {
                        rowseffected = 0;

                        using (cm = new SqlCommand(detail + ";" + stock, con, trans))
                        {

                            cm.Parameters.Add("pid", SqlDbType.Int);
                            cm.Parameters.Add("edate", SqlDbType.DateTime);
                            cm.Parameters.Add("refno", SqlDbType.Int);
                            cm.Parameters.Add("type", SqlDbType.VarChar);
                            cm.Parameters.Add("item", SqlDbType.Int);
                            cm.Parameters.Add("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amt", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amount", SqlDbType.Decimal);
                            cm.Parameters.Add("remarks", SqlDbType.VarChar);

                            cm.Parameters.Add("desc", SqlDbType.VarChar);
                            cm.Parameters.Add("rec", SqlDbType.Decimal);
                            cm.Parameters.Add("iss", SqlDbType.Decimal);
                            cm.Parameters.Add("warehouse", SqlDbType.Int);


                            cm.Parameters.Add("stock_qty", SqlDbType.Int);
                            cm.Parameters.Add("adjust_qty", SqlDbType.Int);
                            cm.Parameters.Add("op_qty", SqlDbType.Int);




                            foreach (DataRow row in table.Rows)
                            {
                                if (Convert.ToInt32(row["adjust_qty"]) != 0)
                                {
                                    adjust_qty = Convert.ToInt32(row["adjust_qty"].ToString());
                                    rec = adjust_qty >= 0 ? adjust_qty : 0;
                                    iss = adjust_qty < 0 ? (adjust_qty) * -1 : 0;

                                    cm.Parameters["pid"].Value = key;
                                    cm.Parameters["edate"].Value = date;
                                    cm.Parameters["refno"].Value = key;
                                    cm.Parameters["type"].Value = type;
                                    cm.Parameters["item"].Value = product;
                                    cm.Parameters["rate"].Value = 0;
                                    cm.Parameters["amt"].Value = 0;
                                    cm.Parameters["disc_rate"].Value = 0;
                                    cm.Parameters["amount"].Value = 0;

                                    cm.Parameters["remarks"].Value = row["remarks"].ToString();
                                    cm.Parameters["desc"].Value = "ADJUST QTY";
                                    cm.Parameters["rec"].Value = rec;
                                    cm.Parameters["iss"].Value = iss;
                                    cm.Parameters["warehouse"].Value = Convert.ToInt32(row["id"]);

                                    cm.Parameters["stock_qty"].Value = Convert.ToInt32(row["stock_qty"]);
                                    cm.Parameters["adjust_qty"].Value = Convert.ToInt32(row["adjust_qty"]);
                                    cm.Parameters["op_qty"].Value = Convert.ToInt32(row["op_qty"]);

                                    rowseffected += cm.ExecuteNonQuery();
                                }
                            }

                        }

                        using (cm = new SqlCommand(detail + stock, con, trans))
                        {
                            cm.Parameters.Add("pid", SqlDbType.Int);
                            cm.Parameters.Add("warehouse", SqlDbType.Int);
                            cm.Parameters.Add("stock_qty", SqlDbType.Int);
                            cm.Parameters.Add("adjust_qty", SqlDbType.Int);
                            cm.Parameters.Add("op_qty", SqlDbType.Int);

                            cm.Parameters.Add("remarks", SqlDbType.VarChar);
                            cm.Parameters.Add("desc", SqlDbType.VarChar);
                            cm.Parameters.Add("item", SqlDbType.Int);
                            cm.Parameters.Add("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amt", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amount", SqlDbType.Decimal);

                            cm.Parameters.Add("edate", SqlDbType.DateTime);
                            cm.Parameters.Add("refno", SqlDbType.Int);
                            cm.Parameters.Add("type", SqlDbType.VarChar);
                            cm.Parameters.Add("rec", SqlDbType.Decimal);
                            cm.Parameters.Add("iss", SqlDbType.Decimal);


                            foreach (DataRow row in table.Rows)
                            {
                                if (Convert.ToInt32(row["op_qty"].ToString()) != 0)
                                {

                                    adjust_qty = Convert.ToInt32(row["op_qty"].ToString());
                                    rec = adjust_qty >= 0 ? adjust_qty : 0;
                                    iss = adjust_qty < 0 ? (adjust_qty) * -1 : 0;

                                    cm.Parameters["pid"].Value = key;
                                    cm.Parameters["warehouse"].Value = Convert.ToInt32(row["id"]);
                                    cm.Parameters["stock_qty"].Value = Convert.ToInt32(row["stock_qty"]);
                                    cm.Parameters["adjust_qty"].Value = Convert.ToInt32(row["adjust_qty"]);
                                    cm.Parameters["op_qty"].Value = Convert.ToInt32(row["op_qty"]);

                                    cm.Parameters["edate"].Value = date;
                                    cm.Parameters["refno"].Value = key;
                                    cm.Parameters["type"].Value = type;
                                    cm.Parameters["item"].Value = product;

                                    cm.Parameters["remarks"].Value = row["remarks"].ToString();
                                    cm.Parameters["desc"].Value = "OPENING QTY";
                                    cm.Parameters["rec"].Value = rec;
                                    cm.Parameters["iss"].Value = iss;
                                    cm.Parameters["rate"].Value = Convert.ToDecimal(row["rate"]);
                                    cm.Parameters["amt"].Value = Convert.ToDecimal(row["amount"]);
                                    cm.Parameters["disc_rate"].Value = Convert.ToDecimal(row["rate"]);
                                    cm.Parameters["amount"].Value = Convert.ToDecimal(row["amount"]);

                                    cm.Parameters["warehouse"].Value = Convert.ToInt32(row["id"]);


                                    rowseffected += cm.ExecuteNonQuery();
                                }

                            }

                        }


                        if (rowseffected > 0)
                        {
                            using (cm = new SqlCommand(Update_Status, con, trans))
                            {

                                cm.ExecuteNonQuery();

                            }

                            Select_Master += invno;
                            Select_Child += invno;


                            using (adp = new SqlDataAdapter(Select_Master + ";" + Select_Child, con))
                            {
                                adp.SelectCommand.Transaction = trans;

                                cmd = new SqlCommandBuilder(adp);
                                adp.Fill(dt);
                                dt.Tables[0].TableName = "Master";
                                dt.Tables[1].TableName = "Child";

                            }

                            String JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                            using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + key + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + (User) + "','" + (system) + "','New Entry','" + JSONString + "')", con, trans))
                            {

                                rows = cm.ExecuteNonQuery();

                            }

                            if (rows > 0)
                            {

                                trans.Commit();
                                IsInsert = key;

                            }
                            else
                            {
                                trans.Rollback();
                                IsInsert = 0;
                            }

                        }

                        else
                        {
                            trans.Rollback();
                            IsInsert = 0;
                        }

                    }

                    else
                    {
                        trans.Rollback();
                        IsInsert = 0;

                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                response = ex.Message;
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }

            return IsInsert.ToString();


        }

        public String VerifyStock_Update(String json)
        {
            JObject json_object = JObject.Parse(json);
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            String type = json_object["Type"].ToString();
            String date = json_object["edate"].ToString();
            int product = Convert.ToInt32(json_object["product"].ToString());
            int key = json_object["key"].ToString() == "" ? 0 : Convert.ToInt32(json_object["key"].ToString());


            String Update_Status = "update itemlinked set verified=1 where idno=" + product;
            SqlTransaction trans = null;
            int rows = 0;
            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();
                    using (cm = new SqlCommand(Update_Status, con, trans))
                    {

                        cm.ExecuteNonQuery();

                    }

                    using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + product + ",'" + type + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + (User) + "','" + (system) + "','New Entry',' ')", con, trans))
                    {

                        rows = cm.ExecuteNonQuery();
                        if (rows > 0)
                        {
                            trans.Commit();
                        }

                    }
                }
            }
            catch (SqlException ex)
            {
                excp(ex.Message);
                trans.Rollback();

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }
            return rows.ToString();
        }

        public String VerifyStock_Reset(String json)
        {
            JObject json_object = JObject.Parse(json);
            int product = Convert.ToInt32(json_object["product"].ToString());
            string token = json_object["token"].ToString();
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();

            if (token != "")
            {
                if (Authorization(token) <= 0)
                {
                    json = "In-Valid";
                    return json;
                }
            }

            String query = "select id from godown_verify where product=" + product;
            int id = IList_ExecuteScalerValue(query);

            query = "  delete from godown_verify_detail where pid=" + id + ";";
            query += " delete from godown_verify where id=" + id + ";";
            query += " delete from stock where estatus='VS' and product=" + product + " and pidno=" + id + ";";
            query += " update itemlinked set verified=0 where idno=" + product;

            String Select_Master = "select distinct  *  from godown_verify  where product=" + product;
            String Select_Child = "select distinct  sd.*  from godown_verify sm inner join godown_verify_detail sd on sm.id=sd.pid where sm.product=" + product;

            DataSet dt = new DataSet();
            SqlTransaction trans = null;
            String Insert = "";
            try
            {
                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();
                    using (adp = new SqlDataAdapter(Select_Master + ";" + Select_Child, con))
                    {
                        adp.SelectCommand.Transaction = trans;

                        cmd = new SqlCommandBuilder(adp);
                        adp.Fill(dt);
                        dt.Tables[0].TableName = "Master";
                        dt.Tables[1].TableName = "Child";

                    }

                    String JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);



                    using (cm = new SqlCommand(query, con, trans))
                    {
                        if (cm.ExecuteNonQuery() > 0)
                        {
                            Insert = "1";

                            using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data) values(" + product + ",'VS','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + (User) + "','" + (system) + "','Modified Entry','" + JSONString + "')", con, trans))
                            {

                                cm.ExecuteNonQuery();

                            }

                            trans.Commit();
                        }
                        else
                        {
                            Insert = "0";
                            trans.Rollback();
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                Insert = "";
                excp(ex.Message);
                trans.Rollback();
            }

            return Insert;
        }

        public String Stock_In_Hand(String json)
        {
            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString();
            String action = json_object["action"].ToString();
            int product = Convert.ToInt32(json_object["product"].ToString());
            int invoice = json_object["invoice"].ToString().Trim() == "" ? 0 : Convert.ToInt32(json_object["invoice"].ToString());
            int key = json_object["idno"].ToString().Trim() == "" ? 0 : Convert.ToInt32(json_object["idno"].ToString());
            String type = json_object["type"].ToString();
            String query = "";
            String remaining = "";
            if (token != "")
            {
                if (token != app_key)
                {
                    json = "In-Valid";
                    return json;
                }
            }

            query = " select im.idno,(sum(ISNULL(rec,0))-sum(ISNULL(iss,0))) as Balance from stock st " +
                        " inner join itemlinked im on im.idno = st.product " +
                        " where im.idno = " + product + "" +
                        " group by im.idno ";

            remaining = " select product,sum(isnull(iss,0)) as remaining from stock" +
                        " where estatus='" + type + "' and refno=" + invoice + " and pidno=" + key + " and product=" + product +
                        " group by product";


            return IList_GetDataSet(query + remaining);

        }

        public String LedgerInvoice(String json)
        {
            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString();
            if (token != "")
            {
                if (Authorization(token) <= 0)
                {
                    json = "In-Valid";
                    return json;
                }
            }

            String query = " select distinct  sm.key_pk,sm.clkdate,sm.days,sm.duedate,sm.dscr_p as inv_disc,sm.disc as inv_disc_amt, case when sd.line_warehouse is null then sm.warehouse else sd.line_warehouse end as warehouse,sm.mrdminv_no,sm.invtype,sm.invoice_no,sm.acode,sm.prtclar,sm.expmnininv,sm.courier,sm.gstp,sm.gsta,sm.itp,sm.ita,sm.o_chgs,sm.prtclar,sm.sglc,sm.auth_by,sm.quotation_no,sm.collection,sm.balance,sm.closed,sd.citmno,sd.prtno,sd.bn" +
                      " ,sd.key_fk,sd.key_pk as sn,sd.vndrcd,sd.acitno,sd.invdesc,sd.subdesc,sd.qty,sd.rate,sd.amt,sd.dscrate,sd.disc,sd.dscr_p,sd.ntamt,sd.line_warehouse from " + json_object["Master"].ToString() + " sm inner join " + json_object["Child"].ToString() + " sd on sm.key_pk=sd.key_fk " +
                      " where  sm.invoice_no=" + json_object["invoice_no"].ToString() + " order by sn;";

            return IList_GetTable(query);
        }

        public String LedgerDropDown(String token)
        {

            if (token != "")
            {
                if (Authorization(token) <= 0)
                {
                    return "In-Valid";
                }
            }

            String query = "select ac.code,ac.title,ac.d_limit, " +
                " case when (sum(debit)-sum(credit))>=0 then sum(debit)-sum(credit) end as Debit, " +
                " case when (sum(debit)-sum(credit))<0 then (sum(debit)-sum(credit))*-1 end as Credit" +
                " from (select d_acode as acode,sum(isnull(d_amt,0)) as debit,null as credit from Ledger group by d_acode" +
                " union all " +
                " select c_acode as acode,null as debit,sum(isnull(c_amt,0)) as credit from Ledger group by c_acode ) a right join ac on ac.code=a.acode" +
                " group by ac.code,ac.title,ac.d_limit order by ac.title;";

            query += " select top 1 LEN(title) lenth from ac order by lenth desc;";

            return IList_GetDataSet(query);
        }

        public String Account_Transfer(String json)
        {
            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString();
            String acode_from = json_object["from"].ToString().Trim();
            String acode_to = json_object["to"].ToString().Trim();
            if (token != "")
            {
                if (Authorization(token) <= 0)
                {
                    json = "In-Valid";
                    return json;
                }
            }

            String response = "";
            int IsInsert = 0;

            String query = "";
            {
                query +=
                    "declare @acode_from char(34);set @acode_from='" + acode_from + "';" +
                    "declare @acode_to char(34);set @acode_to='" + acode_to + "';" +

                    " Update Arrivals_Master set acode=@acode_to  where acode=@acode_from; " +


                    " Update general_journal set d_acode = @acode_to where d_acode = @acode_from;" +
                    " Update general_journal set c_acode = @acode_to where c_acode = @acode_from;" +

                    " Update Ledger set d_acode = @acode_to where d_acode = @acode_from;" +
                    " Update Ledger set c_acode = @acode_to where c_acode = @acode_from;" +

                    " Update Order_Master set acode = @acode_to where acode = @acode_from;" +
                    " Update Order_Master set c_code = @acode_to where c_code = @acode_from;" +

                    " Update Purchase_Master set acode = @acode_to where acode = @acode_from;" +
                    " Update Purchase_Master set c_code = @acode_to where c_code = @acode_from;" +

                    " Update Purchase_Return_Master set acode = @acode_to where acode = @acode_from;" +
                    " Update Purchase_Return_Master set c_code = @acode_to where c_code = @acode_from;" +

                    " Update Purchase_Order set acode = @acode_to where acode = @acode_from;" +
                    " Update Purchase_Order set c_code = @acode_to where c_code = @acode_from;" +

                    " Update Quotation_Master set acode = @acode_to where acode = @acode_from;" +
                    " Update Quotation_Master set c_code = @acode_to where c_code = @acode_from;" +

                    " Update Sales_Master set acode = @acode_to where acode = @acode_from;" +
                    " Update Sales_Master set c_code = @acode_to where c_code = @acode_from;" +

                    " Update Sales_Return_Master set acode = @acode_to where acode = @acode_from;" +
                    " Update Sales_Return_Master set c_code = @acode_to where c_code = @acode_from;" +

                    " Update stock set acode = @acode_to where acode = @acode_from;" +

                    " Update voucher_cash set d_code = @acode_to where d_code = @acode_from;" +
                    " Update voucher_cash set c_code = @acode_to where c_code = @acode_from;" +

                    " Update vouchermaster set maincode = @acode_to where maincode = @acode_from;" +
                    " Update voucherdetail set acode = @acode_to where acode = @acode_from;";

            }

            SqlTransaction trans = null;
            try
            {
                using (con = new SqlConnection(cs))
                {
                    con.Open();
                    trans = con.BeginTransaction();
                    cm = new SqlCommand(query, con, trans);
                    IsInsert = Convert.ToInt32(cm.ExecuteNonQuery());
                    if (IsInsert >= 0)
                    {
                        response = "1";
                        trans.Commit();
                    }
                    else
                    {
                        response = "0";
                    }
                }
            }
            catch (SqlException ex)
            {
                response = ex.Message;
                excp(ex.Message);
            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }

            return response;

        }

        public String Get_Purchase_Invoice(String json)
        {


            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString();
            String invoice_no = json_object["invoice_no"].ToString().Trim();
            String id = json_object["id"].ToString().Trim();
            String Master = json_object["Master"].ToString();
            String Child = json_object["Child"].ToString();
            String action = json_object["action"].ToString();

            if (token != "")
            {
                if (Authorization(token) <= 0)
                {
                    json = "In-Valid";
                    return json;
                }
            }

            String query = " select distinct  sm.key_pk,sm.clkdate,sm.days,sm.duedate,sm.dscr_p as inv_disc,sm.disc as inv_disc_amt, case when sd.line_warehouse is null then sm.warehouse else sd.line_warehouse end as warehouse,sm.mrdminv_no,sm.invtype,sm.invoice_no,sm.acode,sm.prtclar,sm.expmnininv,sm.courier,sm.gstp,sm.gsta,sm.itp,sm.ita,sm.o_chgs,sm.prtclar,sm.sglc,sm.auth_by,sm.quotation_no,sm.collection,sm.balance,sm.closed,sd.citmno,sd.prtno,sd.bn" +
                        " ,sd.key_fk,sd.key_pk as sn,sd.vndrcd,sd.acitno,sd.invdesc,sd.subdesc,sd.qty,sd.rate,sd.amt,sd.dscrate,sd.disc,sd.dscr_p,sd.ntamt,sd.line_warehouse,sd.arrival_no,sd.arrival_key from " + json_object["Master"] + " sm inner join " + json_object["Child"] + " sd on sm.key_pk=sd.key_fk ";


            if (action == "Get Purchase Invoice")
            {

                query += " where sm.key_pk=" + id + " or sm.invoice_no=" + invoice_no + " order by sn;";

            }

            else if (action == "Purchase Invoice Next")
            {
                int invoice = 0;
                invoice = Invoice_Next(Convert.ToInt32(id), Master, Child);
                query += " where sm.key_pk=" + invoice + " order by sn";


            }

            else if (action == "Purchase Invoice Previous")
            {
                int invoice = 0;
                invoice = Invoice_Previous(Convert.ToInt32(id), Master, Child);
                query += " where sm.key_pk=" + invoice + " order by sn";

            }

            else if (action == "Purchase Invoice First")
            {
                int invoice = 0;
                invoice = Invoice_First(Master, Child);
                query += " where sm.key_pk=" + invoice + " order by sn";

            }

            else if (action == "Purchase Invoice Last")
            {
                int invoice = 0;
                invoice = Invoice_Last(Master, Child);
                query += " where sm.key_pk=" + invoice + " order by sn";

            }

            return IList_GetTable(query);
        }

        public String Account_Info2(String json)
        {
            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString();
            String ac = json_object["ac"].ToString().Trim();
            String where = "";
            if (token != "")
            {
                if (Authorization(token) <= 0)
                {
                    return "In-Valid";
                }
            }

            if (ac.Trim() != String.Empty)
            {
                where = " and ac.code = '" + ac.Trim() + "'";
            }

            String query = " select  ac.code,ac.d_limit,ac.person,sum(isnull(dr.debit,0))-sum(isnull(cr.credit,0)) as Balance from  ac " +
                         " inner join(select l.d_acode,sum(ISNULL(d_amt,0)) as debit from Ledger l group by l.d_acode)dr on dr.d_acode=ac.code " +
                         " inner join(select l.c_acode,sum(ISNULL(c_amt,0)) as credit from Ledger l group by l.c_acode)cr on cr.c_acode=ac.code " +
                         " where ac.type='Child'  " + where + "  group by ac.code,ac.title,ac.d_limit,ac.person ;";



            return IList_GetTable(query);
        }

        public String Test()
        {
            return "value";
        }

        public string PostImage(Stream sm)
        {
            System.Drawing.Bitmap imag = new System.Drawing.Bitmap(sm);
            byte[] imagedata = ImageToByte(imag);
            //Write code here to Save byte code to database..  

            MemoryStream ms = new MemoryStream(imagedata);
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
            img.Save(@"D:\sample.png", System.Drawing.Imaging.ImageFormat.Png);

            return "success";
        }

        public static byte[] ImageToByte(System.Drawing.Image img)
        {

            System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
            return (byte[])converter.ConvertTo(img, typeof(byte[]));
        }

        public String DeleteImage(String json)
        {
            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString();
            String id = json_object["id"].ToString().Trim();
            String code = json_object["code"].ToString().Trim();
            String name = json_object["name"].ToString();

            if (token != "")
            {
                if (Authorization(token) <= 0)
                {
                    json = "In-Valid";
                    return json;
                }
            }
            String response = "";
           /* String absolute = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
            string apPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + @"images\" + code.Trim();
            String file = apPath.Trim() + @"\" + name + ".png";
            String image_path = (@"\") + code.Trim() + (@"\") + name + ".png";*/
            try
            {
               /* if (File.Exists(file))
                {
                    File.Delete(file);
               
                }*/

                response = IList_execute("Delete from inspection_images where id=" + id).ToString();




            }
            catch (Exception ex)
            {
                response = ex.Message;
            }

            return response;
        }
    }
}