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
    {
        #region InspectionForm

        public String LoadInspection(String Token)
        {
            if (Token.Trim() != app_key)
            {
                return "404";
            }
            String data = "";
            String query = " select * from inspection_category order by id;" +
                           " select * from inspection_parameter;" +
                           " select id from inspection_master order by id;" +
                           " select distinct chasis_no from inspection_master;" +
                           " select * from inspection_charges;" +
                           " select distinct contactno from inspection_master;";
            data = IList_GetDataSet(query);
            return data;
        }

        public String Inspection_Insert(String json)
        {
            JObject json_object = JObject.Parse(json);
            String Token = json_object["token"].ToString();
            if (Token.Trim() != app_key)
            {
                return "404";
            }

            DataTable table = (DataTable)JsonConvert.DeserializeObject(json_object["Child"].ToString(), (typeof(DataTable)));
            DataTable table_ledger = (DataTable)JsonConvert.DeserializeObject(json_object["Ledger"].ToString(), (typeof(DataTable)));
            String vtype = json_object["Type"].ToString();

            String q1 = "select code from vehicle where LTRIM(RTRIM(vin))='" + (json_object["chasis_no"]).ToString().Trim() + "'";
            int isvalid = IList_ExecuteScalerValue(q1);
            if (isvalid == 0)
            {
                return "-2";
            }

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

            DataTable ds = new DataTable();
            dt.Tables.Add(ds);
            SqlTransaction trans = null;

            String OrderMaster =  " INSERT INTO [dbo].[inspection_master] " +
                                  " ([vno],[reg_no],[model],[mileage],[chasis_no],[colour],[make],[fuel_type],[variant],[years],[tr_type], " +
                                  " [eng_no],[ins_date],[charges],[paid],[balance],[customer],[contactno],[comments],[acode],[itype],[stats],[pay_date],[ent_no],[created_by]) values" +
                                  " (@vno,@reg_no,@model,@mileage,@chasis_no,@colour,@make,@fuel_type,@variant,@years,@tr_type, " +
                                  " @eng_no,@ins_date,@charges,@paid,@balance,@customer,@contactno,@comments,@acode,@itype,@stats,@pay_date,@entryno,@created_by) ;select SCOPE_IDENTITY() as code;";

            String OrderDetails = " INSERT INTO [dbo].[inspection_detail] " +
                                  " (pidno,inspection_master,inpection_parameter,istatus,remarks) values" +
                                  " (@pidno,@inspection_master,@inpection_parameter,@istatus,@remarks)";

            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);";


            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 isnull(cast( vno as int),0) from inspection_master order by cast( vno as int) desc", con, trans))
                    {
                        var val = cm.ExecuteScalar();
                        if (val == null || val == DBNull.Value)
                        {
                            vno = 1;
                        }
                        else
                        {
                            vno = Convert.ToInt32(val) + 1;
                        }
                    }

                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {
                        cm.Parameters.AddWithValue("vno", vno);
                        cm.Parameters.AddWithValue("reg_no", (json_object["reg_no"]).ToString());
                        cm.Parameters.AddWithValue("model", (json_object["model"]).ToString());
                        cm.Parameters.AddWithValue("mileage", Convert.ToDecimal(json_object["mileage"].ToString()).ToString());
                        cm.Parameters.AddWithValue("chasis_no", (json_object["chasis_no"]).ToString());
                        cm.Parameters.AddWithValue("colour", (json_object["colour"]).ToString());
                        cm.Parameters.AddWithValue("make", (json_object["make"].ToString()));
                        cm.Parameters.AddWithValue("fuel_type", (json_object["fuel_type"]).ToString());
                        cm.Parameters.AddWithValue("variant", (json_object["variant"]).ToString());
                        cm.Parameters.AddWithValue("years", (json_object["years"]).ToString());
                        cm.Parameters.AddWithValue("tr_type", (json_object["tr_type"]).ToString());
                        cm.Parameters.AddWithValue("eng_no", json_object["eng_no"].ToString());
                        cm.Parameters.AddWithValue("ins_date", Convert.ToDateTime(json_object["ins_date"].ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
                        cm.Parameters.AddWithValue("charges", Convert.ToDecimal(json_object["charges"].ToString()).ToString());
                        cm.Parameters.AddWithValue("paid", Convert.ToDecimal(json_object["paid"].ToString()).ToString());
                        cm.Parameters.AddWithValue("balance", Convert.ToDecimal(json_object["balance"].ToString()).ToString());
                        cm.Parameters.AddWithValue("customer", (json_object["customer"]).ToString());
                        cm.Parameters.AddWithValue("contactno", (json_object["contactno"]).ToString());
                        cm.Parameters.AddWithValue("comments", (json_object["comments"].ToString()).ToString());
                        cm.Parameters.AddWithValue("acode", json_object["acode"].ToString().Trim());
                        cm.Parameters.AddWithValue("itype", json_object["itype"].ToString().Trim());
                        cm.Parameters.AddWithValue("stats", Convert.ToInt32(json_object["stats"].ToString().Trim()));
                        cm.Parameters.AddWithValue("pay_date", Convert.ToString(json_object["paydate"]).Trim() == String.Empty ? (Object)DBNull.Value : json_object["paydate"].ToString().Trim());
                        cm.Parameters.AddWithValue("created_by", json_object["l_user"].ToString());
                        cm.Parameters.AddWithValue("entryno", entryno);
                        invno = Convert.ToInt32(cm.ExecuteScalar());

                    }
                    if (invno > 0)
                    {
                        using (cm = new SqlCommand(OrderDetails, con, trans))
                        {
                            cm.Parameters.Add("pidno", SqlDbType.Int);
                            cm.Parameters.Add("inspection_master", SqlDbType.Int);
                            cm.Parameters.Add("inpection_parameter", SqlDbType.Int);
                            cm.Parameters.Add("istatus", SqlDbType.VarChar);
                            cm.Parameters.Add("remarks", SqlDbType.VarChar);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters[0].Value = invno;
                                cm.Parameters[1].Value = Convert.ToInt32(row["inspection_master"]);
                                cm.Parameters[2].Value = Convert.ToInt32(row["inspection_parameter"]);
                                cm.Parameters[3].Value = Convert.ToString(row["istatus"]);
                                cm.Parameters[4].Value = Convert.ToString(row["remarks"]);
                                rowseffected += cm.ExecuteNonQuery();
                            }
                        }

                        if (rowseffected > 0)
                        {

                            if (table_ledger.Rows.Count > 0)
                            {
                                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 = vno;
                                        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 = invno;
                                        cm.Parameters["per"].Value = (row["per"]);
                                        cm.Parameters["posted"].Value = (row["posted"]);
                                        cm.Parameters["entryno"].Value = entryno;

                                        rowseffected += cm.ExecuteNonQuery();

                                    }
                                }
                            }

                            if (rowseffected > 0)
                            {
                                using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data,users_id) " +
                                      "values(" + vno + ",'" + vtype + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + (json_object["s_user"]) + "','" + (json_object["l_user"]) + "','New Entry',''," + json_object["UserId"].ToString() + ")", 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;
                        }

                    }
                    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 Inspection_Update(String json)
        {
            JObject json_object = JObject.Parse(json);
            String Token = json_object["token"].ToString();
            if (Token.Trim() != app_key)
            {
                return "404";
            }
            DataTable table = (DataTable)JsonConvert.DeserializeObject(json_object["Child"].ToString(), (typeof(DataTable)));
            DataTable table_ledger = (DataTable)JsonConvert.DeserializeObject(json_object["Ledger"].ToString(), (typeof(DataTable)));

            String q1 = "select code from vehicle where LTRIM(RTRIM(vin))='" + (json_object["chasis_no"]).ToString().Trim() + "'";
            int isvalid = IList_ExecuteScalerValue(q1);
            if (isvalid == 0)
            {
                return "-2";
            }

            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int idno = Convert.ToInt32(json_object["id"].ToString());
            int vno = Convert.ToInt32(json_object["code"].ToString());
            String vtype = json_object["Type"].ToString();
            int entryno = 0;
            String response = "";
            DataSet dt = new DataSet();
            String JSONString = "";
            DataTable ds = new DataTable();
            dt.Tables.Add(ds);
            SqlTransaction trans = null;

            String OrderMaster = "Update [inspection_master] " +
                           " set [reg_no]=@reg_no,[model]=@model,[mileage]=@mileage,[chasis_no]=@chasis_no," +
                           " [colour]=@colour,[make]=@make,[fuel_type]=@fuel_type,[variant]=@variant,[years]=@years," +
                           "[tr_type]=@tr_type,[eng_no]=@eng_no,[ins_date]=@ins_date,[charges]=@charges,[paid]=@paid," +
                           "[balance]=@balance,[customer]=@customer,[contactno]=@contactno,[comments]=@comments," +
                           "[acode]=@acode,[itype]=@itype,[stats]=@stats,[pay_date]=@pay_date where id=@id;";

            String delete_ledger = "Delete from Ledger where type='" + vtype + "' and ref=" + vno + " and pidno=" + idno + ";";

            String delete_inspection = "Delete from inspection_detail where pidno=" + idno + ";";

            String delete = delete_ledger + ";" + delete_inspection;

            String OrderDetails = " INSERT INTO [dbo].[inspection_detail] " +
                                  " (pidno,inspection_master,inpection_parameter,istatus,remarks) values" +
                                  " (@pidno,@inspection_master,@inpection_parameter,@istatus,@remarks)";

            String Select = "select * from inspection_master where id=" + idno + ";" +
                   " select cat.id as mt,cat.name mt_name,ip.id as pt,ip.name as pt_name,id.istatus,id.remarks" +
                   " from inspection_detail id " +
                   " inner join inspection_category cat on cat.id = id.inspection_master " +
                   " inner join inspection_parameter ip on ip.id = id.inpection_parameter" +
                   " where id.pidno=" + idno;


            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 getEntries = "Select key_pk from Inspection_Invoice_Master where inspection_id="+idno;

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

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

                    using (adp = new SqlDataAdapter(Select, con))
                    {
                        adp.SelectCommand.Transaction = trans;
                        cmd = new SqlCommandBuilder(adp);
                        adp.Fill(dt);
                        dt.Tables[0].TableName = "Child";
                        dt.Tables[1].TableName = "Master";
                        JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                    }


                    using (cm = new SqlCommand("select ent_no from inspection_master where id=" + idno + "", con, trans))
                    {

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

                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {
                        cm.Parameters.AddWithValue("id", idno);
                        cm.Parameters.AddWithValue("reg_no", (json_object["reg_no"]).ToString());
                        cm.Parameters.AddWithValue("model", (json_object["model"]).ToString());
                        cm.Parameters.AddWithValue("mileage", Convert.ToDecimal(json_object["mileage"].ToString()).ToString());
                        cm.Parameters.AddWithValue("chasis_no", (json_object["chasis_no"]).ToString());
                        cm.Parameters.AddWithValue("colour", (json_object["colour"]).ToString());
                        cm.Parameters.AddWithValue("make", (json_object["make"].ToString()));
                        cm.Parameters.AddWithValue("fuel_type", (json_object["fuel_type"]).ToString());
                        cm.Parameters.AddWithValue("variant", (json_object["variant"]).ToString());
                        cm.Parameters.AddWithValue("years", (json_object["years"]).ToString());
                        cm.Parameters.AddWithValue("tr_type", (json_object["tr_type"]).ToString());
                        cm.Parameters.AddWithValue("eng_no", json_object["eng_no"].ToString());
                        cm.Parameters.AddWithValue("ins_date", Convert.ToDateTime(json_object["ins_date"].ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
                        cm.Parameters.AddWithValue("charges", Convert.ToDecimal(json_object["charges"].ToString()).ToString());
                        cm.Parameters.AddWithValue("paid", Convert.ToDecimal(json_object["paid"].ToString()).ToString());
                        cm.Parameters.AddWithValue("balance", Convert.ToDecimal(json_object["balance"].ToString()).ToString());
                        cm.Parameters.AddWithValue("customer", (json_object["customer"]).ToString());
                        cm.Parameters.AddWithValue("contactno", (json_object["contactno"]).ToString());
                        cm.Parameters.AddWithValue("comments", (json_object["comments"].ToString()).ToString());
                        cm.Parameters.AddWithValue("acode", json_object["acode"].ToString().Trim());
                        cm.Parameters.AddWithValue("itype", json_object["itype"].ToString().Trim());
                        cm.Parameters.AddWithValue("stats", Convert.ToInt32(json_object["stats"].ToString().Trim()));
                        cm.Parameters.AddWithValue("pay_date", json_object["paydate"].ToString().Trim() == String.Empty ? (Object)DBNull.Value : json_object["paydate"].ToString().Trim());

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

                    }
                    if (rowseffected > 0)
                    {
                        using (cm = new SqlCommand(delete, con, trans))
                        {
                            cm.ExecuteNonQuery();
                        }
                        using (cm = new SqlCommand(OrderDetails, con, trans))
                        {


                            cm.Parameters.Add("pidno", SqlDbType.Int);
                            cm.Parameters.Add("inspection_master", SqlDbType.Int);
                            cm.Parameters.Add("inpection_parameter", SqlDbType.Int);
                            cm.Parameters.Add("istatus", SqlDbType.VarChar);
                            cm.Parameters.Add("remarks", SqlDbType.VarChar);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters[0].Value = idno;
                                cm.Parameters[1].Value = Convert.ToInt32(row["inspection_master"]);
                                cm.Parameters[2].Value = Convert.ToInt32(row["inspection_parameter"]);
                                cm.Parameters[3].Value = Convert.ToString(row["istatus"]);
                                cm.Parameters[4].Value = Convert.ToString(row["remarks"]);
                                rowseffected += cm.ExecuteNonQuery();
                            }
                        }

                        if (rowseffected > 0)
                        {

                            if (table_ledger.Rows.Count > 0)
                            {
                                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 = vno;
                                        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 = idno;
                                        cm.Parameters["per"].Value = (row["per"]);
                                        cm.Parameters["posted"].Value = (row["posted"]);
                                        cm.Parameters["entryno"].Value = entryno;

                                        rowseffected += cm.ExecuteNonQuery();

                                    }
                                }
                            }

                            if (rowseffected > 0)
                            {
                                using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data,users_id) " +
                                "values(" + vno + ",'" + vtype + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + (json_object["s_user"]) + "','" + (json_object["l_user"]) + "','Modified Entry','" + JSONString + "'," + json_object["UserId"].ToString() + ")", con, trans))
                                {
                                    rows = cm.ExecuteNonQuery();
                                }

                                if (rows > 0)
                                {
                                    int entry = 0;
                                    using (cm = new SqlCommand(getEntries, con, trans))
                                    {
                                        var val = cm.ExecuteScalar();
                                        if(val!=null)
                                        {
                                            entry = Convert.ToInt32(val);
                                        }
                                    }
                                    if(entry>0)
                                    {
                                        using (cm = new SqlCommand("Update Inspection_Invoice_Master set acode='" + json_object["acode"].ToString().Trim() + "' where inspection_id=" + idno + ";", con, trans))
                                        {
                                            rows = cm.ExecuteNonQuery();
                                        }

                                        using (cm = new SqlCommand("Update Ledger set d_acode='" + json_object["acode"].ToString().Trim() + "' where type='IS' and ref=" + entry + "; ", con, trans))
                                        {
                                            rows = cm.ExecuteNonQuery();
                                        }
                                    }

                                    trans.Commit();
                                    IsInsert = idno;
                                }
                                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 Inspection_Delete(String json)
        {
            JObject json_object = JObject.Parse(json);

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

            int IsInsert = 0;
            int rowseffected = 0;
            String UserId = json_object["UserId"].ToString();
            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();

            int idno = Convert.ToInt32(json_object["id"].ToString());
            int code = Convert.ToInt32(json_object["code"].ToString());
            String vtype = json_object["Type"].ToString();
            String response = "";
            DataSet dt = new DataSet();

            SqlTransaction trans = null;


            String delete = " Delete from inspection_detail where pidno=" + idno + ";" +
                            " Delete from inspection_images where inspection_id=" + idno + ";" +
                            " Delete from inspection_master where id=" + idno + ";" +
                            "Delete from Ledger where type='" + vtype + "' and ref=" + code + " and pidno=" + idno + ";";

            String Select = "select * from inspection_master where id=" + idno + ";" +
                     " select cat.id as mt,cat.name mt_name,ip.id as pt,ip.name as pt_name,id.istatus,id.remarks from inspection_detail id " +
                     " inner join inspection_category cat on cat.id = id.inspection_master " +
                     " inner join inspection_parameter ip on ip.id = id.inpection_parameter" +
                     " where id.pidno=" + idno;


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

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


                    using (adp = new SqlDataAdapter(Select, 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(" + code + ",'" + vtype + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + (User) + "','" + (system) + "','Delete Entry','" + JSONString + "'," + UserId + ")", con, trans))
                    {

                        cm.ExecuteNonQuery();

                    }
                    using (cm = new SqlCommand(delete, con, trans))
                    {
                        rowseffected = cm.ExecuteNonQuery();
                    }

                    if (rowseffected > 0)
                    {
                        trans.Commit();
                        IsInsert = idno;

                    }
                    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 GetInspectionByVnNumber(String json)
        {
            JObject json_Object = JObject.Parse(json);

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

            String data = "";
            String query = "";
            if (json_Object["vin"].ToString() != "")
            {
                query = " select * from vehicle " +
                         " where LTRIM(RTRIM(vin))='" + json_Object["vin"].ToString() + "' ";

            }
            else
            {
                query = " select top 1 * from inspection_master " +
                                         " where LTRIM(RTRIM(chasis_no))='" + json_Object["chasisno"].ToString() + "' order by id desc";

            }
            data = IList_GetTable(query);
            return data;
        }
        
        public String GetInspectionById(String json)
        {
            JObject json_Object = JObject.Parse(json);

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

            int id = Convert.ToInt32(json_Object["id"].ToString());
            String data = "";
            String path = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "images";
            String query = " Select * from inspection_master where id=" + id + ";" +
                           " select distinct im.inspection_master,ic.name from inspection_detail im inner join inspection_category ic on im.inspection_master=ic.id where im.pidno=" + id + " ;" +
                           " select im.inspection_master,im.inpection_parameter,ic.name,im.istatus,im.remarks from inspection_detail im inner join inspection_parameter ic on im.inpection_parameter=ic.id where im.pidno=" + id + " order by im.id;" +
                           " Select id,inspection_id,('" + path + "' +url) as url,name from inspection_images where inspection_id=" + id + " order by id ;" +
                           " select COUNT(*) as total from Inspection_Orders_Master where inspection_id=" + id;
            data = IList_GetDataSet(query);
            return data;
        }

        public String Inspection_Print(String json)
        {

            JObject json_object = JObject.Parse(json);
            String Token = json_object["token"].ToString();
            if (Token.Trim() != app_key)
            {
                return "404";
            }

            int idno = Convert.ToInt32(json_object["id"].ToString());

            String select1 = " select distinct im.* from inspection_master im ";

            String select2 = " select distinct cat.id,cat.name as Cat,ip.id,ip.name as Child,id.istatus,id.remarks,im.comments " +
                             " from inspection_master im ";

            String join = " inner join inspection_detail id on im.id=id.pidno " +
                          " inner join inspection_category cat on cat.id = id.inspection_master " +
                          " inner join inspection_parameter ip on ip.id = id.inpection_parameter";

            String where = " where im.id=" + idno;

            String master = select1 + join + where;

            String child = select2 + join + where;

            String query = master + ";" + child;

            String data = IList_GetDataSet(query);

            return data;

        }

        public String GetInspectionList(String Token)
        {
            if (Token.Trim() != app_key)
            {
                return "404";
            }

            String data = "";
            String query = " select * from inspection_category order by id;" +
                           " select * from inspection_parameter;"+
                           " select * from inspection_charges;";
            data = IList_GetDataSet(query);
            return data;
        }

        public int UploadImage(Inspection_Obj order)
        {
            if (order.token != app_key)
            {
                return 404;
            }

            int response = 0;
            try
            {
               
                string apPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + @"images\Inspection\" + order.insp_id.Trim();
                excp(apPath);
                String file = apPath.Trim() + @"\" + order.name + ".png";
                String image_path = (@"images\Inspection\") + order.insp_id.Trim() + (@"\") + order.name + ".png";

                if (!Directory.Exists(apPath))
                {
                    Directory.CreateDirectory(apPath);
                }
                excp(image_path);
                MemoryStream ms = new MemoryStream(order.images);
                System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
                img.Save(file, System.Drawing.Imaging.ImageFormat.Png);

                if (order.id == "")
                {
                    IList_ExecuteScalerValue("insert into inspection_images(inspection_id,url,name) " +
                         " values(" + order.insp_id + ",'" + image_path + "','" + order.name + "');select SCOPE_IDENTITY() as code;");
                }
                else
                {
                    IList_execute("Update inspection_images set name='" + order.name + "',url='" + image_path + "' where id=" + order.id);
                }
                if (File.Exists(file))
                {
                    response = 1;
                }
                else
                {
                    response = 0;
                }

            }
            catch (Exception ex)
            {
                excp(ex.Message);
                response = 0;
            }

            return response;
        }

        public String GetInspectionIamgesList(String json)
        {
            JObject json_object = JObject.Parse(json);
            String Token = json_object["token"].ToString();
            if (Token.Trim() != app_key)
            {
                return "404";
            }
         
            String data = "";
            int idno = Convert.ToInt32(json_object["inspect_id"].ToString());

            String query = "select img.*,c.image_base_url from inspection_images img,companysetup c where img.inspection_id=" + idno;

            data = IList_GetTable(query);
            return data;
        }

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

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

            int id = json_Object["id"].ToString().Trim() == "" ? 0 : Convert.ToInt32(json_Object["id"].ToString());
            String vin = Convert.ToString(json_Object["vin"].ToString());
            String maker = Convert.ToString(json_Object["maker"].ToString());
            String model = Convert.ToString(json_Object["model"].ToString());
            String colour = Convert.ToString(json_Object["colour"].ToString());
            String mileage = Convert.ToString(json_Object["mileage"].ToString());
            String fuel_type = Convert.ToString(json_Object["fuel_type"].ToString());
            String year = Convert.ToString(json_Object["year"].ToString());
            String engno = Convert.ToString(json_Object["engno"].ToString());
            String regno = Convert.ToString(json_Object["regno"].ToString());
            String customer = Convert.ToString(json_Object["customer"].ToString());
            String phone = Convert.ToString(json_Object["phone"].ToString());
            String mobile = Convert.ToString(json_Object["mobile"].ToString());
            String address = Convert.ToString(json_Object["address"].ToString());
            String trans = Convert.ToString(json_Object["trans"].ToString());
            String edate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            int rowseffected = 0;

            if (id == 0)
            {
                String q1 = "select code from vehicle where LTRIM(RTRIM(vin))='"+vin+"'";
                int isvalid = IList_ExecuteScalerValue(q1);
                if (isvalid > 0)
                {
                    rowseffected = -2;
                }
                else
                {
                    int code = IList_ExecuteScalerValue("Select top 1 code from vehicle order by code desc ");

                    String query = " insert into vehicle(code,vin,maker,model,colour,mileage,fuel_type,years,engno,regno,edate,name,phone,mobile,addres,transmission) values" +
                                   " (" + (code + 1) + ",'" + vin + "','" + maker + "','" + model + "','" + colour + "'," + mileage + ",'" + fuel_type + "'," + year + ","+
                                   "'" + engno + "','" + regno + "','" + edate + "','"+customer+"','"+phone+"','"+mobile+"','"+address+"','"+trans+"')";
                    rowseffected = IList_execute(query);
                }

            }
            else
            {
                String q1 = "select code from vehicle where LTRIM(RTRIM(vin))='" + vin + "' and code!="+id;
                int isvalid = IList_ExecuteScalerValue(q1);
                if (isvalid > 0)
                {
                    rowseffected = -2;
                }
                else
                {
                    String query = " Update vehicle set vin='" + vin + "',maker='" + maker + "',model='" + model + "',colour='" + colour + "',mileage=" + mileage + ",fuel_type='" + fuel_type + "'," +
                                   " years=" + year + ",engno='" + engno + "',regno='" + regno + "',name='"+customer+ "',phone='" + phone + "',mobile='" + mobile + "',addres='" + address + "',transmission='"+trans+"' where code=" + id;
                    rowseffected = IList_execute(query);
                }
            }
            return rowseffected;
        }

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

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

            String data = "";
            String query = "";
            query = " select * from inspection_charges;";

            data = IList_GetTable(query);
            return data;
        }

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

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

            String query = "";
            query = "Update inspection_charges set charges="+Convert.ToDecimal(json_Object["charges"].ToString());
            int i = IList_execute(query);
            if (i<=0)
            {
                query = "Insert into inspection_charges(charges) values("+ Convert.ToDecimal(json_Object["charges"].ToString()) + ")";
                i = IList_execute(query);
            }

           
            return i.ToString();
        }

        #endregion

        #region InspectionOrder

        public String LoadInspectionOrders(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String token = json_Object["token"].ToString().Trim();
            if (token != app_key)
            {
                return "404";
            }
            int inspection_id = Convert.ToInt32(json_Object["id"].ToString());
            String data = "";
            String query = " Select invoice_no from Inspection_Orders_Master " +
                           " where inspection_id=" + inspection_id + " Order By Key_pk;" +
                           " select id,name from inspection_category order by name;" +
                           " select name,mrk_default from units order by name;" +
                           " select ins.Remarks from inspection_detail ins " +
                           " inner join inspection_category ic on ic.id = ins.inspection_master " +
                           " where LTRIM(RTRIM(remarks))!= '' and ins.pidno=" + inspection_id + " order by ins.id;" +
                           " select * from labour_estimated where mrk_default=1;"+
                           " select *,cast(profit as varchar(10))+(case when mrk_default=1 then '->Default' else '' end)  as descr from prft_per order by profit;";



            data = IList_GetDataSet(query);
            return data;
        }

        public String Inspection_Orders_Insert(String json)
        {

            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString().Trim();
            if (token != app_key)
            {
                return "404";
            }
            String child = json_object["Child"].ToString();
            DataTable table = (DataTable)JsonConvert.DeserializeObject(child, (typeof(DataTable)));
            String User = json_object["System"].ToString();
            String system = json_object["User"].ToString();
            String UserId = json_object["UserId"].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 inspec_id = Convert.ToInt32(json_object["inspec_id"].ToString());
            String response = "";

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

            String detail = " insert into Inspection_Order_Detail(key_fk,acitno,prtno,bn,invdesc,unit,qty,pu_rate,pu_amount,sa_rate,sa_amount,labour_per,labour_amount,profit_per,profit,line_total,inspection_id,itype,cat_id,approved_by,approved_date,req_by,req_date) values "
                             + " (@key,@item,@partno,@brand,@desc,@unit,@qty,@pu_rate,@pu_amount,@sa_rate,@sa_amount,@labour_per,@labour_amount,@profit_per,@profit,@line_total,@inspect_id,@itype,@cat_id,@approved_by,@approved_date,@req_by,@req_date); Select Scope_identity() as code;";

            String Order1 = " insert into Inspection_Orders_Master(key_pk,clkdate,date,invoice_no,prtclar,citmno,users,total_pu,total_profit_per,total_profit,amtgrs,disc,dscr_p,expmnininv,courier,amtnet,gstp,gsta,amtnetwgst,itp,ita,na_w_itax,ttlamtnet,total_labour_per,total_labour,inspection_id) values ";
            String Order2 = " (@key_pk,@edate,@date,@invoice,@remarks,@qty,@users,@total_pu,@total_profit_per,@total_profit,@gross,@disc,@dscr_p,@expense,@courier,@net,@gstp,@gsta,@gst_amt,@itp,@itpa,@itp_amt,@total,@total_labour_per,@total_labour,@inspect_id); ";
            String OrderMaster = Order1 + Order2;


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

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

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

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

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

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

                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {
                   
                        cm.Parameters.AddWithValue("inspect_id", inspec_id);
                        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("remarks", json_object["remarks"].ToString());
                        cm.Parameters.AddWithValue("qty",Convert.ToDecimal( json_object["qty"].ToString()));
                        cm.Parameters.AddWithValue("users", Convert.ToDecimal(json_object["UserId"].ToString()));
                        cm.Parameters.AddWithValue("total_pu", Convert.ToDecimal(json_object["purchase"].ToString()));
                        cm.Parameters.AddWithValue("total_profit_per", Convert.ToDecimal(json_object["profit_per"].ToString()));
                        cm.Parameters.AddWithValue("total_profit", Convert.ToDecimal(json_object["profit"].ToString()));
                        cm.Parameters.AddWithValue("gross", Convert.ToDecimal(json_object["gross"].ToString()));
                        cm.Parameters.AddWithValue("disc", Convert.ToDecimal(json_object["disc_amt"].ToString()));
                        cm.Parameters.AddWithValue("dscr_p", Convert.ToDecimal(Convert.ToDecimal(json_object["disc_per"].ToString())));
                        cm.Parameters.AddWithValue("expense", Convert.ToDecimal(json_object["freight"].ToString()));
                        cm.Parameters.AddWithValue("courier", Convert.ToDecimal(json_object["courier"].ToString()));
                        cm.Parameters.AddWithValue("net", Convert.ToDecimal(json_object["net_amt"].ToString()));
                        cm.Parameters.AddWithValue("gstp", Convert.ToDecimal(json_object["gst_per"].ToString()));
                        cm.Parameters.AddWithValue("gsta", Convert.ToDecimal(json_object["gst_val"].ToString()));
                        cm.Parameters.AddWithValue("gst_amt", Convert.ToDecimal(json_object["gstnet"].ToString()));
                        cm.Parameters.AddWithValue("itp", Convert.ToDecimal(json_object["it_per"].ToString()));
                        cm.Parameters.AddWithValue("itpa", Convert.ToDecimal(json_object["it_val"].ToString()));
                        cm.Parameters.AddWithValue("itp_amt", Convert.ToDecimal(json_object["itnet"].ToString()));
                        cm.Parameters.AddWithValue("total", Convert.ToDecimal(json_object["total"].ToString()));
                        cm.Parameters.AddWithValue("total_labour_per", Convert.ToDecimal(json_object["labour_per"].ToString()));
                        cm.Parameters.AddWithValue("total_labour", Convert.ToDecimal(json_object["labour"].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("qty", SqlDbType.Decimal);
                            cm.Parameters.Add("unit", SqlDbType.VarChar);
                            cm.Parameters.Add("pu_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("pu_amount", SqlDbType.Decimal);
                            cm.Parameters.Add("sa_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("sa_amount", SqlDbType.Decimal);
                            cm.Parameters.Add("labour_per", SqlDbType.Decimal);
                            cm.Parameters.Add("labour_amount", SqlDbType.Decimal);
                            cm.Parameters.Add("profit", SqlDbType.Decimal);
                            cm.Parameters.Add("profit_per", SqlDbType.Decimal);
                            cm.Parameters.Add("line_total", SqlDbType.Decimal);
                            cm.Parameters.Add("inspect_id", SqlDbType.Int);
                            cm.Parameters.Add("itype", SqlDbType.VarChar);
                            cm.Parameters.Add("cat_id", SqlDbType.Int);
                            cm.Parameters.Add("approved_by", SqlDbType.Int);
                            cm.Parameters.Add("approved_date", SqlDbType.DateTime);
                            cm.Parameters.Add("req_by", SqlDbType.Int);
                            cm.Parameters.Add("req_date", SqlDbType.Date);

                           
                            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["unit"].Value = Convert.ToString(row["unit"]);
                                cm.Parameters["desc"].Value = Convert.ToString(row["desc"]);
                                cm.Parameters["qty"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["pu_rate"].Value = Convert.ToDecimal(row["pu_rate"]);
                                cm.Parameters["pu_amount"].Value = Convert.ToDecimal(row["pu_amount"]);
                                cm.Parameters["sa_rate"].Value = Convert.ToDecimal(row["sa_rate"]);
                                cm.Parameters["sa_amount"].Value = Convert.ToDecimal(row["sa_amount"]);
                                cm.Parameters["labour_per"].Value = Convert.ToDecimal(row["labour_per"]);
                                cm.Parameters["labour_amount"].Value = Convert.ToDecimal(row["labour_amount"]);
                                cm.Parameters["profit"].Value = Convert.ToDecimal(row["profit"]);
                                cm.Parameters["profit_per"].Value = Convert.ToDecimal(row["profit_per"]);
                                cm.Parameters["line_total"].Value = Convert.ToDecimal(row["line_total"].ToString());
                                cm.Parameters["inspect_id"].Value = inspec_id;
                                cm.Parameters["itype"].Value = Convert.ToString(row["itype"]);
                                cm.Parameters["cat_id"].Value=Convert.ToInt32(row["category"].ToString()) == 0 ? (Object)DBNull.Value : Convert.ToInt32(row["category"].ToString());
                                cm.Parameters["approved_by"].Value = Convert.ToInt32(row["approved_by"].ToString()) == 0 ? (Object)DBNull.Value : Convert.ToInt32(row["approved_by"].ToString());
                                cm.Parameters["approved_date"].Value = Convert.ToString(row["approved_date"].ToString().Trim()) == "" ? (Object)DBNull.Value : Convert.ToString(row["approved_date"].ToString());
                                cm.Parameters["req_by"].Value = Convert.ToInt32(row["req_by"].ToString()) == 0 ? (Object)DBNull.Value : Convert.ToInt32(row["req_by"].ToString());
                                cm.Parameters["req_date"].Value = Convert.ToString(row["req_date"].ToString()) == "" ? (Object)DBNull.Value : Convert.ToString(row["req_date"].ToString());

                                rowseffected = cm.ExecuteNonQuery();

                            }


                        }


                        if (rowseffected > 0)
                        {


                            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 = 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 Inspection_Orders_Update(String json)
        {

            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString().Trim();
            if (token != app_key)
            {
                return "404";
            }
            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 UserId = json_object["UserId"].ToString();
            String type = json_object["Type"].ToString();
            String date = json_object["edate"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int inspec_id = Convert.ToInt32(json_object["inspec_id"].ToString());
            int invno = Convert.ToInt32(json_object["inv"].ToString());
            int key = Convert.ToInt32(json_object["key"].ToString());

            String response = "";

            DataSet dt = new DataSet();

            SqlTransaction trans = null;

            String detail = " insert into Inspection_Order_Detail(key_fk,acitno,prtno,bn,invdesc,unit,qty,pu_rate,pu_amount,sa_rate,sa_amount,labour_per,labour_amount,profit_per,profit,line_total,inspection_id,itype,cat_id,approved_by,approved_date,req_by,req_date) values "
                              + " (@key,@item,@partno,@brand,@desc,@unit,@qty,@pu_rate,@pu_amount,@sa_rate,@sa_amount,@labour_per,@labour_amount,@profit_per,@profit,@line_total,@inspect_id,@itype,@cat_id,@approved_by,@approved_date,@req_by,@req_date); Select Scope_identity() as code;";



            String OrderMaster = "  Update Inspection_Orders_Master set clkdate=@edate,date=@edate,prtclar=@remarks, closed=@closed," +
                                 " total_pu=@total_pu,total_profit_per=@total_profit_per,total_profit=@total_profit, " +
                                 "  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,total_labour_per=@total_labour_per,total_labour=@total_labour where key_pk=@key_pk";


            String Select_Master = " select distinct  sm.*  from Inspection_Orders_Master sm inner join Inspection_Order_Detail sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

            String Select_Child = " select distinct  sd.*  from Inspection_Orders_Master sm inner join Inspection_Order_Detail sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

            String delete_detail = " Delete from Inspection_Order_Detail where key_fk=" + key + ";";


            String delete = delete_detail;
            String JSONString = "";
            DataTable st = new DataTable();
            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";
                        JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                    }


                    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("remarks", json_object["remarks"].ToString());
                        cm.Parameters.AddWithValue("qty",Convert.ToDecimal( json_object["qty"].ToString()));
                        cm.Parameters.AddWithValue("closed", json_object["closed"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["closed"].ToString()));
                        cm.Parameters.AddWithValue("total_pu",Convert.ToDecimal( json_object["purchase"].ToString()));
                        cm.Parameters.AddWithValue("total_profit_per", Convert.ToDecimal(json_object["profit_per"].ToString()));
                        cm.Parameters.AddWithValue("total_profit", Convert.ToDecimal(json_object["profit"].ToString()));
                        cm.Parameters.AddWithValue("gross", Convert.ToDecimal(json_object["gross"].ToString()));
                        cm.Parameters.AddWithValue("dscr_p", Convert.ToDecimal(json_object["disc_per"].ToString()));
                        cm.Parameters.AddWithValue("disc",Convert.ToDecimal( json_object["disc_amt"].ToString()));
                        cm.Parameters.AddWithValue("expense", Convert.ToDecimal( json_object["freight"].ToString()));
                        cm.Parameters.AddWithValue("courier", Convert.ToDecimal(json_object["courier"].ToString()));
                        cm.Parameters.AddWithValue("net", Convert.ToDecimal(json_object["net_amt"].ToString()));
                        cm.Parameters.AddWithValue("gstp", Convert.ToDecimal(json_object["gst_per"].ToString()));
                        cm.Parameters.AddWithValue("gsta", Convert.ToDecimal( json_object["gst_val"].ToString()));
                        cm.Parameters.AddWithValue("gst_amt", Convert.ToDecimal( json_object["gstnet"].ToString()));
                        cm.Parameters.AddWithValue("itp", Convert.ToDecimal( json_object["it_per"].ToString()));
                        cm.Parameters.AddWithValue("itpa", Convert.ToDecimal( json_object["it_val"].ToString()));
                        cm.Parameters.AddWithValue("itp_amt", Convert.ToDecimal( json_object["itnet"].ToString()));
                        cm.Parameters.AddWithValue("total", Convert.ToDecimal(json_object["total"].ToString()));
                        cm.Parameters.AddWithValue("total_labour_per", Convert.ToDecimal( json_object["labour_per"].ToString()));
                        cm.Parameters.AddWithValue("total_labour", Convert.ToDecimal( json_object["labour"].ToString()));

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

                    }
                    if (rowseffected > 0)
                    {

                        using (cm = new SqlCommand(delete, 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("unit", SqlDbType.VarChar);
                            cm.Parameters.Add("qty", SqlDbType.Decimal);
                            cm.Parameters.Add("pu_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("pu_amount", SqlDbType.Decimal);
                            cm.Parameters.Add("sa_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("sa_amount", SqlDbType.Decimal);
                            cm.Parameters.Add("labour_per", SqlDbType.Decimal);
                            cm.Parameters.Add("labour_amount", SqlDbType.Decimal);
                            cm.Parameters.Add("profit", SqlDbType.Decimal);
                            cm.Parameters.Add("profit_per", SqlDbType.Decimal);
                            cm.Parameters.Add("line_total", SqlDbType.Decimal);
                            cm.Parameters.Add("inspect_id", SqlDbType.Int);
                            cm.Parameters.Add("itype", SqlDbType.VarChar);
                            cm.Parameters.Add("cat_id", SqlDbType.Int);
                            cm.Parameters.Add("approved_by", SqlDbType.Int);
                            cm.Parameters.Add("approved_date", SqlDbType.DateTime);
                            cm.Parameters.Add("req_by", SqlDbType.Int);
                            cm.Parameters.Add("req_date", SqlDbType.Date);

                            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["desc"].Value = Convert.ToString(row["desc"]);
                                cm.Parameters["unit"].Value = Convert.ToString(row["unit"]);
                                cm.Parameters["qty"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["pu_rate"].Value = Convert.ToDecimal(row["pu_rate"]);
                                cm.Parameters["pu_amount"].Value = Convert.ToDecimal(row["pu_amount"]);
                                cm.Parameters["sa_rate"].Value = Convert.ToDecimal(row["sa_rate"]);
                                cm.Parameters["sa_amount"].Value = Convert.ToDecimal(row["sa_amount"]);
                                cm.Parameters["labour_per"].Value = Convert.ToDecimal(row["labour_per"]);
                                cm.Parameters["labour_amount"].Value = Convert.ToDecimal(row["labour_amount"]);
                                cm.Parameters["profit"].Value = Convert.ToDecimal(row["profit"]);
                                cm.Parameters["profit_per"].Value = Convert.ToDecimal(row["profit_per"]);
                                cm.Parameters["line_total"].Value = Convert.ToDecimal(row["line_total"].ToString());

                                cm.Parameters["inspect_id"].Value = inspec_id;
                                cm.Parameters["itype"].Value = Convert.ToString(row["itype"]);
                                cm.Parameters["cat_id"].Value = Convert.ToInt32(row["category"].ToString()) == 0 ? (Object)DBNull.Value : Convert.ToInt32(row["category"].ToString());
                                cm.Parameters["approved_by"].Value = Convert.ToInt32(row["approved_by"].ToString()) == 0 ? (Object)DBNull.Value : Convert.ToInt32(row["approved_by"].ToString());
                                cm.Parameters["approved_date"].Value = Convert.ToString(row["approved_date"].ToString().Trim()) == "" ? (Object)DBNull.Value : Convert.ToString(row["approved_date"].ToString());
                                cm.Parameters["req_by"].Value = Convert.ToInt32(row["req_by"].ToString()) == 0 ? (Object)DBNull.Value : Convert.ToInt32(row["req_by"].ToString());
                                cm.Parameters["req_date"].Value = Convert.ToString(row["req_date"].ToString()) == "" ? (Object)DBNull.Value : Convert.ToString(row["req_date"].ToString());

                                rowseffected = cm.ExecuteNonQuery();

                            }


                        }

                        if (rowseffected > 0)
                        {
                            {


                                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;

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

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

                }
            }

            return IsInsert.ToString();


        }

        public String Inspection_Orders_Delete(String json)
        {

            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString().Trim();
            if (token != app_key)
            {
                return "404";
            }
            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());
            int invno = Convert.ToInt32(json_object["inv"].ToString());
            String type = json_object["Type"].ToString();
            int IsInsert = 0;
            int rows = 0;

            String response = "";
            DataSet dt = new DataSet();
            SqlTransaction trans = null;


            String Select_Master = " select distinct  sm.*  from Inspection_Orders_Master sm inner join Inspection_Order_Detail sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

            String Select_Child = " select distinct  sd.*  from Inspection_Orders_Master sm inner join Inspection_Order_Detail sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

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

            String delete_detail = " Delete from Inspection_Order_Detail where key_fk=" + key + ";";


            String delete = delete_detail + ";" + delete_master;

            DataTable st = new DataTable();
            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("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 + "','Delete Entry','" + JSONString + "'," + UserId + ")", con, trans))
                    {

                        rows = cm.ExecuteNonQuery();

                    }

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

                        rows = cm.ExecuteNonQuery();

                    }

                    if (rows > 0)
                    {

                        trans.Commit();
                        IsInsert = key;

                    }

                    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 Get_Inspection_Orders_Invoice(String json)
        {

            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString();
            if (token != app_key)
            {
                return "404";
            }
            String invoice_no = json_object["invoice_no"].ToString().Trim();
         

            String query = "  select sm.*,sd.*,sm.key_pk as keys,sd.key_pk as rowno, " +
                           " isnull(cat.id,0) as category_id,cat.name as cat_name,isnull(req.USERS,0) as req_id,req.USERS_NAME as req_name, " +
                           " isnull(appr.USERS,0) as approved_id,appr.USERS_NAME as approved_name " +
                           " from Inspection_Orders_Master sm inner join Inspection_Order_Detail sd on sm.key_pk = sd.key_fk " +
                           " left join inspection_category cat on cat.id = sd.cat_id " +
                           " left join USERS req on req.USERS = sd.req_by " +
                           " left join USERS appr on appr.USERS = sd.approved_by  " +
                           " where sm.invoice_no=" + invoice_no + "  order by sd.key_pk ;";

            return IList_GetTable(query);
        }

        public String Inspection_Orders_Print1(String json)
        {
            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString().Trim();
            String where = "";
            if (token != app_key)
            {
                return "404";
            }
            if (json_object["Child"] != null)
            {
                String child = json_object["Child"].ToString();
                DataTable table = (DataTable)JsonConvert.DeserializeObject(child, (typeof(DataTable)));
                if (table.Rows.Count>0) {
                    where = " and (";
                    int count = 0;
                    foreach (DataRow row in table.Rows)
                    {
                        where += " ins_detail.key_pk =" + row[0].ToString() + "or";

                    }
                    where = where.Substring(0, where.Length - 2);
                    where += " )";
                }
            }
            if (json_object["insp_id"]!=null)
            {
                if (Convert.ToInt32(json_object["insp_id"].ToString())>0)
                {
                    where += " and im.id="+ Convert.ToInt32(json_object["insp_id"].ToString());
                }
            }
            if (json_object["invno"] != null)
            {
                if (Convert.ToInt32(json_object["invno"].ToString()) > 0)
                {
                    where += " and ins_order.key_pk=" + Convert.ToInt32(json_object["invno"].ToString());
                }
            }

            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 ;";
            query += " select im.id,im.ins_date,im.customer,im.make,im.model,im.chasis_no,im.eng_no,im.reg_no,im.mileage,im.tr_type,"+
                    "  im.colour,im.contactno, " +
                    "  ins_order.*,ins_detail.* from inspection_master im " +
                    "  inner join Inspection_Orders_Master ins_order on ins_order.inspection_id=im.id " +
                    "  inner join Inspection_Order_Detail ins_detail on ins_detail.key_fk=ins_order.key_pk " +
                    "  where ins_order.key_pk is not null "+ where + " order by ins_detail.key_pk;";




            return IList_GetDataSet(query);
        }

        public String Find_Inspection(String json)
        {
            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString().Trim();
            String where = "";
            if (token != app_key)
            {
                return "404";
            }

            String query = " select im.* from inspection_master  im  left join vehicle v on v.vin=im.chasis_no" +
                           " where im.id is not null ";

            if (json_object["from"].ToString().Trim() != "")
            {
                where += " and CAST(im.ins_date AS DATE) >= CAST( '" + json_object["from"].ToString().Trim() + "' AS DATE) ";

            }
            if (json_object["to"].ToString().Trim() != "")
            {
                where += " AND CAST(im.ins_date AS DATE) <= CAST( '" + json_object["to"].ToString().Trim() + "' AS DATE) ";

            }
            if (json_object["invno"].ToString().Trim() != "")
            {
                where += " and im.vno=" + json_object["invno"].ToString().Trim() + "";
            }
            if (json_object["vn_number"].ToString().Trim() != "")
            {
                where += " and im.chasis_no='" + json_object["vn_number"].ToString().Trim() + "' ";
            }
            if (json_object["make"].ToString().Trim() != "")
            {
                where += " and im. make='" + json_object["make"].ToString().Trim() + "'";
            }
            if (json_object["model"].ToString().Trim() != "")
            {
                where += " and im.model='" + json_object["model"].ToString().Trim() + "'";
            }
            if (json_object["acode"].ToString().Trim() != "")
            {
                where += " and im. acode='" + json_object["acode"].ToString().Trim() + "'";
            }
            if (json_object["mode"].ToString().Trim() != "")
            {
                where += " and im.itype='" + json_object["mode"].ToString().Trim() + "'";
            }

            if (json_object["phone"].ToString().Trim() != "")
            {
                where += " and LTRIM(RTRIM(im.contactno))='" + json_object["phone"].ToString().Trim() + "'";
            }
            if (json_object["reg"].ToString() != "")
            {
                where += " and im.reg_no='" + json_object["reg"].ToString() + "' ";

            }
          
            query = query + where;
            return IList_GetTable(query);
        }

        #endregion

        #region InspectionSaleInvoice

        public String LoadPendingInspection(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String token = Convert.ToString(json_Object["token"].ToString());
            if (token != app_key)
            {
                return "404";
            }
            String type = Convert.ToString(json_Object["type"].ToString());
            String data = "";
            String query = "";
            if (type == "SI")
            {
                query = " select distinct ins_m.id,ins_m.vno,ins_m.ins_date,ins_m.customer,ins_m.reg_no,ins_m.eng_no," +
                            " ins_m.make,ins_m.model from Inspection_Orders_Master ins_o  " +
                            " inner join inspection_master ins_m on ins_m.id=ins_o.inspection_id " +
                            " where ins_o.inspection_id not in ( " +
                            " select ins_inv.inspection_id  from Inspection_Invoice_Master ins_inv " +
                            " ) order by ins_m.ins_date desc ";
            }
            if (type == "PI")
            {
                query = " select distinct ins_m.id,ins_m.vno,ins_m.ins_date,ins_m.customer,ins_m.reg_no,ins_m.eng_no," +
                              " ins_m.make,ins_m.model from Inspection_Orders_Master ins_o  " +
                              " inner join inspection_master ins_m on ins_m.id=ins_o.inspection_id " +
                              " where ins_o.inspection_id not in ( " +
                              " select ins_inv.inspection_id  from Inspection_Purchase_Invoice_Master ins_inv " +
                              " ) order by ins_m.ins_date desc ";
            }

            data = IList_GetTable(query);
            return data;
        }

        public String Get_Inspection_Labour(String json)
        {
            JObject json_object = JObject.Parse(json);
            String token = Convert.ToString(json_object["token"].ToString());
            if (token != app_key)
            {
                return "404";
            }
            String id = json_object["insp_id"].ToString().Trim();

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

            String query = "select * from inspection_invoice_labour where insp_id=" + Convert.ToInt32(id) + ";";

            return IList_GetTable(query);
        }

        public String LoadInspectionInvoice(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String token = Convert.ToString(json_Object["token"].ToString());
            int insp_id = Convert.ToInt32(json_Object["insp_id"].ToString());
            if (token != app_key)
            {
                return "404";
            }
            String data = "";
            String query = " Select  invoice_no from inspection_Invoice_Master where inspection_id=" + insp_id + " Order By Key_pk desc;" +
                           " select * from units order by name; " +
                           " select *,cast(profit as varchar(10))+(case when mrk_default=1 then '->Default' else '' end)  as descr from prft_per order by profit;" +
                           " select * from labour_estimated ; ";
                          

            data = IList_GetDataSet(query);
            return data;
        }

        public String Inspection_Invoice_Insert(String json)
        {

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

            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)));
            DataTable table_charges = (DataTable)JsonConvert.DeserializeObject(json_object["labour_table"].ToString(), (typeof(DataTable)));
            int inspec_id = Convert.ToInt32(json_object["inspec_id"].ToString());
            int inspec_code = Convert.ToInt32(json_object["inspec_code"].ToString());

            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,acitno,prtno,bn,invdesc,purchase_rate,qty,rate,amount,inspection_id,profit_per,profit,unit,labour_per,labour,line_total,return_qty) values "
                       + " (@key,@item,@partno,@brand,@desc,@purchase_rate,@qty,@rate,@amount,@inspect_id,@profit_per,@profit,@unit,@labour_per,@labour,@line_total,@return_qty); Select Scope_identity() as code;";

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

            String stock = "  insert into stock(pidno,cidno,edate,refno,estatus,product,partno,description,rec,iss,rate,gross_amount,disc_p,disc,net_amount,acode,inspect_id) " +
                           "  values (@key,(select SCOPE_IDENTITY()),@edate,@refno,@type,@item,@partno,@desc,@rec,@iss,@rate,@amount,@disc_p,@disc,@net_amount,@acode,@inspect_id)";

            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();

            String labour = " Insert into inspection_invoice_labour(key_fk,descr,amount,insp_id) " +
                            " values(@key_fk,@descr,@amount,@insp_id)";

            String delete_inspection_ledger = "Delete from Ledger where type='IN' and ref=" + inspec_code + " and pidno=" + inspec_id + ";";

            String UpdateCharges = "Update [inspection_master] " +
                        "set [charges]=@charges,[paid]=@paid," +
                        "[balance]=@balance where id=@id;";
            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("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("total_pu", Convert.ToDecimal(json_object["purchase"].ToString()));
                        cm.Parameters.AddWithValue("total_profit_per", Convert.ToDecimal(json_object["profit_per"].ToString()));
                        cm.Parameters.AddWithValue("total_profit", Convert.ToDecimal(json_object["profit"].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("total_labour_per", Convert.ToDecimal(json_object["labour_per"].ToString()));
                        cm.Parameters.AddWithValue("total_labour", Convert.ToDecimal(json_object["labour"].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("users", (json_object["UserId"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["UserId"].ToString())));
                        cm.Parameters.AddWithValue("inspection_id", inspec_id);
                        cm.Parameters.AddWithValue("ent_no", entryno);
                        rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());

                    }

                    if (rowseffected > 0)
                    {
                        using (cm = new SqlCommand(delete_inspection_ledger, con, trans))
                        {
                            cm.ExecuteNonQuery();

                        }

                        using (cm = new SqlCommand(UpdateCharges, con, trans))
                        {
                            cm.Parameters.AddWithValue("id", inspec_id);
                            cm.Parameters.AddWithValue("charges", Convert.ToDecimal(json_object["insp_charges"].ToString()).ToString());
                            cm.Parameters.AddWithValue("paid", Convert.ToDecimal(json_object["insp_paid"].ToString()).ToString());
                            cm.Parameters.AddWithValue("balance", Convert.ToDecimal(json_object["insp_balance"].ToString()).ToString());

                            rowseffected = Convert.ToInt32(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("purchase_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("qty", SqlDbType.Decimal);
                            cm.Parameters.Add("unit", SqlDbType.VarChar);
                            cm.Parameters.Add("profit", SqlDbType.Decimal);
                            cm.Parameters.Add("profit_per", SqlDbType.Decimal);
                            cm.Parameters.Add("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amount", SqlDbType.Decimal);
                            cm.Parameters.Add("inspect_id", SqlDbType.Int);
                            cm.Parameters.Add("labour", SqlDbType.Decimal);
                            cm.Parameters.Add("labour_per", SqlDbType.Decimal);
                            cm.Parameters.Add("line_total", SqlDbType.Decimal);
                            cm.Parameters.Add("return_qty", 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);
                            cm.Parameters.Add("disc_p", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("net_amount", SqlDbType.Decimal);
                            cm.Parameters.Add("acode", SqlDbType.VarChar);

                            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["desc"].Value = Convert.ToString(row["desc"]);
                                cm.Parameters["unit"].Value = Convert.ToString(row["unit"]);
                                cm.Parameters["purchase_rate"].Value = Convert.ToDecimal(row["purchase_rate"]);
                                cm.Parameters["qty"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["rate"].Value = Convert.ToDecimal(row["rate"]);
                                cm.Parameters["amount"].Value = Convert.ToDecimal(row["amount"]);
                                cm.Parameters["profit"].Value = Convert.ToDecimal(row["profit"]);
                                cm.Parameters["profit_per"].Value = Convert.ToDecimal(row["profit_per"]);
                                cm.Parameters["inspect_id"].Value = inspec_id;
                                cm.Parameters["labour"].Value = Convert.ToDecimal(row["labour"]);
                                cm.Parameters["labour_per"].Value = Convert.ToDecimal(row["labour_per"]);
                                cm.Parameters["line_total"].Value = Convert.ToDecimal(row["line_total"]);
                                cm.Parameters["return_qty"].Value = Convert.ToDecimal(row["return_qty"]);
                                
                                cm.Parameters["edate"].Value = date;
                                cm.Parameters["refno"].Value = invno;
                                cm.Parameters["type"].Value = type;
                                cm.Parameters["rec"].Value = (Object)DBNull.Value;
                                cm.Parameters["iss"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["amount"].Value = Convert.ToDecimal(row["amount"]);
                                cm.Parameters["disc_p"].Value = Convert.ToDecimal(json_object["disc_per"].ToString());
                                cm.Parameters["disc"].Value = ((Convert.ToDecimal(json_object["disc_per"].ToString())) * Convert.ToDecimal(row["amount"]) / 100);
                                cm.Parameters["net_amount"].Value = Math.Round(Convert.ToDecimal(row["amount"]) - (((Convert.ToDecimal(json_object["disc_per"].ToString())) * Convert.ToDecimal(row["amount"]) / 100)), 2);
                                cm.Parameters["acode"].Value = Convert.ToString(json_object["debit"].ToString());

                                rowseffected = cm.ExecuteNonQuery();

                            }


                        }

                        if (table_charges.Rows.Count > 0)
                        {
                            rowseffected = 0;
                            using (cm = new SqlCommand(labour, con, trans))
                            {
                                cm.Parameters.Add("key_fk", SqlDbType.Int);
                                cm.Parameters.Add("descr", SqlDbType.VarChar);
                                cm.Parameters.Add("amount", SqlDbType.Decimal);
                                cm.Parameters.Add("insp_id", SqlDbType.Int);

                                foreach (DataRow row in table_charges.Rows)
                                {

                                    cm.Parameters["key_fk"].Value = key;
                                    cm.Parameters["descr"].Value = Convert.ToString(row["descr"]);
                                    cm.Parameters["amount"].Value = Convert.ToDecimal(row["amount"]);
                                    cm.Parameters["insp_id"].Value = inspec_id;

                                    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)
                                {
                                    if(row["type"].ToString().Trim()=="IN")
                                    {
                                        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 = row["ref"];
                                        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 =inspec_id;
                                        cm.Parameters["per"].Value = (row["per"]);
                                        cm.Parameters["posted"].Value = (row["posted"]);
                                        cm.Parameters["entryno"].Value = entryno;

                                        rowseffected += cm.ExecuteNonQuery();

                                    }

                                    if (row["type"].ToString().Trim() == "IS")
                                    {
                                        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)
                            {
                                {

                                    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','')", 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;
                        }

                    }

                    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 Inspection_Invoice_Update(String json)
        {

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

            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)));
            DataTable table_charges = (DataTable)JsonConvert.DeserializeObject(json_object["labour_table"].ToString(), (typeof(DataTable)));
            int inspec_id = Convert.ToInt32(json_object["inspec_id"].ToString());

            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 entryno = Convert.ToInt32(json_object["ent_no"].ToString());
            int invno = Convert.ToInt32(json_object["inv"].ToString());
            int key = Convert.ToInt32(json_object["key"].ToString());

            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;

            String detail = " insert into " + json_object["Detail"] + "(key_fk,acitno,prtno,bn,invdesc,purchase_rate,qty,rate,amount,inspection_id,unit,profit_per,profit,labour_per,labour,line_total,return_qty) values "
                        + " (@key,@item,@partno,@brand,@desc,@purchase_rate,@qty,@rate,@amount,@inspect_id,@unit,@profit_per,@profit,@labour_per,@labour,@line_total,@return_qty); Select Scope_identity() as code;";

            String stock = "  insert into stock(pidno,cidno,edate,refno,estatus,product,partno,description,rec,iss,rate,gross_amount,disc_p,disc,net_amount,acode,inspect_id) " +
                         "  values (@key,(select SCOPE_IDENTITY()),@edate,@refno,@type,@item,@partno,@desc,@rec,@iss,@rate,@amount,@disc_p,@disc,@net_amount,@acode,@inspect_id)";

            String OrderMaster = "  Update " + json_object["Master"] + " set inv_type=@invtype,clkdate=@edate,date=@edate,acode=@debit,c_code=@credit,duedate=@duedate,days=@days,prtclar=@remarks," +
                                 " total_pu=@total_pu,total_profit_per=@total_profit_per,total_profit=@total_profit,amtgrs=@gross,disc=@disc,dscr_p=@dscr_p,expmnininv=@expense,courier=@courier," +
                                 " total_labour_per=@total_labour_per,total_labour=@total_labour,amtnet=@net,gstp=@gstp,gsta=@gsta,amtnetwgst=@gst_amt," +
                                 "  itp=@itp,ita=@itpa,na_w_itax=@itp_amt,ttlamtnet=@total,citmno=@qty 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_stock = "Delete from stock where estatus='" + type + "' and refno=" + invno + " and pidno=" + 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_Labour = "Delete from inspection_invoice_labour where key_fk=" + key + ";";

            String labour = " Insert into inspection_invoice_labour(key_fk,descr,amount,insp_id) " +
                            " values(@key_fk,@descr,@amount,@insp_id)";

           
            int inspec_code = Convert.ToInt32(json_object["inspec_code"].ToString());

            String delete_inspection_ledger = "Delete from Ledger where type='IN' and ref=" + inspec_code + " and pidno=" + inspec_id + ";";

            String UpdateCharges = "Update [inspection_master] " +
                        "set [charges]=@charges,[paid]=@paid," +
                        "[balance]=@balance where id=@id;";

            String delete = delete_detail + delete_stock + delete_Labour + delete_ledger+delete_inspection_ledger;

            DataTable st = new DataTable();


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

            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";
                        JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                    }




                    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("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("total_pu", Convert.ToDecimal(json_object["purchase"].ToString()));
                        cm.Parameters.AddWithValue("total_profit_per", Convert.ToDecimal(json_object["profit_per"].ToString()));
                        cm.Parameters.AddWithValue("total_profit", Convert.ToDecimal(json_object["profit"].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("total_labour_per", Convert.ToDecimal(json_object["labour_per"].ToString()));
                        cm.Parameters.AddWithValue("total_labour", Convert.ToDecimal(json_object["labour"].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("inspection_id", inspec_id);

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

                    }
                    if (rowseffected > 0)
                    {


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

                            cm.ExecuteNonQuery();

                        }

                        using (cm = new SqlCommand(UpdateCharges, con, trans))
                        {
                            cm.Parameters.AddWithValue("id", inspec_id);
                            cm.Parameters.AddWithValue("charges", Convert.ToDecimal(json_object["insp_charges"].ToString()).ToString());
                            cm.Parameters.AddWithValue("paid", Convert.ToDecimal(json_object["insp_paid"].ToString()).ToString());
                            cm.Parameters.AddWithValue("balance", Convert.ToDecimal(json_object["insp_balance"].ToString()).ToString());

                            rowseffected = Convert.ToInt32(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("unit", SqlDbType.VarChar);
                            cm.Parameters.Add("purchase_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("qty", SqlDbType.Decimal);
                            cm.Parameters.Add("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amount", SqlDbType.Decimal);
                            cm.Parameters.Add("profit", SqlDbType.Decimal);
                            cm.Parameters.Add("profit_per", SqlDbType.Decimal);
                            cm.Parameters.Add("inspect_id", SqlDbType.Int);
                            cm.Parameters.Add("labour", SqlDbType.Decimal);
                            cm.Parameters.Add("labour_per", SqlDbType.Decimal);
                            cm.Parameters.Add("line_total", SqlDbType.Decimal);
                            cm.Parameters.Add("return_qty", 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);
                            cm.Parameters.Add("disc_p", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("net_amount", SqlDbType.Decimal);
                            cm.Parameters.Add("acode", SqlDbType.VarChar);

                            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["desc"].Value = Convert.ToString(row["desc"]);
                                cm.Parameters["unit"].Value = Convert.ToString(row["unit"]);
                                cm.Parameters["purchase_rate"].Value = Convert.ToDecimal(row["purchase_rate"]);
                                cm.Parameters["qty"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["rate"].Value = Convert.ToDecimal(row["rate"]);
                                cm.Parameters["amount"].Value = Convert.ToDecimal(row["amount"]);
                                cm.Parameters["profit"].Value = Convert.ToDecimal(row["profit"]);
                                cm.Parameters["profit_per"].Value = Convert.ToDecimal(row["profit_per"]);
                                cm.Parameters["inspect_id"].Value = inspec_id;
                                cm.Parameters["labour"].Value = Convert.ToDecimal(row["labour"]);
                                cm.Parameters["labour_per"].Value = Convert.ToDecimal(row["labour_per"]);
                                cm.Parameters["line_total"].Value = Convert.ToDecimal(row["line_total"]);
                                cm.Parameters["return_qty"].Value = Convert.ToDecimal(row["return_qty"]);
                              
                                cm.Parameters["edate"].Value = date;
                                cm.Parameters["refno"].Value = invno;
                                cm.Parameters["type"].Value = type;
                                cm.Parameters["rec"].Value = (Object)DBNull.Value;
                                cm.Parameters["iss"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["amount"].Value = Convert.ToDecimal(row["amount"]);
                                cm.Parameters["disc_p"].Value = Convert.ToDecimal(json_object["disc_per"].ToString());
                                cm.Parameters["disc"].Value = ((Convert.ToDecimal(json_object["disc_per"].ToString())) * Convert.ToDecimal(row["amount"]) / 100);
                                cm.Parameters["net_amount"].Value = Math.Round(Convert.ToDecimal(row["amount"]) - (((Convert.ToDecimal(json_object["disc_per"].ToString())) * Convert.ToDecimal(row["amount"]) / 100)), 2);
                                cm.Parameters["acode"].Value = Convert.ToString(json_object["debit"].ToString());

                                rowseffected = cm.ExecuteNonQuery();

                            }


                        }

                        if (table_charges.Rows.Count > 0)
                        {
                            rowseffected = 0;
                            using (cm = new SqlCommand(labour, con, trans))
                            {
                                cm.Parameters.Add("key_fk", SqlDbType.Int);
                                cm.Parameters.Add("descr", SqlDbType.VarChar);
                                cm.Parameters.Add("amount", SqlDbType.Decimal);
                                cm.Parameters.Add("insp_id", SqlDbType.Int);

                                foreach (DataRow row in table_charges.Rows)
                                {

                                    cm.Parameters["key_fk"].Value = key;
                                    cm.Parameters["descr"].Value = Convert.ToString(row["descr"]);
                                    cm.Parameters["amount"].Value = Convert.ToDecimal(row["amount"]);
                                    cm.Parameters["insp_id"].Value = inspec_id;

                                    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)
                                {
                                    if (row["type"].ToString().Trim() == "IN")
                                    {
                                        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 = row["ref"];
                                        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 = inspec_id;
                                        cm.Parameters["per"].Value = (row["per"]);
                                        cm.Parameters["posted"].Value = (row["posted"]);
                                        cm.Parameters["entryno"].Value = entryno;
                                        rowseffected += cm.ExecuteNonQuery();

                                    }

                                    if (row["type"].ToString().Trim() == "IS")
                                    {

                                        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 == 0 ? (Object)DBNull.Value : entryno;
                                        rowseffected += cm.ExecuteNonQuery();
                                    }

                                }
                            }

                            if (rowseffected > 0)
                            {
                                {


                                    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;
                
            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();

                }
            }

            return IsInsert.ToString();

        }

        public String Inspection_Invoice_Delete(String json)
        {

            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString().Trim();
            if (token != app_key)
            {
                return "404";
            }
            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();
            int IsInsert = 0;
            int rows = 0;

            int invno = Convert.ToInt32(json_object["inv"].ToString());

            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;


            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_master = "Delete from " + json_object["Master"] + "  where key_pk=" + key;

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

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

            String delete_labour = " Delete from inspection_invoice_labour where key_fk=" + key + ";";

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

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

            DataTable st = new DataTable();
            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("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 + "','Delete Entry','" + JSONString + "')", con, trans))
                    {

                        rows = cm.ExecuteNonQuery();

                    }

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

                        rows = cm.ExecuteNonQuery();

                    }

                    if (rows > 0)
                    {

                        trans.Commit();
                        IsInsert = key;

                    }

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

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

                }
            }

            return IsInsert.ToString();


        }

        public String Get_Inspection_Pending_Orders(String json)
        {
            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString().Trim();
            if (token != app_key)
            {
                return "404";
            }
            String invoice_no = json_object["invoice_no"].ToString().Trim();
            String id = json_object["id"].ToString().Trim();
            String type = json_object["type"].ToString().Trim();


            String query = "";
            if (type == "PI")
            {
                query = " select * from Inspection_Orders_Master sm  where sm.inspection_id=" + Convert.ToInt32(id) + ";";

                query += " select * from Inspection_Order_Detail sd where sd.inspection_id=" + Convert.ToInt32(id) + ";";
                
                query += " select * from inspection_master where id=" + Convert.ToInt32(id) + " and id not in " +
                         " ( select ins_inv.inspection_id  from Inspection_Purchase_Invoice_Master ins_inv ) ";

                query += " select * from Inspection_Purchase_Invoice_Master where inspection_id=" + Convert.ToInt32(id);

               
            }
            else if (type == "SI")
            {
                query = " select * from Inspection_Orders_Master sm  where sm.inspection_id=" + Convert.ToInt32(id) + ";";

                query += " select sd.*,isnull(rtn.return_qty,0) as return_qty " + 
                         " from Inspection_Order_Detail sd" +
                         " left join itemlinked im on im.idno=sd.acitno "+
                         " left join (select inspection_id,prtno,sum(qty) as return_qty from Inspection_Purchase_Return_Invoice_Detail group by inspection_id,prtno)rtn " +
                         " on rtn.inspection_id=sd.inspection_id and sd.prtno=rtn.prtno "+
                         " where sd.inspection_id=" + Convert.ToInt32(id) + "; ";

                query += " select * from inspection_master where id=" + Convert.ToInt32(id) + " and id not in " +
                         " ( select inspection_id  from Inspection_Invoice_Master  ); ";

                query += " select * from Inspection_Invoice_Master where inspection_id=" + Convert.ToInt32(id) + ";";

                query += " select COUNT(*) as total from Inspection_Purchase_Invoice_Master where inspection_id = " + id + ";";


            }
            return IList_GetDataSet(query);
        }

        public String Get_Inspection_Pending_PartNo(String json)
        {
            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString().Trim();

            if (token != app_key)
            {
                return "404";
            }

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

            String query = "";

            query = " select * from Inspection_Order_Detail sd " +
                     " where sd.inspection_id=" + Convert.ToInt32(id) + "" +
                     " and prtno not in ( select prtno from Inspection_Purchase_Invoice_Detail " +
                     " where inspection_id=" + Convert.ToInt32(id)+")";

            if (Convert.ToInt32( cardno)>0)
            {
                query = " select * from Inspection_Order_Detail sd " +
                   " where sd.inspection_id=" + Convert.ToInt32(id) + "" +
                   " and key_fk=" + Convert.ToInt32(cardno) + "" +
                   " and prtno not in ( select prtno from Inspection_Purchase_Invoice_Detail " +
                   " where inspection_id=" + Convert.ToInt32(id) + ")";
            }

            return IList_GetDataSet(query);
        }

        public String Get_Inspection_Pending_Refresh(String json)
        {
            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString().Trim();

            if (token != app_key)
            {
                return "404";
            }

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

            String query = "";

            query = " select * from Inspection_Order_Detail " +
                    " where inspection_id=" + Convert.ToInt32(id) + where;
                     

           

            return IList_GetDataSet(query);
        }

        public String Inspection_Print1(String json)
        {
            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString().Trim();
            if (token != app_key)
            {
                return "404";
            }
            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 ;";
            query += "  select im.id,im.ins_date,im.make,im.model,im.chasis_no,im.eng_no,im.reg_no,im.mileage,im.balance,im.tr_type,im.colour,ac.code, " +
                                               "  sm.key_pk,u.users_name as users,ac.title as Title,sm.invoice_no as Invno,sm.clkdate as Edate,c.name as City," +
                                               " im.contactno as Contactno,ac.add1,ac.cell1,sm.total_labour as labour, sm.expmnininv as Freight,sm.courier as Courier,sm.gstp,sm.gsta,sd.acitno,sd.prtno,sd.bn,sd.qty, " +
                                               " sd.rate,sd.purchase_rate,sd.profit,sd.key_pk as sn,sd.invdesc,sm.disc as in_disc,sm.dscr_p as inv_dscr_p,sm.prtclar,org.short_code as origin,im.Customer  from Inspection_Invoice_Master sm " +
                                               " left join Inspection_Invoice_Detail sd on sm.key_pk=sd.key_fk  " +
                                               " left join inspection_master im on im.id=sm.inspection_id " +
                                               "  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.userno " +
                                               "  left join itemlinked it on it.idno=sd.acitno " +
                                               "  left join origin org on org.code=it.origin " +
                                               "  where sm.invoice_no=" + json_object["invno"].ToString() + " order by sn;";

            query += " select * from Inspection_Invoice_Master sm left join inspection_invoice_labour sd on sm.key_pk=sd.key_fk where sm.invoice_no=" + json_object["invno"].ToString();



            return IList_GetDataSet(query);
        }

        public String Get_Inspection_Invoice(String json)
        {

            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString().Trim();
            if (token != app_key)
            {
                return "404";
            }
            String invoice_no = json_object["invoice_no"].ToString().Trim();
            String Master = "inspection_Invoice_Master";
            String Child = "inspection_Invoice_Detail";
            
            String query = "";

            String query1 = " select sm.* from " + Master + " sm  ";

            String query2 = " select sd.* from " + Child + " sd  inner join " + Master + " sm on sm.key_pk=sd.key_fk ";

            String query3 = " select  sd.* from inspection_invoice_labour sd inner join " + Master + " sm on sm.key_pk=sd.key_fk ";

            String query4 = " select im.* from inspection_master im inner join " + Master + " inv on inv.inspection_id=im.id ";

            String query5 = " select COUNT(*) as total from Inspection_Purchase_Invoice_Master im " +
                            " where  inspection_id in ( select top 1 inspection_id from Inspection_Invoice_Master " +
                            " where invoice_no="+invoice_no+");";      

            query1 += " where sm.invoice_no=" + invoice_no + ";";
            query2 += " where sm.invoice_no=" + invoice_no + "  order by sd.key_pk ;";
            query3 += " where sm.invoice_no=" + invoice_no + "  order by sd.id ;";
            query4 += " where inv.invoice_no=" + invoice_no + ";";

            query = query1 + query2 + query3 + query4 + query5;

            return IList_GetDataSet(query);
        }

        public String Find_Inspection_Invoice(String json)
        {

            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString().Trim();
            if (token != app_key)
            {
                return "404";
            }
            String invoice_no = json_object["invoice_no"].ToString().Trim();
           
            String where = "";
            if (json_object["invoice_no"].ToString()!="")
            {
                where += " and sm.vno="+json_object["invoice_no"].ToString();
            }
            if (json_object["vn_number"].ToString() != "")
            {
                where += " and sm.chasis_no='" + json_object["vn_number"].ToString()+"' ";
            }
            if (json_object["from"].ToString() != "")
            {
                where += " and cast(sm.ins_date as Date)>='"+json_object["from"].ToString()+"'";
            }
            if (json_object["to"].ToString() != "")
            {
                where += " and cast(sm.ins_date as Date)<='" + json_object["to"].ToString() + "'";

            }

            if (json_object["phone"].ToString().Trim() != "")
            {
                where += " and LTRIM(RTRIM(sm.contactno))='" + json_object["phone"].ToString().Trim() + "'";
            }

            if (json_object["acode"].ToString() != "")
            {
                where += " and ac.code='" + json_object["acode"].ToString() + "'";

            }
         
            

            String query = " select sm.*,ac.title,im.invoice_no,im.key_pk,isnull(im.ttlamtnet,0) as inv_amount,isnull(gj.paid,0) as paid from inspection_master sm " +
                           " left join Inspection_Invoice_Master im on sm.id = im.inspection_id " +
                           " left join(select insp_id,sum(cramt) as paid from General_Journal where insp_id is not null group by insp_id) gj on gj.insp_id = sm.id " +
                           " inner join ac on ac.code=sm.acode "+
                           " where sm.id is not null " + where;
            return IList_GetDataSet(query);

        }

        #endregion

        #region InpectionPurchaseInvoice

        public String Load_Inspection_Purchase(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String token = Convert.ToString(json_Object["token"].ToString());
            if (token != app_key)
            {
                return "404";
            }
            String data = "";

            int insp_id = Convert.ToInt32(json_Object["insp_id"].ToString());

            String query = " Select invoice_no from Inspection_Purchase_Invoice_Master" +
                           " Order By Key_pk desc;";
                           
                         
            
            if(insp_id>0)
            {

                query = "  Select invoice_no from Inspection_Purchase_Invoice_Master " +
                        "  where  inspection_id=" + insp_id + " Order By Key_pk desc;";
          
                query += " select distinct sm.key_pk,sm.invoice_no,sm.clkdate,count(sd.qty) as Parts from Inspection_Orders_Master sm " +
                         " inner join Inspection_Order_Detail sd on sm.key_pk=sd.key_fk " +
                         " where sm.inspection_id= " + insp_id +
                         " and sd.prtno not in ( select prtno from Inspection_Purchase_Invoice_Detail " +
                         " where inspection_id=" + insp_id + ")" +
                         " group by sm.key_pk,sm.invoice_no,sm.clkdate ";
            }
            query+=   " Select  title,code,iden from ac where type='Child'  order by title;";

            data = IList_GetDataSet(query);
            return data;
        }

        public String Inspection_Invoice_Purchase_Insert(String json)
        {

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

            DataTable table = (DataTable)JsonConvert.DeserializeObject(json_object["Child"].ToString(), (typeof(DataTable)));
            DataTable table_ledger = (DataTable)JsonConvert.DeserializeObject(json_object["Ledger"].ToString(), (typeof(DataTable)));
            DataTable table_party = (DataTable)JsonConvert.DeserializeObject(json_object["Party"].ToString(), (typeof(DataTable)));

            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            String UserId = json_object["UserId"].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 Order1 = " insert into " + json_object["Master"] + "(key_pk,clkdate,date,invoice_no,prtclar,citmno,userno,amtgrs,inspection_id,ent_no) values ";
            String Order2 = " (@key_pk,@edate,@date,@invoice,@remarks,@qty,@users,@gross,@inspect_id,@ent_no); ";
            String OrderMaster = Order1 + Order2;

            String detail = " insert into " + json_object["Detail"] + "(key_fk,acode,c_code,acitno,prtno,bn,invdesc,qty,rate,disc,disc_rate,amount,inspection_id) values "
                          + " (@key,@acode,@c_code,@item,@partno,@brand,@desc,@qty,@rate,@disc,@disc_rate,@amount,@inspect_id); Select Scope_identity() as code;";

            String party = " Insert into Inspection_Purchase_Invoice_Detail_Party(key_fk,acode,gross,disc,disc_per,net_amount)" +
                           " values (@key_fk,@acode,@gross,@disc,@disc_per,@net_amount)";

            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 stock = "  insert into stock(pidno,cidno,edate,refno,estatus,product,partno,description,rec,iss,rate,gross_amount,disc_rate,disc,net_amount,acode,inspect_id) " +
                           "  values (@key,(select SCOPE_IDENTITY()),@edate,@refno,@type,@item,@partno,@desc,@rec,@iss,@rate,@amt,@disc_rate,@disc,@amount,@acode,@inspect_id)";

            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("users", json_object["UserId"].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("remarks", json_object["remarks"].ToString());
                        cm.Parameters.AddWithValue("qty", json_object["qty"].ToString());
                        cm.Parameters.AddWithValue("gross", json_object["gross"].ToString());
                        cm.Parameters.AddWithValue("inspect_id", json_object["inspect_id"].ToString());
                        cm.Parameters.AddWithValue("ent_no", entryno);
                        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("acode", SqlDbType.VarChar);
                            cm.Parameters.Add("c_code", SqlDbType.VarChar);
                            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("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amount", SqlDbType.Decimal);
                            cm.Parameters.Add("inspect_id", 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("iss", SqlDbType.Decimal);
                            cm.Parameters.Add("amt", SqlDbType.Decimal);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["item"].Value = Convert.ToInt32(row["item"]) == 0 ? (Object)DBNull.Value : Convert.ToInt32(row["item"]);
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"]);
                                cm.Parameters["c_code"].Value = Convert.ToString(json_object["credit"]);
                                cm.Parameters["partno"].Value = Convert.ToString(row["partno"]) == String.Empty ? (Object)DBNull.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["rate"].Value = Convert.ToDecimal(row["rate"]);
                                cm.Parameters["disc"].Value = Convert.ToDecimal(row["disc"]);
                                cm.Parameters["disc_rate"].Value = Convert.ToDecimal(row["disc_rate"]);
                                cm.Parameters["amount"].Value = Convert.ToDecimal(row["amount"]);
                                cm.Parameters["inspect_id"].Value = Convert.ToInt32(json_object["inspect_id"].ToString());
                            

                                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 = (Object)DBNull.Value;
                                cm.Parameters["amt"].Value = Convert.ToDecimal(Convert.ToDecimal(row["qty"]) * Convert.ToDecimal(row["rate"]));
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"]);

                                rowseffected = cm.ExecuteNonQuery();

                            }
                        }

                        using (cm = new SqlCommand(party, con, trans))
                        {
                            rowseffected = 0;
                            cm.Parameters.Add("key_fk", SqlDbType.Int);
                            cm.Parameters.Add("acode", SqlDbType.VarChar);
                            cm.Parameters.Add("gross", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_per", SqlDbType.Decimal);
                            cm.Parameters.Add("net_amount", SqlDbType.Decimal);


                            foreach (DataRow row in table_party.Rows)
                            {
                                cm.Parameters["key_fk"].Value = key;
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"].ToString());
                                cm.Parameters["gross"].Value = Convert.ToDecimal(row["gross"].ToString()).ToString("N0");
                                cm.Parameters["disc"].Value = Convert.ToDecimal(row["disc"].ToString()).ToString("N0");
                                cm.Parameters["disc_per"].Value = Convert.ToDecimal(row["disc_per"].ToString());
                                cm.Parameters["net_amount"].Value = Convert.ToDecimal(row["net_amount"].ToString()).ToString("N0");

                                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)
                            {
                                {

                                    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 = 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;
              

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

                }
            }

            return IsInsert.ToString();


        }

        public String Inspection_Invoice_Purchase_Update(String json)
        {

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

            DataTable table = (DataTable)JsonConvert.DeserializeObject(json_object["Child"].ToString(), (typeof(DataTable)));
            DataTable table_ledger = (DataTable)JsonConvert.DeserializeObject(json_object["Ledger"].ToString(), (typeof(DataTable)));
            DataTable table_party = (DataTable)JsonConvert.DeserializeObject(json_object["Party"].ToString(), (typeof(DataTable)));

            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            String UserId = json_object["UserId"].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());
            int key = Convert.ToInt32(json_object["key"].ToString());
            int entryno = 0;
            String response = "";

            DataSet dt = new DataSet();

            SqlTransaction trans = null;
            String JSONString = "";
            String OrderMaster = " Update " + json_object["Master"] + "  set clkdate=@edate,date=@date," +
                                 " prtclar=@remarks,citmno=@qty,amtgrs=@gross where key_pk=@key_pk ";

            String detail = " insert into " + json_object["Detail"] + "(key_fk,acode,c_code,acitno,prtno,bn,invdesc,qty,rate,disc,disc_rate,amount,inspection_id) values "
                            + " (@key,@acode,@c_code,@item,@partno,@brand,@desc,@qty,@rate,@disc,@disc_rate,@amount,@inspect_id); Select Scope_identity() as code;";

            String party = " Insert into Inspection_Purchase_Invoice_Detail_Party(key_fk,acode,gross,disc,disc_per,net_amount)" +
                     " values (@key_fk,@acode,@gross,@disc,@disc_per,@net_amount)";


            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 remarks = json_object["remarks"].ToString().Trim();

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

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

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

            String delete_party = "Delete from Inspection_Purchase_Invoice_Detail_Party where key_fk=" + key + ";";

            String delete = delete_detail + delete_stock + delete_party + delete_ledger;

            String stock = "  insert into stock(pidno,cidno,edate,refno,estatus,product,partno,description,rec,iss,rate,gross_amount,disc_rate,disc,net_amount,acode,inspect_id) " +
                           "  values (@key,(select SCOPE_IDENTITY()),@edate,@refno,@type,@item,@partno,@desc,@rec,@iss,@rate,@amt,@disc_rate,@disc,@amount,@acode,@inspect_id)";
            try
            {

                using (con = new SqlConnection(cs))
                {

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

                    using (cm = new SqlCommand("select ent_no from Inspection_Purchase_Invoice_Master where key_pk=" + key + "", con, trans))
                    {

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

                    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";
                        JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                    }


                    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("remarks", json_object["remarks"].ToString());
                        cm.Parameters.AddWithValue("qty", json_object["qty"].ToString());
                        cm.Parameters.AddWithValue("gross", json_object["gross"].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("acode", SqlDbType.VarChar);
                            cm.Parameters.Add("c_code", SqlDbType.VarChar);
                            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("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amount", SqlDbType.Decimal);
                            cm.Parameters.Add("inspect_id", 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("iss", SqlDbType.Decimal);
                            cm.Parameters.Add("amt", SqlDbType.Decimal);


                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["item"].Value = Convert.ToInt32(row["item"]) == 0 ? (Object)DBNull.Value : Convert.ToInt32(row["item"]);
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"]);
                                cm.Parameters["c_code"].Value = Convert.ToString(json_object["credit"]);
                                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["rate"].Value = Convert.ToDecimal(row["rate"]);
                                cm.Parameters["disc"].Value = Convert.ToDecimal(row["disc"]);
                                cm.Parameters["disc_rate"].Value = Convert.ToDecimal(row["disc_rate"]);
                                cm.Parameters["amount"].Value = Convert.ToDecimal(row["amount"]);
                                cm.Parameters["inspect_id"].Value = Convert.ToInt32(json_object["inspect_id"].ToString());
                               
                                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 = (Object)DBNull.Value;
                                cm.Parameters["amt"].Value = Convert.ToDecimal(Convert.ToDecimal(row["qty"]) * Convert.ToDecimal(row["rate"]));
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"]);

                                rowseffected += cm.ExecuteNonQuery();

                            }
                        }

                        using (cm = new SqlCommand(party, con, trans))
                        {
                            rowseffected = 0;
                            cm.Parameters.Add("key_fk", SqlDbType.Int);
                            cm.Parameters.Add("acode", SqlDbType.VarChar);
                            cm.Parameters.Add("gross", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_per", SqlDbType.Decimal);
                            cm.Parameters.Add("net_amount", SqlDbType.Decimal);

                            foreach (DataRow row in table_party.Rows)
                            {
                                cm.Parameters["key_fk"].Value = key;
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"].ToString().Trim());
                                cm.Parameters["gross"].Value = Convert.ToDecimal(row["gross"].ToString()).ToString("N0");
                                cm.Parameters["disc"].Value = Convert.ToDecimal(row["disc"].ToString()).ToString("N0");
                                cm.Parameters["disc_per"].Value = Convert.ToDecimal(row["disc_per"].ToString());
                                cm.Parameters["net_amount"].Value = Convert.ToDecimal(row["net_amount"].ToString()).ToString("N0");

                                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)
                            {


                                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 = 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();

                }
            }

            return IsInsert.ToString();


        }
        
        public String Inspection_Purchase_Invoice_Delete(String json)
        {

            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString();
            if (token != app_key)
            {
                return "404";
            }
            String Master = "Inspection_Purchase_Invoice_Master";
            String Child = "Inspection_Purchase_Invoice_Detail";
            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();
            int IsInsert = 0;
            int rows = 0;

            int invno = Convert.ToInt32(json_object["inv"].ToString());

            String response = "";

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

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

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

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

            String delete_detail = " Delete from " + Child + " where key_fk=" + key + ";";

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

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

            String delete_party = "Delete from Inspection_Purchase_Invoice_Detail_Party where key_fk=" + key + ";";

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

            DataTable st = new DataTable();
            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("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 + "','Delete Entry','" + JSONString + "'," + UserId + ")", con, trans))
                    {

                        rows = cm.ExecuteNonQuery();

                    }

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

                        rows = cm.ExecuteNonQuery();

                    }

                    if (rows > 0)
                    {

                        trans.Commit();
                        IsInsert = invno;

                    }

                    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 Get_Inspection_Purchase_Invoice(String json)
        {

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

            String id = json_object["invoice_no"].ToString().Trim();
            String Master = "Inspection_Purchase_Invoice_Master";
            String Child = "Inspection_Purchase_Invoice_Detail";


            String query = "";

            String query1 = " select sm.* from " + Master + " sm  ";

            String query2 = " select sd.* from " + Child + " sd  ";

            String query3 = " select  * from inspection_invoice_labour  ";

            String query4 = " select im.* from inspection_master im inner join Inspection_Purchase_Invoice_Master inv on inv.inspection_id=im.id ";

            String query5 = " select im.*,ac.title from Inspection_Purchase_Invoice_Detail_Party im inner join ac on ac.code = im.acode ";

            query1 += " where sm.key_pk=" + id + ";";
            query2 += " where sd.key_fk=" + id + "  order by sd.key_pk ;";
            query3 += " where key_fk=" + id + "  order by id ;";
            query4 += " where inv.key_pk=" + id + ";";
            query5 += " where key_fk=" + id + " order by key_pk;";

            query = query1 + query2 + query3 + query4 + query5;

            return IList_GetDataSet(query);
        }

        public String Inspection_Purchase_Invoice_Print(String json)
        {
            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString();
           
            if (token != app_key)
            {
                return "404";
            }
            String where = " ";
            String where2 = " ";

        
            if (json_object["idno"]!=null)
            {
                if (Convert.ToInt32(json_object["idno"].ToString()) > 0)
                {
                    where += " and im.key_pk=" + json_object["idno"].ToString();
                    where2 += " and im.key_fk=" + json_object["idno"].ToString();

                    if (json_object["Child"] != null)
                    {

                        where = " and (";
                        where2 = " and (";

                        DataTable table = (DataTable)JsonConvert.DeserializeObject(json_object["Child"].ToString(), (typeof(DataTable)));

                        foreach (DataRow row in table.Rows)
                        {
                            where += " ac.code='" + row[0].ToString() + "' or";

                        }
                        where = where.Substring(0, where.Length - 3);
                        where += " )";

                        foreach (DataRow row in table.Rows)
                        {
                            where2 += " im.acode='" + row[0].ToString() + "' or";

                        }
                        where2 = where2.Substring(0, where2.Length - 3);
                        where2 += " )";
                    }
                }
            }
            if (json_object["insp_id"] != null)
            {
                where += " and im.inspection_id=" + json_object["insp_id"].ToString();
                where2 += " and im.inspection_id=" + json_object["insp_id"].ToString();
            }
            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 ;";

            query += " select im.key_pk as keys,im.invoice_no,im.clkdate,ac.code,ac.title,ip.gross as inv_gross,ip.disc as inv_disc, " +
                     " ip.disc_per as inv_disc_per,ip.net_amount as inv_net_amount,ac.add1,c.name,ac.cell1 " +
                     " from Inspection_Purchase_Invoice_Master im " +
                     " inner join   Inspection_Purchase_Invoice_Detail_Party ip on im.key_pk=ip.key_fk " +
                     " inner join ac on ac.code=ip.acode left join City c on c.code=ac.city_code " +
                     " where im.key_pk is not null " + where + " order by ip.key_pk;";

            query += " select im.acode,ip.gross as inv_gross,ip.disc as inv_disc,ip.disc_per as inv_disc_per,ip.net_amount as inv_net_amount,im.* " +
                     " from Inspection_Purchase_Invoice_Detail im inner join Inspection_Purchase_Invoice_Detail_Party ip on im.acode = ip.acode and ip.key_fk=im.key_fk " +
                     " where im.key_fk is not null "+ where2;

            return IList_GetDataSet(query);
        }


        #endregion

        #region InpectionPurchaseReturnInvoice

        public String Load_Inspection_Return_Purchase(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String token = Convert.ToString(json_Object["token"].ToString());
            if (token != app_key)
            {
                return "404";
            }
            String data = "";

            int insp_id = Convert.ToInt32(json_Object["insp_id"].ToString());

            String query = " Select invoice_no from Inspection_Purchase_Return_Invoice_Master " +
                           " Order By Key_pk desc;";

            if (insp_id > 0)
            {

                query = " Select invoice_no from Inspection_Purchase_Return_Invoice_Master  " +
                        " where  inspection_id=" + insp_id + " Order By Key_pk desc;" +
                       
                        " select * from Inspection_Purchase_Invoice_Detail where inspection_id=" + insp_id + ";" +
                        
                        " Select pu.prtno,sum(pu.qty-isnull(pr.qty,0)) as total from Inspection_Purchase_Invoice_Detail pu " +
                        " left join Inspection_Purchase_Return_Invoice_Detail pr on pu.inspection_id=pr.inspection_id " +
                        " and pu.prtno=pr.prtno group by pu.inspection_id,pu.prtno ;" +
                        
                        " select ac.code,ac.title from Inspection_Purchase_Invoice_Detail_Party pty " +
                        " inner join Inspection_Purchase_Invoice_Master im on im.key_pk=pty.key_fk " +
                        " inner join ac on ac.code=pty.acode " +
                        " where im.inspection_id="+insp_id+" order by title;";
            }

            data = IList_GetDataSet(query);
            return data;
        }
        
        public String Inspection_Invoice_Purchase_Return_Insert(String json)
        {

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

            DataTable table = (DataTable)JsonConvert.DeserializeObject(json_object["Child"].ToString(), (typeof(DataTable)));
            DataTable table_ledger = (DataTable)JsonConvert.DeserializeObject(json_object["Ledger"].ToString(), (typeof(DataTable)));
            DataTable table_party = (DataTable)JsonConvert.DeserializeObject(json_object["Party"].ToString(), (typeof(DataTable)));

            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            String UserId = json_object["UserId"].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 master_table = "Inspection_Purchase_Return_Invoice_Master";
            String child_table = " Inspection_Purchase_Return_Invoice_Detail";
            String party_table = " Inspection_Purchase_Return_Invoice_Detail_Party ";

            String Order1 = " insert into " + master_table + "(key_pk,clkdate,date,invoice_no,prtclar,citmno,userno,amtgrs,inspection_id,ent_no) values ";
            String Order2 = " (@key_pk,@edate,@date,@invoice,@remarks,@qty,@users,@gross,@inspect_id,@ent_no); ";
            String OrderMaster = Order1 + Order2;

            String detail = " insert into " + child_table + "(key_fk,acode,c_code,acitno,prtno,bn,invdesc,qty,rate,disc,disc_rate,amount,inspection_id) values "
                          + " (@key,@acode,@c_code,@item,@partno,@brand,@desc,@qty,@rate,@disc,@disc_rate,@amount,@inspect_id); Select Scope_identity() as code;";

            String party = " Insert into " + party_table + "(key_fk,acode,gross,disc,disc_per,net_amount)" +
                           " values (@key_fk,@acode,@gross,@disc,@disc_per,@net_amount)";

            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 stock = "  insert into stock(pidno,cidno,edate,refno,estatus,product,partno,description,rec,iss,rate,gross_amount,disc_rate,disc,net_amount,acode,inspect_id) " +
                           "  values (@key,(select SCOPE_IDENTITY()),@edate,@refno,@type,@item,@partno,@desc,@rec,@iss,@rate,@amt,@disc_rate,@disc,@amount,@acode,@inspect_id)";

            String Select_Master = "select distinct  sm.*  from " + master_table + " sm inner join " + child_table + " sd on sm.key_pk=sd.key_fk where sd.key_fk=";

            String Select_Child = "select distinct  sd.*  from " + master_table + " sm inner join " + child_table + " 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 " + master_table + " order by invoice_no desc;", con, trans))
                    {

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

                    using (cm = new SqlCommand(" select top 1 key_pk from " + master_table + " 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("users", json_object["UserId"].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("remarks", json_object["remarks"].ToString());
                        cm.Parameters.AddWithValue("qty", json_object["qty"].ToString());
                        cm.Parameters.AddWithValue("gross", json_object["gross"].ToString());
                        cm.Parameters.AddWithValue("inspect_id", json_object["inspect_id"].ToString());
                        cm.Parameters.AddWithValue("ent_no", entryno);
                        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("acode", SqlDbType.VarChar);
                            cm.Parameters.Add("c_code", SqlDbType.VarChar);
                            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("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amount", SqlDbType.Decimal);
                            cm.Parameters.Add("inspect_id", 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("iss", SqlDbType.Decimal);
                            cm.Parameters.Add("amt", SqlDbType.Decimal);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["item"].Value = Convert.ToInt32(row["item"]) == 0 ? (Object)DBNull.Value : Convert.ToInt32(row["item"]);
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"]);
                                cm.Parameters["c_code"].Value = Convert.ToString(json_object["credit"]);
                                cm.Parameters["partno"].Value = Convert.ToString(row["partno"]) == String.Empty ? (Object)DBNull.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["rate"].Value = Convert.ToDecimal(row["rate"]);
                                cm.Parameters["disc"].Value = Convert.ToDecimal(row["disc"]);
                                cm.Parameters["disc_rate"].Value = Convert.ToDecimal(row["disc_rate"]);
                                cm.Parameters["amount"].Value = Convert.ToDecimal(row["amount"]);
                                cm.Parameters["inspect_id"].Value = Convert.ToInt32(json_object["inspect_id"].ToString());


                                cm.Parameters["edate"].Value = date;
                                cm.Parameters["refno"].Value = invno;
                                cm.Parameters["type"].Value = type;
                                cm.Parameters["rec"].Value = (Object)DBNull.Value;
                                cm.Parameters["iss"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["amt"].Value = Convert.ToDecimal(Convert.ToDecimal(row["qty"]) * Convert.ToDecimal(row["rate"]));
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"]);

                                rowseffected = cm.ExecuteNonQuery();

                            }
                        }

                        using (cm = new SqlCommand(party, con, trans))
                        {
                            rowseffected = 0;
                            cm.Parameters.Add("key_fk", SqlDbType.Int);
                            cm.Parameters.Add("acode", SqlDbType.VarChar);
                            cm.Parameters.Add("gross", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_per", SqlDbType.Decimal);
                            cm.Parameters.Add("net_amount", SqlDbType.Decimal);


                            foreach (DataRow row in table_party.Rows)
                            {
                                cm.Parameters["key_fk"].Value = key;
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"].ToString());
                                cm.Parameters["gross"].Value = Convert.ToDecimal(row["gross"].ToString()).ToString("N0");
                                cm.Parameters["disc"].Value = Convert.ToDecimal(row["disc"].ToString()).ToString("N0");
                                cm.Parameters["disc_per"].Value = Convert.ToDecimal(row["disc_per"].ToString());
                                cm.Parameters["net_amount"].Value = Convert.ToDecimal(row["net_amount"].ToString()).ToString("N0");

                                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)
                            {
                                {

                                    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 = 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();

                }
            }

            return IsInsert.ToString();


        }

        public String Inspection_Invoice_Purchase_Return_Update(String json)
        {

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

            DataTable table = (DataTable)JsonConvert.DeserializeObject(json_object["Child"].ToString(), (typeof(DataTable)));
            DataTable table_ledger = (DataTable)JsonConvert.DeserializeObject(json_object["Ledger"].ToString(), (typeof(DataTable)));
            DataTable table_party = (DataTable)JsonConvert.DeserializeObject(json_object["Party"].ToString(), (typeof(DataTable)));

            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            String UserId = json_object["UserId"].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());
            int key = Convert.ToInt32(json_object["key"].ToString());
            int entryno = 0;
            String response = "";

            DataSet dt = new DataSet();

            SqlTransaction trans = null;

            String master_table = "Inspection_Purchase_Return_Invoice_Master";
            String child_table = " Inspection_Purchase_Return_Invoice_Detail";
            String party_table = " Inspection_Purchase_Return_Invoice_Detail_Party ";

            String JSONString = "";
            String OrderMaster = " Update " + master_table + "  set clkdate=@edate,date=@date," +
                                 " prtclar=@remarks,citmno=@qty,amtgrs=@gross where key_pk=@key_pk ";

            String detail = " insert into " + child_table + "(key_fk,acode,c_code,acitno,prtno,bn,invdesc,qty,rate,disc,disc_rate,amount,inspection_id) values "
                            + " (@key,@acode,@c_code,@item,@partno,@brand,@desc,@qty,@rate,@disc,@disc_rate,@amount,@inspect_id); Select Scope_identity() as code;";

            String party = " Insert into " + party_table + "(key_fk,acode,gross,disc,disc_per,net_amount)" +
                     " values (@key_fk,@acode,@gross,@disc,@disc_per,@net_amount)";


            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 " + master_table + " sm inner join " + child_table + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

            String Select_Child = "select distinct  sd.*  from " + master_table + " sm inner join " + child_table + " sd on sm.key_pk=sd.key_fk where sd.key_fk=" + key;

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

            String delete_detail = "Delete from " + child_table + " where key_fk=" + key + ";";

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

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

            String delete_party = "Delete from " + party_table + " where key_fk=" + key + ";";

            String delete = delete_detail + delete_stock + delete_party + delete_ledger;

            String stock = "  insert into stock(pidno,cidno,edate,refno,estatus,product,partno,description,rec,iss,rate,gross_amount,disc_rate,disc,net_amount,acode,inspect_id) " +
                           "  values (@key,(select SCOPE_IDENTITY()),@edate,@refno,@type,@item,@partno,@desc,@rec,@iss,@rate,@amt,@disc_rate,@disc,@amount,@acode,@inspect_id)";
            try
            {

                using (con = new SqlConnection(cs))
                {

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

                    using (cm = new SqlCommand("select ent_no from " + master_table + " where key_pk=" + key + "", con, trans))
                    {

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

                    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";
                        JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                    }


                    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("remarks", json_object["remarks"].ToString());
                        cm.Parameters.AddWithValue("qty", json_object["qty"].ToString());
                        cm.Parameters.AddWithValue("gross", json_object["gross"].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("acode", SqlDbType.VarChar);
                            cm.Parameters.Add("c_code", SqlDbType.VarChar);
                            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("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_rate", SqlDbType.Decimal);
                            cm.Parameters.Add("amount", SqlDbType.Decimal);
                            cm.Parameters.Add("inspect_id", 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("iss", SqlDbType.Decimal);
                            cm.Parameters.Add("amt", SqlDbType.Decimal);


                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["item"].Value = Convert.ToInt32(row["item"]) == 0 ? (Object)DBNull.Value : Convert.ToInt32(row["item"]);
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"]);
                                cm.Parameters["c_code"].Value = Convert.ToString(json_object["credit"]);
                                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["rate"].Value = Convert.ToDecimal(row["rate"]);
                                cm.Parameters["disc"].Value = Convert.ToDecimal(row["disc"]);
                                cm.Parameters["disc_rate"].Value = Convert.ToDecimal(row["disc_rate"]);
                                cm.Parameters["amount"].Value = Convert.ToDecimal(row["amount"]);
                                cm.Parameters["inspect_id"].Value = Convert.ToInt32(json_object["inspect_id"].ToString());

                                cm.Parameters["edate"].Value = date;
                                cm.Parameters["refno"].Value = invno;
                                cm.Parameters["type"].Value = type;
                                cm.Parameters["rec"].Value = (Object)DBNull.Value;
                                cm.Parameters["iss"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["amt"].Value = Convert.ToDecimal(Convert.ToDecimal(row["qty"]) * Convert.ToDecimal(row["rate"]));
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"]);

                                rowseffected += cm.ExecuteNonQuery();

                            }
                        }

                        using (cm = new SqlCommand(party, con, trans))
                        {
                            rowseffected = 0;
                            cm.Parameters.Add("key_fk", SqlDbType.Int);
                            cm.Parameters.Add("acode", SqlDbType.VarChar);
                            cm.Parameters.Add("gross", SqlDbType.Decimal);
                            cm.Parameters.Add("disc", SqlDbType.Decimal);
                            cm.Parameters.Add("disc_per", SqlDbType.Decimal);
                            cm.Parameters.Add("net_amount", SqlDbType.Decimal);

                            foreach (DataRow row in table_party.Rows)
                            {
                                cm.Parameters["key_fk"].Value = key;
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"].ToString().Trim());
                                cm.Parameters["gross"].Value = Convert.ToDecimal(row["gross"].ToString()).ToString("N0");
                                cm.Parameters["disc"].Value = Convert.ToDecimal(row["disc"].ToString()).ToString("N0");
                                cm.Parameters["disc_per"].Value = Convert.ToDecimal(row["disc_per"].ToString());
                                cm.Parameters["net_amount"].Value = Convert.ToDecimal(row["net_amount"].ToString()).ToString("N0");

                                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)
                            {
                                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 = 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;

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

                }
            }

            return IsInsert.ToString();


        }

        public String Inspection_Purchase_Return_Invoice_Delete(String json)
        {

            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString();
            if (token != app_key)
            {
                return "404";
            }
            String Master = "Inspection_Purchase_Return_Invoice_Master";
            String Child = "Inspection_Purchase_Return_Invoice_Detail";
            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();
            int IsInsert = 0;
            int rows = 0;

            int invno = Convert.ToInt32(json_object["inv"].ToString());

            String response = "";

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

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

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

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

            String delete_detail = " Delete from " + Child + " where key_fk=" + key + ";";

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

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

            String delete_party = "Delete from Inspection_Purchase_Return_Invoice_Detail_Party where key_fk=" + key + ";";

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

            DataTable st = new DataTable();
            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("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 + "','Delete Entry','" + JSONString + "'," + UserId + ")", con, trans))
                    {

                        rows = cm.ExecuteNonQuery();

                    }

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

                        rows = cm.ExecuteNonQuery();

                    }

                    if (rows > 0)
                    {

                        trans.Commit();
                        IsInsert = invno;

                    }

                    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 Get_Inspection_Purchase_Return_Invoice(String json)
        {

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

            String id = json_object["invoice_no"].ToString().Trim();
            String Master = "Inspection_Purchase_Return_Invoice_Master";
            String Child = "Inspection_Purchase_Return_Invoice_Detail";


            String query = "";

            String query1 = " select sm.* from " + Master + " sm  ";

            String query2 = " select sd.* from " + Child + " sd  ";

            String query3 = " select  * from inspection_invoice_labour  ";

            String query4 = " select im.* from inspection_master im inner join Inspection_Purchase_Return_Invoice_Master inv on inv.inspection_id=im.id ";

            String query5 = " select im.*,ac.title from Inspection_Purchase_Return_Invoice_Detail_Party im inner join ac on ac.code = im.acode ";

            query1 += " where sm.key_pk=" + id + ";";
            query2 += " where sd.key_fk=" + id + "  order by sd.key_pk ;";
            query3 += " where key_fk=" + id + "  order by id ;";
            query4 += " where inv.key_pk=" + id + ";";
            query5 += " where key_fk=" + id + " order by key_pk;";

            query = query1 + query2 + query3 + query4 + query5;

            return IList_GetDataSet(query);
        }

        public String Inspection_Purchase_Return_Invoice_Print(String json)
        {
            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString();

            if (token != app_key)
            {
                return "404";
            }
            String where = " ";
            String where2 = " ";


            if (json_object["idno"] != null)
            {
                if (Convert.ToInt32(json_object["idno"].ToString()) > 0)
                {
                    where += " and im.key_pk=" + json_object["idno"].ToString();
                    where2 += " and im.key_fk=" + json_object["idno"].ToString();

                    if (json_object["Child"] != null)
                    {

                        where = " and (";
                        where2 = " and (";

                        DataTable table = (DataTable)JsonConvert.DeserializeObject(json_object["Child"].ToString(), (typeof(DataTable)));

                        foreach (DataRow row in table.Rows)
                        {
                            where += " ac.code='" + row[0].ToString() + "' or";

                        }
                        where = where.Substring(0, where.Length - 3);
                        where += " )";

                        foreach (DataRow row in table.Rows)
                        {
                            where2 += " im.acode='" + row[0].ToString() + "' or";

                        }
                        where2 = where2.Substring(0, where2.Length - 3);
                        where2 += " )";
                    }
                }
            }
            if (json_object["insp_id"] != null)
            {
                where += " and im.inspection_id=" + json_object["insp_id"].ToString();
                where2 += " and im.inspection_id=" + json_object["insp_id"].ToString();
            }
            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 ;";

            query += " select im.key_pk as keys,im.invoice_no,im.clkdate,ac.code,ac.title,ip.gross as inv_gross,ip.disc as inv_disc, " +
                     " ip.disc_per as inv_disc_per,ip.net_amount as inv_net_amount,ac.add1,c.name,ac.cell1 " +
                     " from Inspection_Purchase_Return_Invoice_Master im " +
                     " inner join Inspection_Purchase_Return_Invoice_Detail_Party ip on im.key_pk=ip.key_fk " +
                     " inner join ac on ac.code=ip.acode left join City c on c.code=ac.city_code " +
                     " where im.key_pk is not null " + where + " order by ip.key_pk;";

            query += " select im.acode,ip.gross as inv_gross,ip.disc as inv_disc,ip.disc_per as inv_disc_per,ip.net_amount as inv_net_amount,im.* " +
                     " from Inspection_Purchase_Return_Invoice_Detail im inner join Inspection_Purchase_Return_Invoice_Detail_Party ip on im.acode = ip.acode and ip.key_fk=im.key_fk " +
                     " where im.key_fk is not null " + where2;

            return IList_GetDataSet(query);
        }


        #endregion
      
        #region ToolsPurchase
        public String LoadInventoryInvoices(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String token = json_Object["token"].ToString();
            if (token != app_key)
            {
                return "404";
            }

            String data = "";
            String query = " select title,code,iden from ac where type='Child'  order by title;" +
                           " select * from tools order by part_no ; " +
                           " 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 Inventory_Item_Get(String where, String token, String partno)
        {
            if (token != app_key)
            {
                return "404";
            }
            String query = "  SELECT * FROM tools where part_no  like '%" + partno + "%'";

            return IList_GetTable(query);

        }

        public String Inventory_Get_Invoice_By_Id(String table, String json)
        {
            String query = "";
            String data = "";
            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString();
            if (token != app_key)
            {
                return "404";
            }

            if (table == "Get Invoice")
            {

                query = " select distinct sm.key_pk,sm.clkdate,sm.days,sm.duedate,sm.dscr_p as inv_disc,sm.disc as inv_disc_amt,sm.mrdminv_no,sm.invtype,sm.invoice_no,sm.c_code as acode,sm.prtclar,sm.expmnininv,sm.courier,sm.gstp,sm.gsta,sm.itp,sm.ita,sm.prtclar,sd.citmno,sd.prtno," +
                        " sd.key_fk,sd.key_pk as sn,sd.vndrcd,sd.acitno,sd.invdesc,sd.qty,sd.rate,sd.amt,sd.dscrate,sd.disc,sd.dscr_p,sd.ntamt  from " + json_object["Master"] + " sm inner join " + json_object["Child"] + " sd on sm.key_pk=sd.key_fk " +
                        " where sm.key_pk=" + json_object["id"].ToString() + " or sm.invoice_no=" + json_object["invoice_no"].ToString() + " order by sn;";

                data = IList_GetTable(query);

            }

            else if (table == "Invoice Next")
            {
                int invoice = 0;
                invoice = Invoice_Next(Convert.ToInt32(json_object["id"].ToString()), json_object["Master"].ToString(), json_object["Child"].ToString());
                query = " select distinct sm.key_pk,sm.clkdate,sm.days,sm.duedate,sm.dscr_p as inv_disc,sm.disc as inv_disc_amt,sm.mrdminv_no,sm.invtype,sm.invoice_no,sm.c_code as acode,sm.prtclar,sm.expmnininv,sm.courier,sm.gstp,sm.gsta,sm.itp,sm.ita,sm.prtclar,sd.citmno,sd.prtno," +
                        " sd.key_fk,sd.key_pk as sn,sd.vndrcd,sd.acitno,sd.invdesc,sd.qty,sd.rate,sd.amt,sd.dscrate,sd.disc,sd.dscr_p,sd.ntamt  from " + json_object["Master"] + " sm inner join " + json_object["Child"] + " sd on sm.key_pk=sd.key_fk " +
                        " where sm.key_pk=" + invoice + " order by sn";

                data = IList_GetTable(query);
            }

            else if (table == "Invoice Previous")
            {
                int invoice = 0;
                invoice = Invoice_Previous(Convert.ToInt32(json_object["id"].ToString()), json_object["Master"].ToString(), json_object["Child"].ToString());
                query = " select distinct sm.key_pk,sm.clkdate,sm.days,sm.duedate,sm.dscr_p as inv_disc,sm.disc as inv_disc_amt,sm.mrdminv_no,sm.invtype,sm.invoice_no,sm.c_code as acode,sm.prtclar,sm.expmnininv,sm.courier,sm.gstp,sm.gsta,sm.itp,sm.ita,sm.prtclar,sd.citmno,sd.prtno," +
                        " sd.key_fk,sd.key_pk as sn,sd.vndrcd,sd.acitno,sd.invdesc,sd.qty,sd.rate,sd.amt,sd.dscrate,sd.disc,sd.dscr_p,sd.ntamt  from " + json_object["Master"] + " sm inner join " + json_object["Child"] + " sd on sm.key_pk=sd.key_fk " +
                         " where sm.key_pk=" + invoice + " order by sn";
                data = IList_GetTable(query);
            }

            else if (table == "Invoice First")
            {
                int invoice = 0;
                invoice = Invoice_First(json_object["Master"].ToString(), json_object["Child"].ToString());
                query = " select distinct sm.key_pk,sm.clkdate,sm.days,sm.duedate,sm.dscr_p as inv_disc,sm.disc as inv_disc_amt,sm.mrdminv_no,sm.invtype,sm.invoice_no,sm.c_code as acode,sm.prtclar,sm.expmnininv,sm.courier,sm.gstp,sm.gsta,sm.itp,sm.ita,sm.prtclar,sd.citmno,sd.prtno," +
                        " sd.key_fk,sd.key_pk as sn,sd.vndrcd,sd.acitno,sd.invdesc,sd.qty,sd.rate,sd.amt,sd.dscrate,sd.disc,sd.dscr_p,sd.ntamt  from " + json_object["Master"] + " sm inner join " + json_object["Child"] + " sd on sm.key_pk=sd.key_fk " +
                        " where sm.key_pk=" + invoice + " order by sn";
                data = IList_GetTable(query);
            }

            else if (table == "Invoice Last")
            {
                int invoice = 0;
                invoice = Invoice_Last(json_object["Master"].ToString(), json_object["Child"].ToString());
                query = " select distinct sm.key_pk,sm.clkdate,sm.days,sm.duedate,sm.dscr_p as inv_disc,sm.disc as inv_disc_amt,sm.mrdminv_no,sm.invtype,sm.invoice_no,sm.c_code as acode,sm.prtclar,sm.expmnininv,sm.courier,sm.gstp,sm.gsta,sm.itp,sm.ita,sm.prtclar,sd.citmno,sd.prtno," +
                        " sd.key_fk,sd.key_pk as sn,sd.vndrcd,sd.acitno,sd.invdesc,sd.qty,sd.rate,sd.amt,sd.dscrate,sd.disc,sd.dscr_p,sd.ntamt  from " + json_object["Master"] + " sm inner join " + json_object["Child"] + " sd on sm.key_pk=sd.key_fk " +
                        " where sm.key_pk=" + invoice + " order by sn";
                data = IList_GetTable(query);
            }
            return data;

        }

        public String Inventory_Invoice_Insert(String json)
        {

            JObject json_object = JObject.Parse(json);

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

            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();
            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,invdesc,qty,rate,amt,dscrate,dscr_p,disc,ntamt) values "
                             + " (@key,@sno,@item,@partno,@desc,@qty,@rate,@amt,@disc_rate,@disc_p,@disc,@amount)";

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

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


            String ledger = " insert into ledger(edate,description,details,type,ref,d_acode,d_amt,c_acode,c_amt,pidno,per,posted,entryno) " +
                            " values(@edate,@desc,@det,@type,@ref,@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("acode", json_object["acode"].ToString());
                        cm.Parameters.AddWithValue("debit", json_object["debit"].ToString());
                        cm.Parameters.AddWithValue("credit", json_object["credit"].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("users", (json_object["UserId"] == null ? (Object)DBNull.Value : Convert.ToInt32(json_object["UserId"].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("desc", 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("iss", SqlDbType.Decimal);
                            cm.Parameters.Add("acode", SqlDbType.VarChar);

                            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["desc"].Value = Convert.ToString(row["desc"]);
                                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["iss"].Value = Convert.ToDecimal(row["iss"]);
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"]);

                                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("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["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)
                            {
                                {

                                    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 = 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 Inventory_Invoice_Update(String json)
        {

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

            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 UserId = json_object["UserId"].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 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,invdesc,qty,rate,amt,dscrate,dscr_p,disc,ntamt) values "
                           + " (@key,@sno,@item,@partno,@desc,@qty,@rate,@amt,@disc_rate,@disc_p,@disc,@amount)";

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

            String OrderMaster = "  Update " + json_object["Master"] + " set invtype=@invtype,clkdate=@edate,date=@edate,acode=@acode,d_code=@debit,c_code=@credit,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,citmno=@qty where key_pk=@key_pk";

            String ledger = " insert into ledger(edate,description,details,type,ref,d_acode,d_amt,c_acode,c_amt,pidno,per,posted,entryno) " +
                            " values(@edate,@desc,@det,@type,@ref,@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 inventory_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();
            String JSONString = "";
            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 (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";
                        JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                    }


                    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("acode", json_object["acode"].ToString());
                        cm.Parameters.AddWithValue("debit", json_object["debit"].ToString());
                        cm.Parameters.AddWithValue("credit", json_object["credit"].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("qty", json_object["qty"].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("desc", 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("iss", SqlDbType.Decimal);
                            cm.Parameters.Add("acode", SqlDbType.VarChar);


                            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["desc"].Value = Convert.ToString(row["desc"]);
                                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["iss"].Value = Convert.ToDecimal(row["iss"]);
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"]);

                                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("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["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 (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 int Inventory_Invoice_Delete(String jsondata)
        {
            int IsDelete = 0;
            JObject json_object = JObject.Parse(jsondata);

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

            int invoice = Convert.ToInt32(json_object["inv"].ToString());
            String system = json_object["User"].ToString();
            String UserId = json_object["UserId"].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 = "";

            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 inventory_stock where estatus='" + type + "' and refno=" + invoice + " 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 Insert_Tools(String json)
        {

            JObject json_object = JObject.Parse(json);
            int rowsEffected = 0;
            String token = json_object["token"].ToString();
            String system = json_object["User"].ToString();
            String UserId = json_object["UserId"].ToString();
            String User = json_object["System"].ToString();

            if (token.Trim() != app_key)
            {
                return 404;
            }
            String query = " select top 1 isnull(code,0) from tools  order by CAST(code AS INT) desc";
            String code = IList_ExecuteScalerValue_String(query);
            if (code == String.Empty)
            {
                code = "00001";
            }
            else
            {
                code = (Convert.ToInt32(code) + 1).ToString().PadLeft(5, '0');
            }
            String name = json_object["name"].ToString();
            String prt = json_object["partno"].ToString();
            decimal qty = Convert.ToDecimal(json_object["qty"].ToString());
            decimal rate = Convert.ToDecimal(json_object["rate"].ToString());
            decimal amount = Convert.ToDecimal(json_object["amount"].ToString());
            String edate = json_object["edate"].ToString();
            int active = Convert.ToInt32(json_object["active"].ToString());
            int cat = Convert.ToInt32(json_object["cat"].ToString());
            query = " Insert Into tools(code,part_no,name,op_qty,cat,active,rate,amount,edate) " +
                    " values('" + code + "','" + prt + "','" + name + "'," + qty + "," + cat + "," + active + "," + rate + "," + amount + ",'" + edate + "');(select SCOPE_IDENTITY());";
            rowsEffected = IList_ExecuteScalerValue(query);

            if (rowsEffected > 0)
            {
                String stock = "insert into inventory_stock(pidno,cidno,edate,refno,estatus,product,description,rec,rate,gross_amount,disc_rate,disc,net_amount) " +
                      "  values (" + rowsEffected + "," + rowsEffected + ",'" + edate + "','" + code + "','OP','" + rowsEffected + "','OPENING QTY'," + qty + "," + rate + "," + amount + ",0,0," + amount + ")";
                IList_execute(stock);
            }
            String Log = "Insert into Log(Entry,type,edate,s_user,l_user,remarks,data,users_id) values(" + rowsEffected + ",'TL','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + User + "','" + system + "','New Entry',''," + UserId + ")";
            IList_execute(Log);

            return rowsEffected;

        }

        public int Update_Tools(String json)
        {
            JObject json_object = JObject.Parse(json);
            int rowsEffected = 0;
            String token = json_object["token"].ToString();
            String system = json_object["User"].ToString();
            String UserId = json_object["UserId"].ToString();
            String User = json_object["System"].ToString();

            if (token.Trim() != app_key)
            {
                return 404;
            }
            String query = "";
            String id = json_object["id"].ToString();
            String name = json_object["name"].ToString();
            String prt = json_object["partno"].ToString();
            decimal qty = Convert.ToDecimal(json_object["qty"].ToString());
            decimal rate = Convert.ToDecimal(json_object["rate"].ToString());
            decimal amount = Convert.ToDecimal(json_object["amount"].ToString());
            String edate = json_object["edate"].ToString();
            int active = Convert.ToInt32(json_object["active"].ToString());
            int cat = Convert.ToInt32(json_object["cat"].ToString());
            query = "select * from tools where id=" + id;
            String data = IList_GetTable(query);

            query = " Update tools set Name='" + name + "',part_no='" + prt + "',op_qty=" + qty + ",rate=" + rate + "," +
                    " amount=" + amount + ",active=" + active + ",cat=" + cat + ",edate='" + edate + "' where id=" + id;
            rowsEffected = IList_execute(query);

            if (rowsEffected > 0)
            {
                String stock = " Update inventory_stock set edate='" + edate + "',rec=" + qty + ",rate=" + rate + ",gross_amount=" + amount + ",net_amount=" + amount + " where estatus='OP' and product=" + id;
                IList_execute(stock);
            }
            String Log = "Insert into Log(Entry,type,edate,s_user,l_user,remarks,data,users_id) values(" + rowsEffected + ",'TL','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + User + "','" + system + "','Modified Entry','" + data + "'," + UserId + ")";
            IList_execute(Log);

            return rowsEffected;
        }

        public String Tools_Invoice_Print(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 ;";

            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,sm.itp,sm.ita,sd.acitno,it.part_no as partno,it.name as desc_cr,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 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 tools it on it.id=sd.acitno" +
                      "  where sm.key_pk=" + json_object["idno"].ToString() + " order by sn;";


            return IList_GetDataSet(query);
        }

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

            if (token.Trim() != app_key)
            {
                return "404";
            }

            String query = "Select code,title,city_code from ac where iden='SPAC' order by title;" +
                         " select * from tools order by name; " +
                         " select * from tool_category order by name;";


            return IList_GetDataSet(query);

        }

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

            if (token.Trim() != app_key)
            {
                return "404";
            }

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

            String query = "";
            String Master = json_Object["Master"].ToString();
            String Child = json_Object["Child"].ToString();
            String where = "";
            String where2 = "";
            String where3 = "";

            if (index == 0 || index == 4)
            {

                {
                    if (json_Object["partno"].ToString() != String.Empty)
                    {
                        where3 += " and im.id=" + json_Object["partno"].ToString().Trim();
                        where2 += " and im.id=" + json_Object["partno"].ToString().Trim();
                    }
                    if (json_Object["category"].ToString() != String.Empty)
                    {
                        where3 += " and cat.id=" + json_Object["category"].ToString().Trim();
                        where2 += " and cat.id=" + json_Object["category"].ToString().Trim();
                    }
                    if (json_Object["desc"].ToString() != String.Empty)
                    {
                        where3 += " and cat.name like '%" + json_Object["desc"].ToString().Trim() + "%'";
                        where2 += " and im.id=" + json_Object["partno"].ToString().Trim();
                    }
                    if (json_Object["from"].ToString() != String.Empty)
                    {

                        where = " And  CAST(sm.clkdate AS DATE) >= CAST( '" + json_Object["from"].ToString() + "' AS DATE)   ";
                        where2 = " And  CAST(sm.clkdate AS DATE) >= CAST( ''" + json_Object["from"].ToString() + "'' AS DATE)   ";

                    }
                    if (json_Object["to"].ToString() != String.Empty)
                    {
                        where = " And CAST(sm.clkdate AS DATE) <= CAST( '" + json_Object["to"].ToString() + "' AS DATE) ";
                        where2 = " And CAST(sm.clkdate AS DATE) <= CAST( ''" + json_Object["to"].ToString() + "'' 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() + "'' ";
                    }

                }
                query = "   WITH GroupedData AS( " +
                         "  select sd.key_fk,count(*) as [Qty],sum(sd.amt) as [Amount],sum(sd.disc) as [DiscAmount]" +
                         " from " + Master + " sm inner join " + Child + "  sd on sm.key_pk=sd.key_fk  " +
                         " left join ac on ac.code=sm.acode left join tools im on im.id=sd.acitno left  join tool_category cat on cat.id=im.cat " +
                         " where sd.key_fk is not null " + where3 + " group by sd.key_fk) " +
                         "(" +
                         "  select sm.key_pk as [Computrized_No],sm.invoice_no as [Invno],FORMAT(Cast( sm.clkdate as Date), 'dd-MM-yyyy') as [InvDate], " +
                         "  ac.title as [Party],gd.Qty,gd.Amount,(sm.disc+gd.DiscAmount) as [DiscAmount],(sm.expmnininv+sm.courier) as [Charges], " +
                         "  sm.gsta as [GstAmount],sm.ita as [VatAmount],(gd.Amount-(sm.disc+gd.DiscAmount)+gsta+ita+sm.expmnininv+sm.courier) as[Net_Amount] from GroupedData gd " +
                         " inner join " + Master + " sm on sm.key_pk=gd.key_fk  left join ac on ac.code=sm.acode " +
                         " where  sm.key_pk is not null " + where + " ) order by [Invno],[InvDate] ";

            }

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

                {
                    if (json_Object["partno"].ToString() != String.Empty)
                    {
                        where += " and im.id=" + json_Object["partno"].ToString().Trim();
                    }
                    if (json_Object["category"].ToString() != String.Empty)
                    {
                        where += " and cat.id=" + json_Object["category"].ToString().Trim();
                    }
                    if (json_Object["desc"].ToString() != String.Empty)
                    {
                        where += " and cat.name like '%" + json_Object["desc"].ToString().Trim() + "%'";
                    }
                    if (json_Object["from"].ToString() != String.Empty)
                    {

                        where = " And  CAST(sm.clkdate AS DATE) >= CAST( '" + json_Object["from"].ToString() + "' AS DATE)   ";

                    }

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

                    }


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

                query = "  select distinct im.id as Idno,im.part_no as Partno,im.name as Part_Descr, 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" +
                            " left join ac on ac.code=sm.acode left join tools im on im.id=sd.acitno " +
                            " left  join tool_category cat on cat.id=im.cat  " +
                             " where im.id is not null " + where + " group by im.id,im.part_no,im.name order by im.name;";



            }

            else if (index == 2 || index == 6)
            {
                {
                    if (json_Object["partno"].ToString() != String.Empty)
                    {
                        where += " and im.id=" + json_Object["partno"].ToString().Trim();
                    }
                    if (json_Object["category"].ToString() != String.Empty)
                    {
                        where += " and cat.id=" + json_Object["category"].ToString().Trim();
                    }
                    if (json_Object["desc"].ToString() != String.Empty)
                    {
                        where += " and cat.name like '%" + json_Object["desc"].ToString().Trim() + "%'";
                    }
                    if (json_Object["from"].ToString() != String.Empty)
                    {
                        where = " And  CAST(sm.clkdate AS DATE) >= CAST( '" + json_Object["from"].ToString() + "' AS DATE)   ";
                    }
                    if (json_Object["to"].ToString() != String.Empty)
                    {
                        where = " And CAST(sm.clkdate AS DATE) <= CAST( '" + json_Object["to"].ToString() + "' AS DATE) ";

                    }
                    if (json_Object["acode"].ToString() != String.Empty)
                    {
                        where += " and ac.code='" + json_Object["acode"].ToString().Trim() + "'";
                    }
                }
                query = "  select idno,isnull(PartNo,'') as Partno,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.id as idno, isnull(im.part_no,'') as PartNo,isnull(im.name,'') as Description,sum(sd.ntamt) as[Amount] from " + Master + " sm inner join " + Child + " sd on sm.key_pk=sd.key_fk " +
                      " left join ac on ac.code=sm.acode left join tools im on im.id=sd.acitno " +
                      " left  join tool_category cat on cat.id=im.cat  " +
                      " where im.id is not null " + where + "  group by YEAR(sm.clkdate)*100 + MONTH(sm.clkdate),Cast( DateName( month , DateAdd( month ,MONTH(sm.clkdate) , -1 )) as Varchar(3)),im.id,im.part_no,im.name" +
                     " ) 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 == 7)
            {

                {
                    if (json_Object["partno"].ToString() != String.Empty)
                    {
                        where += " and im.id=" + json_Object["partno"].ToString().Trim();
                    }
                    if (json_Object["category"].ToString() != String.Empty)
                    {
                        where += " and cat.id=" + json_Object["category"].ToString().Trim();
                    }
                    if (json_Object["desc"].ToString() != String.Empty)
                    {
                        where += " and cat.name like '%" + json_Object["desc"].ToString().Trim() + "%'";
                    }
                    if (json_Object["from"].ToString() != String.Empty)
                    {
                        where = " And  CAST(sm.clkdate AS DATE) >= CAST( '" + json_Object["from"].ToString() + "' AS DATE)   ";
                    }
                    if (json_Object["to"].ToString() != String.Empty)
                    {
                        where = " And CAST(sm.clkdate AS DATE) <= CAST( '" + json_Object["to"].ToString() + "' AS DATE) ";

                    }
                    if (json_Object["acode"].ToString() != String.Empty)
                    {
                        where += " and ac.code='" + json_Object["acode"].ToString().Trim() + "'";
                    }
                }
                query = "  select idno,isnull(PartNo,'') as Partno,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.id as idno, isnull(im.part_no,'') as PartNo,isnull(im.name,'') as Description,sum(sd.qty) as[Amount] from " + Master + " sm inner join " + Child + " sd on sm.key_pk=sd.key_fk " +
                         " left join ac on ac.code=sm.acode left join tools im on im.id=sd.acitno " +
                          " left  join tool_category cat on cat.id=im.cat  " +
                          where + "  group by YEAR(sm.clkdate)*100 + MONTH(sm.clkdate),Cast( DateName( month , DateAdd( month ,MONTH(sm.clkdate) , -1 )) as Varchar(3)),im.id,im.part_no,im.name" +
                         " ) t pivot (Sum(Amount) For Period IN([Jan],[Feb],[Mar],[Apr],[May],[Jun],[Jul],[Aug],[Sep],[Oct],[Nov],[Dec]) ) as pivot_table";

            }

            return IList_GetTable(query);
        }


        #endregion

        #region InevntoryIssued
        public String LoadInventoryIssued(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String token = json_Object["token"].ToString();
            if (token != app_key)
            {
                return "404";
            }

            String data = "";
            String query = " select id as code,name as title from employees order by name;" +
                           " select * from tools order by part_no ; " +
                           " 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 Inventory_Issued_Invoice_By_Id(String table, String json)
        {
            String query = "";
            String data = "";
            JObject json_object = JObject.Parse(json);
            String token = json_object["token"].ToString();
            if (token != app_key)
            {
                return "404";
            }

            if (table == "Get Invoice")
            {

                query = " select distinct sm.key_pk,sm.invoice_no,sm.clkdate,sm.employee,sm.prtclar,sd.citmno,sd.prtno," +
                        " sd.acitno,sd.invdesc,sd.issued_qty,sd.return_qty,sd.loss_qty,sd.balance_qty  from " + json_object["Master"] + " sm inner join " + json_object["Child"] + " sd on sm.key_pk=sd.key_fk " +
                        " where sm.key_pk=" + json_object["id"].ToString() + " or sm.invoice_no=" + json_object["invoice_no"].ToString() + " order by citmno;";

                data = IList_GetTable(query);

            }

            else if (table == "Invoice Next")
            {
                int invoice = 0;
                invoice = Invoice_Next(Convert.ToInt32(json_object["id"].ToString()), json_object["Master"].ToString(), json_object["Child"].ToString());
                query = " select distinct sm.key_pk,sm.invoice_no,sm.clkdate,sm.employee,sm.prtclar,sd.citmno,sd.prtno," +
                        " sd.acitno,sd.invdesc,sd.issued_qty,sd.return_qty,sd.loss_qty,sd.balance_qty  from " + json_object["Master"] + " sm inner join " + json_object["Child"] + " sd on sm.key_pk=sd.key_fk " +
                        " where sm.key_pk=" + invoice + " order by citmno";

                data = IList_GetTable(query);
            }

            else if (table == "Invoice Previous")
            {
                int invoice = 0;
                invoice = Invoice_Previous(Convert.ToInt32(json_object["id"].ToString()), json_object["Master"].ToString(), json_object["Child"].ToString());
                query = " select distinct sm.key_pk,sm.invoice_no,sm.clkdate,sm.employee,sm.prtclar,sd.citmno,sd.prtno," +
                        " sd.acitno,sd.invdesc,sd.issued_qty,sd.return_qty,sd.loss_qty,sd.balance_qty  from " + json_object["Master"] + " sm inner join " + json_object["Child"] + " sd on sm.key_pk=sd.key_fk " +
                         " where sm.key_pk=" + invoice + " order by citmno";
                data = IList_GetTable(query);
            }

            else if (table == "Invoice First")
            {
                int invoice = 0;
                invoice = Invoice_First(json_object["Master"].ToString(), json_object["Child"].ToString());
                query = " select distinct sm.key_pk,sm.invoice_no,sm.clkdate,sm.employee,sm.prtclar,sd.citmno,sd.prtno," +
                        " sd.acitno,sd.invdesc,sd.issued_qty,sd.return_qty,sd.loss_qty,sd.balance_qty  from " + json_object["Master"] + " sm inner join " + json_object["Child"] + " sd on sm.key_pk=sd.key_fk " +
                        " where sm.key_pk=" + invoice + " order by citmno";
                data = IList_GetTable(query);
            }

            else if (table == "Invoice Last")
            {
                int invoice = 0;
                invoice = Invoice_Last(json_object["Master"].ToString(), json_object["Child"].ToString());
                query = " select distinct sm.key_pk,sm.invoice_no,sm.clkdate,sm.employee,sm.prtclar,sd.citmno,sd.prtno," +
                        " sd.acitno,sd.invdesc,sd.issued_qty,sd.return_qty,sd.loss_qty,sd.balance_qty  from " + json_object["Master"] + " sm inner join " + json_object["Child"] + " sd on sm.key_pk=sd.key_fk " +
                        " where sm.key_pk=" + invoice + " order by citmno";
                data = IList_GetTable(query);
            }
            return data;

        }

        public String Inventory_Issued_Insert(String json)
        {

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

            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 UserId = json_object["UserId"].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 Order1 = " insert into " + json_object["Master"] + "(key_pk,usrno__,invtype,clkdate,date,invoice_no,prtclar,employee) values ";
            String Order2 = " (@key_pk,@userno,@invtype,@edate,@date,@invoice,@remarks,@employee); ";
            String OrderMaster = Order1 + Order2;

            String detail = " insert into " + json_object["Detail"] + "(key_fk,citmno,acitno,prtno,invdesc,issued_qty,return_qty,loss_qty,balance_qty) values "
                                        + " (@key,@sno,@item,@partno,@desc,@issued_qty,@return_qty,@loss_qty,@balance_qty)";

            String stock = "insert into inventory_stock(pidno,cidno,edate,refno,estatus,product,description,rec,iss,damage,employees) " +
                        "  values (@key,(select SCOPE_IDENTITY()),@edate,@refno,@type,@item,@desc,@return_qty,@issued_qty,@loss_qty,@employees)";


            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();
            int employees = 0;
            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 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("remarks", json_object["remarks"].ToString());
                        cm.Parameters.AddWithValue("employee", json_object["employee"].ToString());
                        employees = Convert.ToInt32(json_object["employee"].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("desc", SqlDbType.VarChar);
                            cm.Parameters.Add("issued_qty", SqlDbType.Decimal);
                            cm.Parameters.Add("return_qty", SqlDbType.Decimal);
                            cm.Parameters.Add("loss_qty", SqlDbType.Decimal);
                            cm.Parameters.Add("balance_qty", SqlDbType.Decimal);


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

                            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["desc"].Value = Convert.ToString(row["desc"]);
                                cm.Parameters["issued_qty"].Value = Convert.ToDecimal(row["issued_qty"]);
                                cm.Parameters["return_qty"].Value = Convert.ToDecimal(row["return_qty"]);
                                cm.Parameters["loss_qty"].Value = Convert.ToDecimal(row["loss_qty"]);
                                cm.Parameters["balance_qty"].Value = Convert.ToDecimal(row["balance_qty"]);

                                cm.Parameters["edate"].Value = date;
                                cm.Parameters["refno"].Value = invno;
                                cm.Parameters["type"].Value = type;
                                cm.Parameters["employees"].Value = employees;


                                rowseffected += cm.ExecuteNonQuery();

                            }
                        }

                        if (rowseffected > 0)
                        {
                            {

                                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 = 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 Inventory_Issued_Update(String json)
        {

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

            String child = json_object["Child"].ToString();
            DataTable table = (DataTable)JsonConvert.DeserializeObject(child, (typeof(DataTable)));
            String system = json_object["User"].ToString();
            String UserId = json_object["UserId"].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 entryno = 0;
            int invno = Convert.ToInt32(json_object["inv"].ToString());

            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;


            String OrderMaster = "  Update " + json_object["Master"] + " set invtype=@invtype,clkdate=@edate,date=@edate,employee=@employee,prtclar=@remarks " +
                            " where key_pk=@key_pk";

            String detail = " insert into " + json_object["Detail"] + "(key_fk,citmno,acitno,prtno,invdesc,issued_qty,return_qty,loss_qty,balance_qty) values "
                                                   + " (@key,@sno,@item,@partno,@desc,@issued_qty,@return_qty,@loss_qty,@balance_qty)";

            String stock = "insert into inventory_stock(pidno,cidno,edate,refno,estatus,product,description,rec,iss,damage,employees) " +
                        "  values (@key,(select SCOPE_IDENTITY()),@edate,@refno,@type,@item,@desc,@return_qty,@issued_qty,@loss_qty,@employees)";

            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 inventory_stock where estatus='" + type + "' and pidno=" + key + " and refno=" + Convert.ToInt32(json_object["inv"].ToString()) + ";";

            String delete = delete_detail + delete_stock;

            DataTable st = new DataTable();


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

            int employees = 0;


            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("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("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("remarks", json_object["remarks"].ToString());
                        cm.Parameters.AddWithValue("employee", json_object["employee"].ToString());
                        employees = Convert.ToInt32(json_object["employee"].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("desc", SqlDbType.VarChar);
                            cm.Parameters.Add("issued_qty", SqlDbType.Decimal);
                            cm.Parameters.Add("return_qty", SqlDbType.Decimal);
                            cm.Parameters.Add("loss_qty", SqlDbType.Decimal);
                            cm.Parameters.Add("balance_qty", SqlDbType.Decimal);


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

                            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["desc"].Value = Convert.ToString(row["desc"]);
                                cm.Parameters["issued_qty"].Value = Convert.ToDecimal(row["issued_qty"]);
                                cm.Parameters["return_qty"].Value = Convert.ToDecimal(row["return_qty"]);
                                cm.Parameters["loss_qty"].Value = Convert.ToDecimal(row["loss_qty"]);
                                cm.Parameters["balance_qty"].Value = Convert.ToDecimal(row["balance_qty"]);

                                cm.Parameters["edate"].Value = date;
                                cm.Parameters["refno"].Value = invno;
                                cm.Parameters["type"].Value = type;
                                cm.Parameters["employees"].Value = employees;

                                rowseffected += cm.ExecuteNonQuery();

                            }


                        }

                        if (rowseffected > 0)
                        {

                            {
                                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;

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

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

                }
            }


            return IsInsert.ToString();


        }

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

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

            int invoice = Convert.ToInt32(json_object["inv"].ToString());
            String system = json_object["User"].ToString();
            String UserId = json_object["UserId"].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 = "";

            DataTable table = new DataTable();

            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_stock = "Delete from inventory_stock where estatus='" + type + "' and refno=" + invoice + " and pidno=" + key + ";";

            String delete = delete_detail + delete_stock + 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 String Tools_Issued_Print(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 ;";

            query += "  select sm.key_pk,sm.invoice_no,sm.usrno__,sm.clkdate,sd.issued_qty, it.part_no as partno,it.name as desc_cr," +
                      "  sd.return_qty,sd.loss_qty,sd.balance_qty,emp.name,u.users_name as users from Inventory_Issued sm" +
                      "  inner join Inventory_Issued_Detail sd on sm.key_pk=sd.key_fk " +
                      "   inner join employees emp on emp.id=sm.employee   inner join tools it on it.id=sd.acitno" +
                      " left join users u on u.users=sm.usrno__" +
                      "  where sm.key_pk=" + json_object["idno"].ToString() + " order by sd.key_fk;";


            return IList_GetDataSet(query);
        }

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

            if (token.Trim() != app_key)
            {
                return "404";
            }

            String query = " select * from employees order by name;" +
                           " select * from tools order by name; " +
                           " select * from tool_category order by name;";


            return IList_GetDataSet(query);

        }

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

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

            if (token.Trim() != app_key)
            {
                return "404";
            }


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

            String query = "";

            String where = " where sm.invoice_no is not null ";

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

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

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

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

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

            if (json_Object["desc"].ToString() != String.Empty)
            {
                where += " and tc.name like '%" + json_Object["desc"].ToString().Trim() + "%'";
            }

            if (index == 0)
            {
                query = " select sm.key_pk as Computrized_No,sm.invoice_no as Issue_No,FORMAT(Cast( sm.clkdate as Date), 'dd-MM-yyyy') as Issued_Date,emp.name  as Employee,SUM(issued_qty) as Issued_Qty,SUM(return_qty) as Return_Qty, " +
                    " SUM(loss_qty) as [Loss_Qty],SUM(balance_qty) as [Balance_Qty] from Inventory_Issued sm " +
                    " inner join Inventory_Issued_Detail sd on sm.key_pk=sd.key_fk  inner join employees emp on emp.id=sm.employee " +
                    "  inner join tools t on t.id=sd.acitno  inner join tool_category tc on tc.id=t.cat" +
                  where + "  group by sm.key_pk,sm.invoice_no,sm.clkdate,emp.name  order by sm.clkdate";
            }

            if (index == 1)
            {
                query = " select sm.key_pk as Computrized_No,sm.invoice_no as Issue_No,FORMAT(Cast( sm.clkdate as Date), 'dd-MM-yyyy') as Issued_Date,emp.name as Employee,t.name as Description,SUM(issued_qty) as Issued_Qty,SUM(return_qty) as Return_Qty, " +
                    " SUM(loss_qty) as [Loss_Qty],SUM(balance_qty) as [Balance_Qty] from Inventory_Issued sm " +
                    " inner join Inventory_Issued_Detail sd on sm.key_pk=sd.key_fk  inner join employees emp on emp.id=sm.employee " +
                    "  inner join tools t on t.id=sd.acitno  inner join tool_category tc on tc.id=t.cat" +
                  where + " and balance_qty>0 group by sm.key_pk,sm.invoice_no,sm.clkdate,emp.name,t.id,t.name order by sm.clkdate";
            }

            if (index == 2)
            {
                query = " select sm.key_pk as Computrized_No,sm.invoice_no as Issue_No,FORMAT(Cast( sm.clkdate as Date), 'dd-MM-yyyy') as Issued_Date,emp.name as Employee,t.name as Description,SUM(issued_qty) as Issued_Qty,SUM(return_qty) as Return_Qty, " +
                    " SUM(loss_qty) as [Loss_Qty],SUM(balance_qty) as [Balance_Qty] from Inventory_Issued sm " +
                    " inner join Inventory_Issued_Detail sd on sm.key_pk=sd.key_fk  inner join employees emp on emp.id=sm.employee " +
                    "  inner join tools t on t.id=sd.acitno  inner join tool_category tc on tc.id=t.cat" +
                  where + " and loss_qty>0 group by sm.key_pk,sm.invoice_no,sm.clkdate,emp.name,t.id,t.name order by sm.clkdate";
            }

            return IList_GetTable(query);
        }

        public String Tools_Stock(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String token = json_Object["token"].ToString();
            if (token != app_key)
            {
                return "404";
            }

            String data = "";
            String query = "";
            String where = " where t.id is not null ";
            if (json_Object["partno"].ToString() != String.Empty)
            {
                where += " and t.id=" + json_Object["partno"].ToString().Trim();
            }

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

            if (json_Object["desc"].ToString() != String.Empty)
            {
                where += " and tc.name like '%" + json_Object["desc"].ToString().Trim() + "%'";
            }
            {
                query = " select t.id,t.part_no as PartNo,t.name as Part_Description,sum(ISNULL(rec,0))-sum(ISNULL(iss,0))-sum(ISNULL(damage,0)) as Balance ,tc.name as Category, " +
                        " (select top 1 sd.dscrate from Inventory_Master sm inner join Inventory_Detail sd on sm.key_pk=sd.key_fk where sd.acitno=t.id order by sm.clkdate desc) as Last_Pu_Rate " +
                        " from tools t inner join tool_category tc on t.cat=tc.id left join inventory_stock st on st.product=t.id" +
                          where + " group by t.id,t.name,t.part_no,tc.name";

            }
            data = IList_GetTable(query);
            return data;
        }

        #endregion

        #region ReportsInspection

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

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

            if (token.Trim() != app_key)
            {
                return "404";
            }

            String query = "select distinct reg_no from inspection_master; " +
                           " select distinct make from inspection_master; " +
                           " select distinct model from inspection_master; " +
                           " select distinct chasis_no from inspection_master;" +
                           " select distinct variant from inspection_master; " +
                           " select distinct[years] from inspection_master; " +
                           " select distinct tr_type from inspection_master; " +
                           " select distinct eng_no from inspection_master; " +
                           " select distinct colour from inspection_master;" +
                           " select distinct fuel_type from inspection_master;" +
                           " select id, name from inspection_category; ";

            return IList_GetDataSet(query);
        }

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

            if (token.Trim() != app_key)
            {
                return "404";
            }

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

            String query = "  ";
            String where = " where sm.id is not null ";
            if (json_Object["from"].ToString() != String.Empty)
            {
                where = " and CAST(sm.ins_date AS DATE) >= CAST( '" + json_Object["from"].ToString() + "' AS DATE) ";

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

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

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

            if (json_Object["make"].ToString() != String.Empty)
            {
                where += " and LTRIM(RTRIM(sm.make))='" + json_Object["make"].ToString().Trim() + "'";
            }
            if (json_Object["model"].ToString() != String.Empty)
            {
                where += " and LTRIM(RTRIM(sm.model)) ='" + json_Object["model"].ToString().Trim() + "'";
            }
            if (json_Object["vn_num"].ToString() != String.Empty)
            {
                where += " and LTRIM(RTRIM(sm.chasis_no))='" + json_Object["vn_num"].ToString().Trim() + "'";
            }
            if (json_Object["variant"].ToString() != String.Empty)
            {
                where += " and LTRIM(RTRIM( sm.variant))='" + json_Object["variant"].ToString().Trim() + "'";
            }
            if (json_Object["year"].ToString() != String.Empty)
            {
                where += " and sm.years=" + json_Object["year"].ToString().Trim();
            }
            if (json_Object["type"].ToString() != String.Empty)
            {
                where += " and LTRIM(RTRIM(sm.tr_type))='" + json_Object["type"].ToString().Trim() + "'";
            }
            if (json_Object["status"].ToString() != String.Empty)
            {
                /*if (json_Object["status"].ToString() == "Paid")
                {
                    where += " and sm.balance=0 ";
                }

                if (json_Object["status"].ToString() == "Unpaid")
                {
                    where += " and sm.balance>0 ";
                }*/

                if (json_Object["status"].ToString() == "Foc")
                {
                    where += " and sm.balance=0 ";
                }

            }
            if (json_Object["eng_no"].ToString() != String.Empty)
            {
                where += " and LTRIM(RTRIM(sm.eng_no)) ='" + json_Object["eng_no"].ToString().Trim() + "'";
            }
            if (json_Object["colour"].ToString() != String.Empty)
            {
                where += " and LTRIM(RTRIM(sm.colour))='" + json_Object["colour"].ToString().Trim() + "'";
            }
            if (json_Object["fuel_type"].ToString() != String.Empty)
            {
                where += " and LTRIM(RTRIM(sm.fuel_type))='" + json_Object["fuel_type"].ToString().Trim() + "'";
            }
            if (json_Object["cat"].ToString() != String.Empty)
            {
                where += " and cat.id=" + json_Object["cat"].ToString().Trim();
            }

            query = " select distinct sm.id as [Computrized_No],sm.vno as [Inspection_Id],FORMAT(Cast(sm.ins_date as Date), 'dd-MM-yyyy') as [Insp_Date],sm.chasis_no as [Reg_No],sm.customer as Customer,sm.reg_no as [Vn_Number],sm.eng_no as [Eng_No],sm.make as [Make],sm.model as [Model] " +
                    " ,sm.colour as [Colour],sm.variant as [Vairant],sm.years as [Years],sm.tr_type as [Type],sm.fuel_type as [Fuel_Type],sm.charges as [Charges],sm.paid as [Discount],sm.balance as [Balance],inv.Invoice_No from inspection_master sm " +
                    "  inner join inspection_detail sd on sm.id=sd.pidno  inner join inspection_parameter ip on ip.id=sd.inpection_parameter " +
                    "   inner join inspection_category ic on ic.id=ip.cat " +
                    " left join (select inspection_id,invoice_no from Inspection_Invoice_Master )inv on inv.inspection_id=sm.id " +
                     where + "   order by insp_date";



            return IList_GetTable(query);
        }

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

            if (token.Trim() != app_key)
            {
                return "404";
            }

            int id = Convert.ToInt32(json_Object["id"].ToString());
            String type = json_Object["type"].ToString().Trim();
            if (type=="PI")
            {
                id = IList_ExecuteScalerValue("SELECT inspection_id FROM Inspection_Purchase_Invoice_Master WHERE key_pk="+id);
            }
            if (type == "IR")
            {
                id = IList_ExecuteScalerValue("SELECT inspection_id FROM Inspection_Purchase_Return_Invoice_Master WHERE key_pk=" + id);

            }
            if (type == "SI")
            {
                id = IList_ExecuteScalerValue("SELECT inspection_id FROM Inspection_Invoice_Master WHERE key_pk=" + id);

            }

            if (type == "PO")
            {
                id = IList_ExecuteScalerValue("SELECT inspection_id FROM Inspection_Orders_Master WHERE key_pk=" + id);

            }
            String data = "";
            String absolute = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
            String apPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + @"images";

            String query = " Select * from inspection_master where id=" + id + ";" +
                           " select distinct im.inspection_master,ic.name from inspection_detail im inner join inspection_category ic on im.inspection_master=ic.id where im.pidno=" + id + " order by im.inspection_master;" +
                           " select im.inspection_master,im.inpection_parameter,ic.name,im.istatus,im.remarks from inspection_detail im inner join inspection_parameter ic on im.inpection_parameter=ic.id where im.pidno=" + id + " order by im.id;" +
                           " Select id,inspection_id,('" + apPath + "' +url) as url,name from inspection_images where inspection_id=" + id + " order by id ;" +
                           " select * from ac;" +

                             "  select sm.*,sd.*,sm.key_pk as keys,sd.key_pk as rowno, " +
                           " isnull(cat.id,0) as category_id,cat.name as cat_name,isnull(req.USERS,0) as req_id,req.USERS_NAME as req_name, " +
                           " isnull(appr.USERS,0) as approved_id,appr.USERS_NAME as approved_name " +
                           " from Inspection_Orders_Master sm inner join Inspection_Order_Detail sd on sm.key_pk = sd.key_fk " +
                           " left join inspection_category cat on cat.id = sd.cat_id " +
                           " left join USERS req on req.USERS = sd.req_by " +
                           " left join USERS appr on appr.USERS = sd.approved_by  " +
                           " where sm.inspection_id=" + id + "  order by sd.key_pk ;" +

                           " select sm.*,ac.title from Inspection_Invoice_Master sm inner join ac on ac.code=sm.acode where inspection_id=" + id + ";" +
                           " select sd.* from Inspection_Invoice_Detail sd  where inspection_id=" + id + ";" +
                           " select  * from inspection_invoice_labour  where insp_id=" + id + ";" +
                           " select sd.* from Inspection_Purchase_Invoice_Detail sd where inspection_id= " + id + ";" +
                           " select im.*,ac.title from Inspection_Purchase_Invoice_Detail_Party im inner join Inspection_Purchase_Invoice_Master sm on sm.key_pk=im.key_fk inner join ac on ac.code = im.acode where sm.inspection_id=" + id + ";" +

                          "  Select im.*,ac2.title as customer_title,gj.gjno as General_No,ac.title as Debit,ac1.title as Credit,gj.dramt as Amount " +
                          "  From inspection_master im  " +
                          "  inner join General_Journal gj on gj.insp_id=im.id " +
                          "  inner join ac ac2 on ac2.code=im.acode " +
                          "  inner join ac on ac.code = gj.d_acode " +
                          "  inner join ac ac1 on ac1.code = gj.c_acode " +
                          "  where gj.insp_id =" + id + ";" +
                           " select sd.* from Inspection_Purchase_Return_Invoice_Detail sd where inspection_id= " + id + ";" +
                           " select im.*,ac.title from Inspection_Purchase_Return_Invoice_Detail_Party im inner join Inspection_Purchase_Return_Invoice_Master sm on sm.key_pk=im.key_fk inner join ac on ac.code = im.acode where sm.inspection_id=" + id + ";";



            data = IList_GetDataSet(query);
            return data;
        }

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

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

            if (token.Trim() != app_key)
            {
                return "404";
            }

            String query = " select distinct chasis_no from inspection_master;"+
                           " select code,title from ac where type='Child' order by title;"+
                           " select distinct reg_no from inspection_master;"+
                           " select distinct contactno from inspection_master;";
            return IList_GetDataSet(query);
        }

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

            if (token.Trim() != app_key)
            {
                return "404";
            }

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

            }

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

            }

            if (json_Object["id"].ToString() != String.Empty)
            {
                where += " and im.vno=" + json_Object["id"].ToString().Trim() + " ";
            }
            
            if (json_Object["vn_num"].ToString() != String.Empty)
            {
                where += " and LTRIM(RTRIM(im.chasis_no))='" + json_Object["vn_num"].ToString().Trim() + "'";
            }

            if (json_Object["reg"].ToString() != String.Empty)
            {
                where += " and LTRIM(RTRIM(im.reg_no))='" + json_Object["reg"].ToString().Trim() + "'";
            }

            if (json_Object["phone"].ToString().Trim() != "")
            {
                where += " and LTRIM(RTRIM(im.contactno))='" + json_Object["phone"].ToString().Trim() + "'";
            }

            if (json_Object["status"].ToString() != String.Empty)
            {
                if (json_Object["status"].ToString() == "Paid")
                {
                    where += " and ( (isnull(im.balance,0))+(isnull(sale.Invoice_Amount,0))-(isnull(gj.cramt,0)) )=0";
                    having= " having( sum(isnull(im.balance,0))+sum(isnull(sale.Invoice_Amount,0))-sum(isnull(gj.cramt,0)) )!=0";

                }

                if (json_Object["status"].ToString() == "Unpaid")
                {
                    where += " and ((isnull(im.balance,0))+(isnull(sale.Invoice_Amount,0))-(isnull(gj.cramt,0)) )!=0";
                    having = " having ( sum(isnull(im.balance,0))+sum(isnull(sale.Invoice_Amount,0))-sum(isnull(gj.cramt,0)) )!=0";

                }

            }

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

            {
                query = " select im.chasis_no as [Vn_Number],vh.engno as [Engine_No],vh.regno as [Reg_No],vh.model as [Model],vh.Maker, " +
                        " count(*) as [No_Of_Inspection],sum(isnull(pu.pu_amount,0)) as Pu_Amount,sum(isnull(im.charges, 0)) as [Charges],sum(isnull(im.paid, 0)) as [Discount], " +
                        " sum(isnull(im.balance, 0)) as [Balance],sum(isnull(sale.Invoice_Amount, 0)) as Invoice,sum(isnull(gj.cramt, 0)) as Paid," +
                        " sum(isnull(im.balance,0))+sum(isnull(sale.Invoice_Amount,0))-sum(isnull(gj.cramt,0)) as [Due] " +
                        " from inspection_master im " +
                        " left join vehicle vh on vh.vin = im.chasis_no " +
                        " left join (select inspection_id,sum(ttlamtnet) as invoice_amount from Inspection_Invoice_Master group by inspection_id)sale on sale.inspection_id = im.id " +
                        " left join(select insp_id,sum(isnull(cramt, 0)) as cramt from General_Journal where insp_id is not null group by insp_id) gj on gj.insp_id = im.id " +
                        " left join (select inspection_id,sum(purchase_rate*qty) as pu_amount from Inspection_Invoice_Detail group by inspection_id)pu on pu.inspection_id=im.id" +
                        " left join ac on ac.code=im.acode " +
                        " where im.chasis_no is not null " +where+" "+
                        " group by im.chasis_no,vh.engno,vh.RegNo,vh.model,vh.maker;";

                query += " select im.id,im.vno as [Insp_No],im.ins_date as [Insp_Date],ac.Title,im.customer,im.chasis_no as [Vn_Number],vh.engno as [Engine_No],vh.regno as [Reg_No],vh.model as [Model],vh.Maker, " +
                         " count(*) as [No_Of_Inspection],sum(isnull(pu.pu_amount,0)) as Pu_Amount,sum(isnull(im.charges, 0)) as [Charges],sum(isnull(im.paid, 0)) as [Discount], " +
                         " sum(isnull(im.balance, 0)) as [Balance],sum(isnull(sale.Invoice_Amount, 0)) as Invoice,sum(isnull(gj.cramt, 0)) as Paid," +
                         " sum(isnull(im.balance,0))+sum(isnull(sale.Invoice_Amount,0))-sum(isnull(gj.cramt,0)) as [Due],im.contactno " +
                         " from inspection_master im " +
                         " left join vehicle vh on vh.vin = im.chasis_no " +
                         " left join (select inspection_id,sum(ttlamtnet) as invoice_amount from Inspection_Invoice_Master group by inspection_id)sale on sale.inspection_id = im.id " +
                         " left join(select insp_id,sum(isnull(cramt, 0)) as cramt from General_Journal where insp_id is not null group by insp_id) gj on gj.insp_id = im.id " +
                         " left join (select inspection_id,sum(purchase_rate*qty) as pu_amount from Inspection_Invoice_Detail group by inspection_id)pu on pu.inspection_id=im.id" +
                         " left join ac on ac.code=im.acode " +
                         " where im.chasis_no is not null " + where + " " +
                         " group by im.id,im.vno,im.ins_date,im.chasis_no,vh.engno,vh.RegNo,vh.model,vh.maker,ac.Title,im.customer,im.contactno " + having +
                         " order by im.ins_date ";
            }

          

            return IList_GetDataSet(query);
        }

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

            if (token.Trim() != app_key)
            {
                return "404";
            }

            String query = "  ";
            
           if(Convert.ToInt32(json_Object["insp_id"].ToString())>0) {
                query = "  Select im.*,ac2.title as customer_title,gj.gjno as General_No,ac.title as Debit,ac1.title as Credit,gj.dramt as Amount " +
                        "  From inspection_master im  " +
                        "  inner join General_Journal gj on gj.insp_id=im.id " +
                        " inner join ac ac2 on ac2.code=im.acode "+
                        "  inner join ac on ac.code = gj.d_acode " +
                        "  inner join ac ac1 on ac1.code = gj.c_acode " +
                        "  where gj.insp_id ="+Convert.ToInt32(json_Object["insp_id"].ToString());
               
            }
            if (json_Object["vn_number"].ToString().Trim()!=String.Empty)
            {
                query = "  Select im.*,ac2.title as customer_title,gj.gjno as General_No,ac.title as Debit,ac1.title as Credit,gj.dramt as Amount " +
                      "  From inspection_master im  " +
                      "  inner join General_Journal gj on gj.insp_id=im.id " +
                      " inner join ac ac2 on ac2.code=im.acode " +
                      "  inner join ac on ac.code = gj.d_acode " +
                      "  inner join ac ac1 on ac1.code = gj.c_acode " +
                      "  where im.chasis_no='" + Convert.ToString(json_Object["vn_number"].ToString().Trim())+"';";
            }

            return IList_GetDataSet(query);
        }

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

            if (token.Trim() != app_key)
            {
                return "404";
            }

            String query = "  ";
            String where = " ";
            String having = "";

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

            }

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

            }

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

            if (json_Object["vn_num"].ToString() != String.Empty)
            {
                where += " and LTRIM(RTRIM(im.chasis_no))='" + json_Object["vn_num"].ToString().Trim() + "'";
            }

            if (json_Object["phone"].ToString().Trim() != "")
            {
                where += " and LTRIM(RTRIM(im.contactno))='" + json_Object["phone"].ToString().Trim() + "'";
            }

            if (json_Object["status"].ToString() != String.Empty)
            {
                if (json_Object["status"].ToString() == "Paid")
                {
                    where += " and ( (isnull(im.balance,0))+(isnull(sale.Invoice_Amount,0))-(isnull(gj.cramt,0)) )=0";
                    having = " having( sum(isnull(im.balance,0))+sum(isnull(sale.Invoice_Amount,0))-sum(isnull(gj.cramt,0)) )!=0";

                }

                if (json_Object["status"].ToString() == "Unpaid")
                {
                    where += " and ((isnull(im.balance,0))+(isnull(sale.Invoice_Amount,0))-(isnull(gj.cramt,0)) )!=0";
                    having = " having ( sum(isnull(im.balance,0))+sum(isnull(sale.Invoice_Amount,0))-sum(isnull(gj.cramt,0)) )!=0";

                }

            }

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

            {


                query = " select im.id,im.vno as [Insp_No],im.ins_date as [Insp_Date],sale.date as [Sale_Date],ac.Title,im.customer,vh.vin as [Reg_No],vh.engno as [Engine_No],vh.regno as [Vn_Number],vh.model as [Model],vh.Maker, " +
                         " count(*) as [No_Of_Inspection],sum(isnull(pu.pu_amount,0)) as Pu_Amount,sum(isnull(im.charges, 0)) as [Charges],sum(isnull(im.paid, 0)) as [Discount], " +
                         " sum(isnull(im.balance, 0)) as [Balance],sum(isnull(sale.amtgrs, 0)) as Invoice,sum(isnull(gj.cramt, 0)) as Paid," +
                         " sum(isnull(im.balance,0))+sum(isnull(sale.amtgrs,0))-sum(isnull(gj.cramt,0)) as [Due] ,sum(isnull(sale.total_labour,0)) as Labour" +
                         " from inspection_master im  " +
                         " left join Inspection_Invoice_Master sale on im.id=sale.inspection_id " +
                         " left join vehicle vh on vh.vin = im.chasis_no " +
                         " left join(select insp_id,sum(isnull(cramt, 0)) as cramt from General_Journal where insp_id is not null group by insp_id) gj on gj.insp_id = im.id " +
                         " left join (select inspection_id,sum(pu_amount) as pu_amount from Inspection_Order_Detail group by inspection_id)pu on pu.inspection_id=im.id" +
                         " left join ac on ac.code=im.acode " +
                         " where im.chasis_no is not null " + where + " " +
                         " group by im.id,im.vno,im.ins_date,sale.date,vh.vin,vh.engno,vh.RegNo,vh.model,vh.maker,ac.Title,im.customer " + having +
                         " order by im.id ";
            }

            return IList_GetDataSet(query);
        }

        #endregion

        #region Vouchers

        public String Voucher_CashBook_Insert(String json)
        {

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

            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 UserId = json_object["UserId"].ToString();
            String type = "CB";
            String date = json_object["edate"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int vno = 0;
            int key = 0;
            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;

            String Order1 = " insert into cash_book(id,vno,edate,opening,debit,credit,closing,users,tally) values ";
            String Order2 = " (@id,@vno,@edate,@opening,@debit,@credit,@closing,@users,@tally); ";
            String OrderMaster = Order1 + Order2;

            String detail = " insert into cash_book_detail(pid,sno,acode,dscr,debit,credit,gjno) values "
                                        + " (@key,@sno,@acode,@dscr,@debit,@credit,@gjno)";

            try
            {


                using (con = new SqlConnection(cs))
                {

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


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

                        key = Convert.ToInt32(cm.ExecuteScalar()) + 1;
                    }
                    using (cm = new SqlCommand(" select top 1 vno from cash_book order by vno desc;", con, trans))
                    {

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

                        cm.Parameters.AddWithValue("id", key);
                        cm.Parameters.AddWithValue("vno",vno);
                        cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("opening", json_object["opening"].ToString());
                        cm.Parameters.AddWithValue("debit", json_object["debit"].ToString());
                        cm.Parameters.AddWithValue("credit", json_object["credit"].ToString());
                        cm.Parameters.AddWithValue("closing", json_object["closing"].ToString());
                        cm.Parameters.AddWithValue("users", json_object["UserId"].ToString());
                        cm.Parameters.AddWithValue("tally",Convert.ToInt32( json_object["tally"].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("acode", SqlDbType.VarChar);
                            cm.Parameters.Add("dscr", SqlDbType.VarChar);
                            cm.Parameters.Add("debit", SqlDbType.Decimal);
                            cm.Parameters.Add("credit", SqlDbType.Decimal);
                            cm.Parameters.Add("gjno", SqlDbType.Int);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["sno"].Value = Convert.ToInt32(row["sno"]);
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"]);
                                cm.Parameters["dscr"].Value = Convert.ToString(row["dscr"]);
                                cm.Parameters["debit"].Value = Convert.ToDecimal(row["debit"]);
                                cm.Parameters["credit"].Value = Convert.ToDecimal(row["credit"]);
                                cm.Parameters["gjno"].Value = Convert.ToInt32(row["gjno"])==0?(Object)DBNull.Value: Convert.ToInt32(row["gjno"]);
                                rowseffected += cm.ExecuteNonQuery();

                            }
                        }

                        if (rowseffected > 0)
                        {
                            {

                                using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data,users_id) values(" + vno + ",'" + 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 = vno;

                                }
                                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 Voucher_CashBook_Update(String json)
        {

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

            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 UserId = json_object["UserId"].ToString();
            String type = "CB";
            String date = json_object["edate"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int vno = Convert.ToInt32(json_object["vno"].ToString());
            int key = Convert.ToInt32(json_object["id"].ToString());
            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;

            String OrderMaster = " update cash_book set edate=@edate,opening=@opening,debit=@debit,"+
                 "credit=@credit,closing=@closing,tally=@tally where id=@id";
            
            String detail = " insert into cash_book_detail(pid,sno,acode,dscr,debit,credit,gjno) values "
                                        + " (@key,@sno,@acode,@dscr,@debit,@credit,@gjno)";

            String delete = " delete from cash_book_detail where pid="+key;

            String Select_Master = "select distinct  *  from cash_book  where id=" + key;

            String Select_Child = "select distinct  *  from cash_book_detail where pid=" + key;

            String JSONString = "";
            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";
                        JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                    }

                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {
                        
                        cm.Parameters.AddWithValue("id", key);
                        cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("opening", json_object["opening"].ToString());
                        cm.Parameters.AddWithValue("debit", json_object["debit"].ToString());
                        cm.Parameters.AddWithValue("credit", json_object["credit"].ToString());
                        cm.Parameters.AddWithValue("closing", json_object["closing"].ToString());
                        cm.Parameters.AddWithValue("tally", Convert.ToInt32(json_object["tally"].ToString()));
                        rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());

                    }
                    if (rowseffected > 0)
                    {
                        using (cm = new SqlCommand(delete, 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("acode", SqlDbType.VarChar);
                            cm.Parameters.Add("dscr", SqlDbType.VarChar);
                            cm.Parameters.Add("debit", SqlDbType.Decimal);
                            cm.Parameters.Add("credit", SqlDbType.Decimal);
                            cm.Parameters.Add("gjno", SqlDbType.Int);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["sno"].Value = Convert.ToInt32(row["sno"]);
                                cm.Parameters["acode"].Value = Convert.ToString(row["acode"]);
                                cm.Parameters["dscr"].Value = Convert.ToString(row["dscr"]);
                                cm.Parameters["debit"].Value = Convert.ToDecimal(row["debit"]);
                                cm.Parameters["credit"].Value = Convert.ToDecimal(row["credit"]);
                                cm.Parameters["gjno"].Value = Convert.ToInt32(row["gjno"]) == 0 ? (Object)DBNull.Value : Convert.ToInt32(row["gjno"]);
                                rowseffected += cm.ExecuteNonQuery();

                            }
                        }

                        if (rowseffected > 0)
                        {
                            {

                                using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data,users_id) values(" + vno + ",'" + 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 = vno;

                                }
                                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 Voucher_CashBook_Delete(String json)
        {

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

            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            String UserId = json_object["UserId"].ToString();
            String type = "CB";
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int vno = Convert.ToInt32(json_object["vno"].ToString());
            int key = Convert.ToInt32(json_object["id"].ToString());
            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;

            String Delete_Master = " delete from cash_book  where id=" + key+";";

            String Delete_Child = "  delete from cash_book_detail where pid=" + key + ";";

            String delete = Delete_Child + Delete_Master;

            String Select_Master = "select distinct  *  from cash_book  where id=" + key;

            String Select_Child = "select distinct  *  from cash_book_detail where pid=" + key;

            String JSONString = "";
            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";
                        JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                    }

                    using (cm = new SqlCommand(delete, con, trans))
                    {
                        rowseffected = cm.ExecuteNonQuery();
                    }

                    if (rowseffected > 0)
                    {
                        {

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

                                rows = cm.ExecuteNonQuery();

                            }

                            if (rows > 0)
                            {

                                trans.Commit();
                                IsInsert = vno;

                            }
                            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 Voucher_CashBook_Load(String token)
        {
           if (token != app_key)
            {
                return "404";
            }

            String data = "";
            String query = " select * from ac where type='Child' order by ac.title; " +
                           " select * from cash_book order by id; ";
                        

            data = IList_GetDataSet(query);
            return data;
        }

        public String Voucher_CashBook_ByEntry(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String token = json_Object["token"].ToString();
            if (token != app_key)
            {
                return "404";
            }
            int idno =Convert.ToInt32( json_Object["id"].ToString());
            String edate = Convert.ToString(json_Object["edate"].ToString());
            String data = "";
            String query = "";
            if (idno>0) {

                query = " select * from cash_book where id=" + idno + ";" +
                        " select cb.*,gj.gjno as invoice_no from  cash_book_detail cb " +
                        " inner join General_Journal gj on gj.key_pk= cb.gjno " +
                        " where pid=" + idno + " and cb.gjno is not null order by sno; " +
                        " select top 1 id from cash_book where id > " +idno;
            }
            else
            {
                query = " select * from cash_book where cast(edate as date)='" + edate + "';" +
                        " select cd.*,gj.gjno as invoice_no from cash_book cb inner join cash_book_detail cd on cd.pid=cb.id " +
                        " inner join General_Journal gj on gj.key_pk= cd.gjno  " +
                        " where cast(cb.edate as date)='" + edate + "' order by sno; ";

            }

            data = IList_GetDataSet(query);
            return data;
        }

        public String Voucher_CashBook_ByDate(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String token = json_Object["token"].ToString();
            if (token != app_key)
            {
                return "404";
            }
            string edate = Convert.ToString(json_Object["edate"].ToString());
           
            String data = "";

            String query = " select c.cash_in_hnd,gj.c_acode as code,gj.gjno,gj.key_pk,gj.prtclar,gj.dramt as debit,0 as credit from companysetup c " +
                           " inner join General_Journal gj on c.cash_in_hnd=gj.d_acode " +
                           " where cast(gj.date as date)='"+edate+ "' and gj.key_pk not in(select gjno from cash_book_detail where gjno is not null) union all" +

                           " select c.cash_in_hnd,gj.d_acode,gj.gjno,gj.key_pk,gj.prtclar,0,gj.cramt from companysetup c " +
                           " inner join General_Journal gj on c.cash_in_hnd=gj.c_acode " +
                           " where cast(gj.date as date)='"+edate+ "' and gj.key_pk not in(select gjno from cash_book_detail where gjno is not null) ";



           data = IList_GetTable(query);
            return data;
        }

        public String Voucher_CashBook_Opening(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String token = json_Object["token"].ToString();
            if (token != app_key)
            {
                return "404";
            }
            String data = "";
            String query = "select top 1 closing from cash_book order by id desc; ";


            data = IList_GetTable(query);
            return data;
        }

        public String Voucher_CashBook_Valid(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String token = json_Object["token"].ToString();
            if (token != app_key)
            {
                return "404";
            }
            String id = Convert.ToString(json_Object["id"].ToString());

            String data = "";
            data =IList_ExecuteScalerValue_String("select top 1 id  from cash_book where id>" + id);
            return data;
        }

        public String Voucher_CashBook_Print(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String token = json_Object["token"].ToString();
            if (token != app_key)
            {
                return "404";
            }
            int idno = Convert.ToInt32(json_Object["id"].ToString());
            String data = "";
            String query = "";

            query = "select cb.id,cb.vno,cb.edate,cb.opening,cb.shortage,cb.closing,cb.users,cb.tally,"+
                    "cd.*,ac.title,u.USERS_NAME,gj.gjno as invoice_no from cash_book cb " +
                    " inner join cash_book_detail cd on cb.id=cd.pid " +
                    " inner join ac on ac.code=cd.acode " +
                    " left join General_Journal gj on gj.key_pk=cd.gjno "+
                    " left join USERS u on u.USERS=cb.users " +
                    " where cb.id=" + idno + " order by sno; " +
                    " select * from companysetup;";
                  

            data = IList_GetDataSet(query);
            return data;
        }

        public String Voucher_CashBook_Report(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String token = json_Object["token"].ToString();
            if (token != app_key)
            {
                return "404";
            }
            int index = Convert.ToInt32(json_Object["index"].ToString());
            String from = Convert.ToString(json_Object["from"].ToString());
            String to = Convert.ToString(json_Object["to"].ToString());
            String data = "";
            String query = "";
            if (index==0) {

                query = " select id,vno,edate,opening,debit,credit,closing from cash_book where  tally=1 order by id";

                if (from != "")
                {
                    query = " select null as id,null as vno,'" + from + "' as edate,null as opening,null as debit,null as credit,(SUM(isnull(debit,0))-SUM(isnull(credit,0))) as Closing from cash_book " +
                            " where cast(edate as date)<'" + from + "' and tally=1 union all" +
                            " select id,vno,edate,opening,debit,credit,closing from cash_book where tally=1 and cast(edate as date)>='" + from + "'";

                }
                if (to != "")
                {
                    query = " select id,vno,edate,opening,debit,credit,closing from cash_book where  tally=1 and cast(edate as date)<='" + to + "'";

                }
                if (from != "" && to != "")
                {
                    query = " select null as id,null as vno,'" + from + "' as edate,null as opening,null as debit,null as credit,(SUM(isnull(debit,0))-SUM(isnull(credit,0))) as Closing from cash_book " +
                                " where cast(edate as date)<'" + from + "' and tally=1 union all" +
                                " select id,vno,edate,opening,debit,credit,closing from cash_book" +
                                " where  tally=1 and cast(edate as date)>='" + from + "' and cast(edate as date)<='" + to + "'";

                }
            }

            if (index==1)
            {
                query = " select cb.id,cb.vno,cb.edate,ac.title,cd.dscr,cd.debit,cd.credit,gj.gjno,cd.pid from cash_book cb " +
                        " inner join cash_book_detail cd on cd.pid=cb.id  inner join  ac on ac.code=cd.acode inner join General_Journal gj on gj.key_pk=cd.gjno " +
                        " where tally=1 ";


                if (from != "")
                {
                    query = "select null as id,null as vno,'"+from+"' as edate,null as title,'Balance B/F' as dscr,case when (SUM(isnull(debit,0))-SUM(isnull(credit,0)))>0 then (SUM(isnull(debit,0))-SUM(isnull(credit,0)))  else 0 end as debit, " +
                            " case when (SUM(isnull(debit,0))-SUM(isnull(credit,0)))<0 then (SUM(isnull(debit,0))-SUM(isnull(credit,0)))  else 0 end  as credit,null as gjno,null as id from cash_book where cast(edate as date)<'" + from+"' and tally=1 union all " +
                            " select cb.id,cb.vno,cb.edate,ac.title,cd.dscr,cd.debit,cd.credit,gj.gjno,cd.pid from cash_book cb "+
                            " inner join cash_book_detail cd on cd.pid=cb.id  inner join  ac on ac.code=cd.acode inner join General_Journal gj on gj.key_pk=cd.gjno " +
                            " where tally=1 and cast(cb.edate as date)>='" + from + "'";

                }
                if (to != "")
                {
                    query =  " select cb.id,cb.vno,cb.edate,ac.title,cd.dscr,cd.debit,cd.credit,gj.gjno,cd.pid from cash_book cb " +
                             " inner join cash_book_detail cd on cd.pid=cb.id  inner join  ac on ac.code=cd.acode inner join General_Journal gj on gj.key_pk=cd.gjno " +
                             " where tally=1 and cast(cb.edate as date)<='" + to + "'";

                }
                if (from != "" && to != "")
                {
                    query = "select null as id,null as vno,'"+from+"' as edate,null as title,'Balance B/F' as dscr,case when (SUM(isnull(debit,0))-SUM(isnull(credit,0)))>0 then (SUM(isnull(debit,0))-SUM(isnull(credit,0)))  else 0 end as debit, " +
                             " case when (SUM(isnull(debit,0))-SUM(isnull(credit,0)))<0 then (SUM(isnull(debit,0))-SUM(isnull(credit,0))) else 0 end  as credit,null as gjno,null as id from cash_book where cast(edate as date)<'" + from+"' and tally=1 union all " +
                             " select cb.id,cb.vno,cb.edate,ac.title,cd.dscr,cd.debit,cd.credit,gj.gjno,cd.pid from cash_book cb " +
                             " inner join cash_book_detail cd on cd.pid=cb.id  inner join  ac on ac.code=cd.acode inner join General_Journal gj on gj.key_pk=cd.gjno " +
                             " where tally=1 and cast(cb.edate as date)>='" + from + "' and cast(cb.edate as date)<='" + to + "'";

                }
            }
         
            data = IList_GetTable(query);
            return data;
        }

       
        #endregion

        #region partsbook

        public String Voucher_PartsBook_Load(String token)

        {
            if (token != app_key)
            {
                return "404";
            }

            String data = "";
            String query = " select * from partsbook order by id; ";


            data = IList_GetDataSet(query);
            return data;
        }

        public String Voucher_PartsBook_Insert(String json)
        {

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

            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 UserId = json_object["UserId"].ToString();
            String type = "PB";
            String date = json_object["edate"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int vno = 0;
            int key = 0;
            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;

            String Order1 = " insert into partsbook(vno,edate,users,tally) values ";
            String Order2 = " (@vno,@edate,@users,@tally);select SCOPE_IDENTITY() as code; ";
            String OrderMaster = Order1 + Order2;

            String detail = " insert into partsbook_detail(pid,sno,partno,descrp,qty,rate,v_name,v_inv,v_return,remarks) values "
                                        + " (@key,@sno,@partno,@dscr,@qty,@rate,@v_name,@v_inv,@v_return,@remarks)";

            try
            {


                using (con = new SqlConnection(cs))
                {

                    con.Open();
                    trans = con.BeginTransaction();
                    
                    using (cm = new SqlCommand(" select top 1 vno from partsbook order by vno desc;", con, trans))
                    {

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

                    using (cm = new SqlCommand(OrderMaster, con, trans))
                    {
                        cm.Parameters.AddWithValue("vno", vno);
                        cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("users", json_object["UserId"].ToString());
                        cm.Parameters.AddWithValue("tally", Convert.ToInt32(json_object["tally"].ToString()));
                        key = Convert.ToInt32(cm.ExecuteScalar());

                    }
                    if (key > 0)
                    {

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

                          
                            cm.Parameters.Add("key", SqlDbType.Int);
                            cm.Parameters.Add("sno", SqlDbType.Int);
                            cm.Parameters.Add("partno", SqlDbType.VarChar);
                            cm.Parameters.Add("dscr", SqlDbType.VarChar);
                            cm.Parameters.Add("qty", SqlDbType.Decimal);
                            cm.Parameters.Add("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("v_name", SqlDbType.VarChar);
                            cm.Parameters.Add("v_inv", SqlDbType.VarChar);
                            cm.Parameters.Add("v_return", SqlDbType.VarChar);
                            cm.Parameters.Add("remarks", SqlDbType.VarChar);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["sno"].Value = Convert.ToInt32(row["sno"]);
                                cm.Parameters["partno"].Value = Convert.ToString(row["partno"]);
                                cm.Parameters["dscr"].Value = Convert.ToString(row["dscr"]);
                                cm.Parameters["qty"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["rate"].Value = Convert.ToDecimal(row["rate"]);
                                cm.Parameters["v_name"].Value = row["v_name"].ToString();
                                cm.Parameters["v_inv"].Value = row["v_inv_no"].ToString();
                                cm.Parameters["v_return"].Value = row["v_sales_return"].ToString();
                                cm.Parameters["remarks"].Value = row["remarks"].ToString();
                                rowseffected += cm.ExecuteNonQuery();

                            }
                        }

                        if (rowseffected > 0)
                        {
                            {

                                using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data,users_id) values(" + vno + ",'" + 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 = vno;

                                }
                                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 Voucher_PartsBook_Update(String json)
        {

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

            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 UserId = json_object["UserId"].ToString();
            String type = "PB";
            String date = json_object["edate"].ToString();
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int vno = Convert.ToInt32(json_object["vno"].ToString());
            int key = Convert.ToInt32(json_object["id"].ToString());
            String response = "";

            DataSet dt = new DataSet();


            SqlTransaction trans = null;

            String OrderMaster = " update partsbook set edate=@edate,tally=@tally where id=@id";

            String detail = " insert into partsbook_detail(pid,sno,partno,descrp,qty,rate,v_name,v_inv,v_return,remarks) values "
                                       + " (@key,@sno,@partno,@dscr,@qty,@rate,@v_name,@v_inv,@v_return,@remarks)";


            String delete = " delete from partsbook_detail where pid=" + key;

            String Select_Master = "select distinct  *  from partsbook  where id=" + key;

            String Select_Child = "select distinct  *  from partsbook_detail where pid=" + key;

            String JSONString = "";
            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";
                        JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                    }

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

                        cm.Parameters.AddWithValue("id", key);
                        cm.Parameters.AddWithValue("edate", json_object["edate"].ToString());
                        cm.Parameters.AddWithValue("tally", Convert.ToInt32(json_object["tally"].ToString()));
                        rowseffected = Convert.ToInt32(cm.ExecuteNonQuery());

                    }
                    if (rowseffected > 0)
                    {
                        using (cm = new SqlCommand(delete, 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("partno", SqlDbType.VarChar);
                            cm.Parameters.Add("dscr", SqlDbType.VarChar);
                            cm.Parameters.Add("qty", SqlDbType.Decimal);
                            cm.Parameters.Add("rate", SqlDbType.Decimal);
                            cm.Parameters.Add("v_name", SqlDbType.VarChar);
                            cm.Parameters.Add("v_inv", SqlDbType.VarChar);
                            cm.Parameters.Add("v_return", SqlDbType.VarChar);
                            cm.Parameters.Add("remarks", SqlDbType.VarChar);

                            foreach (DataRow row in table.Rows)
                            {

                                cm.Parameters["key"].Value = key;
                                cm.Parameters["sno"].Value = Convert.ToInt32(row["sno"]);
                                cm.Parameters["partno"].Value = Convert.ToString(row["partno"]);
                                cm.Parameters["dscr"].Value = Convert.ToString(row["dscr"]);
                                cm.Parameters["qty"].Value = Convert.ToDecimal(row["qty"]);
                                cm.Parameters["rate"].Value = Convert.ToDecimal(row["rate"]);
                                cm.Parameters["v_name"].Value = row["v_name"].ToString();
                                cm.Parameters["v_inv"].Value = row["v_inv_no"].ToString();
                                cm.Parameters["v_return"].Value = row["v_sales_return"].ToString();
                                cm.Parameters["remarks"].Value = row["remarks"].ToString();
                                rowseffected += cm.ExecuteNonQuery();

                            }
                        }

                        if (rowseffected > 0)
                        {
                            {

                                using (cm = new SqlCommand("insert into Log(Entry,type,edate,s_user,l_user,remarks,data,users_id) values(" + vno + ",'" + 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 = vno;

                                }
                                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 Voucher_PartsBook_Delete(String json)
        {

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

            String system = json_object["User"].ToString();
            String User = json_object["System"].ToString();
            String UserId = json_object["UserId"].ToString();
            String type = "PB";
            int IsInsert = 0;
            int rowseffected = 0;
            int rows = 0;
            int vno = Convert.ToInt32(json_object["vno"].ToString());
            int key = Convert.ToInt32(json_object["id"].ToString());
            String response = "";

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

            String Delete_Master = " delete from partsbook  where id=" + key + ";";

            String Delete_Child = "  delete from partsbook_detail where pid=" + key + ";";

            String delete = Delete_Child + Delete_Master;

            String Select_Master = "select distinct  *  from partsbook  where id=" + key;

            String Select_Child = "select distinct  *  from partsbook_detail where pid=" + key;

            String JSONString = "";
            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";
                        JSONString = JsonConvert.SerializeObject(dt, Formatting.Indented);

                    }

                    using (cm = new SqlCommand(delete, con, trans))
                    {
                        rowseffected = cm.ExecuteNonQuery();
                    }

                    if (rowseffected > 0)
                    {
                        {

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

                                rows = cm.ExecuteNonQuery();

                            }

                            if (rows > 0)
                            {

                                trans.Commit();
                                IsInsert = vno;

                            }
                            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 Voucher_PartsBook_ByEntry(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String token = json_Object["token"].ToString();
            if (token != app_key)
            {
                return "404";
            }
            int idno =0;
            string edate = "";
            String data = "";
            String query = "";
            String where = "";

            if (json_Object["id"]!=null)
            {
              idno = Convert.ToInt32(json_Object["id"].ToString());
                if (idno>0) {
                    where += " and p.id =" + idno + "";
                }
            }
            if (json_Object["edate"]!=null)
            {
                edate = json_Object["edate"].ToString().Trim();
                if (edate!="") {
                    where += " and cast(p.edate as Date) ='" + edate + "'";
                }
            }
            query = " select * from partsbook p where p.id is not null " + where + ";" +
                    " select pb.* from partsbook_detail pb inner join partsbook p on p.id=pb.pid "+
                    " where p.id is not null " + where + ";";

            data = IList_GetDataSet(query);
            return data;
        }

        public String Voucher_PartsBook_Print(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String token = json_Object["token"].ToString();
            if (token != app_key)
            {
                return "404";
            }
            int idno = Convert.ToInt32(json_Object["id"].ToString());
            String data = "";
            String query = "";

            query = " select * from partsbook pb "+
                    " inner join partsbook_detail pbd on pb.id = pbd.pid" +
                    " where pb.id=" + idno + " order by pbd.pid ; " +
                    " select * from companysetup;";


            data = IList_GetDataSet(query);
            return data;
        }

        public String Voucher_PartsBook_Report(String json)
        {
            JObject json_Object = JObject.Parse(json);
            String token = json_Object["token"].ToString();
            if (token != app_key)
            {
                return "404";
            }
            String data = "";
            String query = "";

            query = " select * from partsbook pb " +
                    " inner join partsbook_detail pbd on pb.id = pbd.pid" +
                    " where cast(edate as Date)>='"+json_Object["from"].ToString()+"'"+
                    " and cast(edate as Date)<='" + json_Object["to"].ToString() + "'" +
                    " order by pbd.pid ; " +
                    " select * from companysetup;";


            data = IList_GetDataSet(query);
            return data;
        }

        #endregion
    }
}