
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Windows.Forms;
using TinyHeels.App_Code;

namespace TinyHeels
{
    public partial class controlSales : UserControl
    {
        DataTable orders = new DataTable();
        //-------------------------
        private static controlSales _instance;
        public static controlSales Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new controlSales();
                }
                return _instance;
            }
        }
        public controlSales()
        {
            InitializeComponent();
            loadCategory();
        }
        protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
        {
            try
            {
                KeyEventArgs e = new KeyEventArgs(keyData);
                if (e.Control && e.KeyCode == Keys.Enter)
                {
                    txtAmountReceived.Text = "";
                    txtAmountReceived.Select();
                }
               
                //else if (msg.WParam.ToInt32() == (int)Keys.F5)
                //{
                //    button2.Select();
                //}
                //else if (e.Control && e.KeyCode == Keys.C)
                //{
                //    txtCodePlace.Select();
                //    txtCodePlace.Text = "";
                //}
                //else if (e.Control && msg.WParam.ToInt32() == (int)Keys.Enter)
                //{
                //    txtAmountReceived.Text = lblGrandAmount.Text;
                //    txtAmountReceived.Select();
                //}
                //else if (e.Control && e.KeyCode == Keys.S)
                //{
                //    if (autoSwitch.Value == true)
                //    {
                //        autoSwitch.Value = false;
                //    }
                //    else
                //    {
                //        autoSwitch.Value = true;
                //    }
                //}
                //else if (e.Control && e.KeyCode == Keys.B)
                //{
                //    if (chkPrint.Value == true)
                //    {
                //        chkPrint.Value = false;
                //    }
                //    else
                //    {
                //        chkPrint.Value = true;
                //    }
                //}
                //else if (e.Control && e.KeyCode == Keys.R)
                //{
                //    if (chkSale.Value == true)
                //    {
                //        chkSale.Value = false;
                //    }
                //    else
                //    {
                //        chkSale.Value = true;
                //    }

                //    if (chkSale.Value == true)
                //    {
                //        lblSaleType.Text = "Retail";
                //        resetData();
                //    }
                //    else
                //    {
                //        lblSaleType.Text = "Wholesale";
                //        resetData();
                //    }
                //}
            }
            catch (Exception ex)
            {

            }

            return false;
        }
        private void controlSales_Load(object sender, EventArgs e)
        {
            cboPaymentType.SelectedIndex = 0;
            orders.Columns.AddRange(new DataColumn[9] { new DataColumn("Seriel"), new DataColumn("Code"), new DataColumn("Description"), new DataColumn("Price"), new DataColumn("Discount"), new DataColumn("Net Price"), new DataColumn("Quantity"), new DataColumn("Total"), new DataColumn("S") });
        }
        byte[] imgbytes;
        public void loadCategory()
        {
            try
            {
                flowLayoutPanel1.Controls.Clear();
                List<PictureBox> pictureBoxList = new List<PictureBox>();
                Category cat = new Category();
                DataTable dt = cat.getAllCategories();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows.Count > 21)
                    {
                        PictureBox picture = new PictureBox
                        {
                            Name = dt.Rows[i][0].ToString(),
                            Size = new Size(108, 70),
                            BorderStyle = BorderStyle.FixedSingle,
                            SizeMode = PictureBoxSizeMode.StretchImage
                        };

                        this.imgbytes = (Byte[])dt.Rows[i][2];
                        Image img1 = byteArrayToImage(this.imgbytes);
                        picture.Image = img1;
                        pictureBoxList.Add(picture);

                        picture.MouseLeave += new System.EventHandler(this.mouseLeave);
                        picture.MouseEnter += new System.EventHandler(this.mouseEnter);
                        picture.Click += new System.EventHandler(this.imgClicks);
                    }
                    else
                    {
                        PictureBox picture = new PictureBox
                        {
                            Name = dt.Rows[i][0].ToString(),
                            Size = new Size(145, 95),
                            BorderStyle = BorderStyle.FixedSingle,
                            SizeMode = PictureBoxSizeMode.StretchImage
                        };

                        this.imgbytes = (Byte[])dt.Rows[i][2];
                        Image img1 = byteArrayToImage(this.imgbytes);
                        picture.Image = img1;
                        pictureBoxList.Add(picture);

                        picture.MouseLeave += new System.EventHandler(this.mouseLeave);
                        picture.MouseEnter += new System.EventHandler(this.mouseEnter);
                        picture.Click += new System.EventHandler(this.imgClicks);
                    }
                }

                foreach (PictureBox p in pictureBoxList)
                {
                    flowLayoutPanel1.Controls.Add(p);
                }

            }
            catch (Exception ex)
            {

                throw new Exception("Sorry Could Not Load Category Data");
            }
        }
        public void imgClicks(object sender, EventArgs e)
        {
            try
            {
                //message
                PictureBox btn = (PictureBox)sender;
                cat = btn.Name;
                loadItems();
            }
            catch (Exception ex)
            {
                //Test
                MessageBox.Show(ex.ToString());
            }
        }
        //----------------------------
        string cat;
        string article;
        string size;
        string color;
        //----------------------------
        public void loadItems()
        {
            try
            {
                int cat = Int32.Parse(this.cat);
                cboArticle.Items.Clear();
                Products prd = new Products();
                prd.category = cat;
                DataTable dt = prd.filterItems();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    cboArticle.Items.Add(dt.Rows[i][0].ToString());
                }
                cboArticle.SelectedIndex=0;
            }
            catch (Exception ex)
            {
            }
        }
        public void mouseLeave(object sender, EventArgs e)
        {
            PictureBox currentBtn = (PictureBox)sender;
            currentBtn.BorderStyle = BorderStyle.FixedSingle;
            currentBtn.Cursor = Cursors.Default;
        }
        public void mouseEnter(object sender, EventArgs e)
        {
            PictureBox currentBtn = (PictureBox)sender;
            currentBtn.SizeMode = PictureBoxSizeMode.Zoom;
            currentBtn.BorderStyle = BorderStyle.Fixed3D;
            currentBtn.Cursor = Cursors.Hand;
        }
        //A function to convert byte array to image
        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }

        private void panel3_Paint(object sender, PaintEventArgs e)
        {

        }

        private void cboArticle_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.article = cboArticle.Text;
                loadSizes();
            }
            catch (Exception ex)
            {

            }
        }
        public void loadSizes()
        {
            try
            {
                Products prd = new Products();
                prd.article = this.article;
                prd.category =Int32.Parse(this.cat);
                cboSize.Items.Clear();
                DataTable dt = prd.filterItemsForSizes();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    cboSize.Items.Add(dt.Rows[i][0].ToString());
                }
                cboSize.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void cboSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.size = cboSize.Text;
                loadColors();
            }
            catch (Exception ex)
            {

            }
        }
        public void loadColors()
        {
            try
            {
                Products prd = new Products();
                prd.article = this.article;
                prd.size = this.size;
                prd.category = Int32.Parse(this.cat);
                cboColor.Items.Clear();
                DataTable dt = prd.filterItemsForColors();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    cboColor.Items.Add(dt.Rows[i][0].ToString());
                }
                cboColor.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void cboColor_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.color = cboColor.Text;
                loadPrice();
            }
            catch (Exception ex)
            {

            }
        }
        double price = 0;
        double discount = 0;
        double newAmount = 0;
        double quantity = 0;
        double totalAmount;

        public void basicCalculation()
        {
            try
            {
                price = double.Parse(txtPrice.Text);
                discount = double.Parse(txtDiscount.Text);
                newAmount = price - discount;
                quantity = double.Parse(txtQuantity.Text);
                totalAmount = quantity * price;


                txtNewAmount.Text = newAmount.ToString();
                txtTotalAmount.Text = totalAmount.ToString();
            }
            catch (Exception ex)
            {

            }
        }
        public void loadPrice()
        {
            try
            {
                Products prd = new Products();
                prd.article = this.article;
                prd.size = this.size;
                prd.color = this.color;
                prd.category = Int32.Parse(this.cat);
                cboColor.Items.Clear();
                DataTable dt = prd.filterItemsForPrices();
                txtPrice.Text = dt.Rows[0][0].ToString();
                txtCode.Text = dt.Rows[0][1].ToString();
            }
            catch (Exception ex)
            {
            }
        }

        private void txtPrice_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                basicCalculation();
            }
            catch (Exception ex)
            {

            }
        }
        int count = 1;
        private void txtDiscount_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                basicCalculation();
            }
            catch (Exception ex)
            {
            }
        }

        private void txtQuantity_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                basicCalculation();
            }
            catch (Exception ex)
            {

            }
        }

        private void txtPrice_TextChanged(object sender, EventArgs e)
        {
            try
            {
                basicCalculation();
            }
            catch (Exception ex)
            {

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                string code = (string.IsNullOrWhiteSpace(txtCode.Text)) ? "-" : txtCode.Text;
                if(code.Length<=1)
                {
                    ErrorBox error = new ErrorBox("Sorry No Code Found");
                    error.ShowDialog();
                }
                else
                {
                    string article = cboArticle.Text;
                    string size = cboSize.Text;
                    string color = cboColor.Text;
                    string description = article + ", " + size + ", " + color;
                    totalNetAmount += totalAmount;
                    totalDiscount += discount * quantity;
                    orders.Rows.Add(count, code, description, price.ToString(), discount.ToString(),newAmount.ToString(),quantity.ToString(),totalAmount.ToString() , "N");
                    count++;
                    bindGrid();
                    

                    calculateFinalAmount();

                    resetData();
                }
            }
            catch (Exception ex)
            {

            }
        }
        public void resetData()
        {
            txtCode.Text = "";
            txtDiscount.Text = "0";
            cboArticle.Items.Clear();
            cboArticle.Text = "";
            txtNewAmount.Text = "0";
            cboSize.Items.Clear();
            cboSize.Text = "";
            txtQuantity.Text = "1";
            cboColor.Items.Clear();
            cboColor.Text = "";
            txtTotalAmount.Text = "";
            txtPrice.Text = "";

            totalAmount = 0;
            discount = 0;
            price=0;
            quantity = 0;

            status = "Fresh Sales Mode";

        }
        public void resetFinal()
        {
            totalNetAmount = 0;
            totalDiscount = 0;
            grandTotal = 0;
            amountReceived = 0;
            cashBack = 0;

            txtTotalNetAmount.Text = "";
            txtTotalDiscount.Text = "";
            lblGrandAmount.Text = "000000.00";
            txtNote.Text = "-";

            productGrid.DataSource = null;
            orders.Rows.Clear();

            txtAmountReceived.Text = "0";
        }
        double totalNetAmount = 0;
        double totalDiscount = 0;
        double grandTotal = 0;
        double amountReceived = 0;
        double cashBack = 0;
        public void calculateFinalAmount()
        {
            try
            {
                grandTotal = totalNetAmount-totalDiscount;
                txtTotalNetAmount.Text = totalNetAmount.ToString();
                txtTotalDiscount.Text = totalDiscount.ToString();
                lblGrandAmount.Text = grandTotal.ToString();

                amountReceived = double.Parse(txtAmountReceived.Text);
                cashBack = amountReceived - grandTotal;
                if(cashBack<0)
                {
                    lblCashback.Text = "Cash Receivable";
                }
                else
                {
                    lblCashback.Text = "Cash Payable";
                }
                txtCash.Text = cashBack.ToString();
            }
            catch (Exception ex)
            {

            }
        }
        public void bindGrid()
        {
            try
            {
                productGrid.DataSource = orders;
                productGrid.Columns[0].Width = 45;
                productGrid.Columns[1].Width = 120;
                productGrid.Columns[2].Width = 250;
                productGrid.Columns[3].Width = 50;
                productGrid.Columns[4].Width = 60;
                productGrid.Columns[5].Width = 75;
                productGrid.Columns[6].Width = 50;
                productGrid.Columns[7].Width = 70;
            }
            catch (Exception ex)
            {
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                int num = Convert.ToInt32(productGrid.SelectedRows[0].Cells[0].Value.ToString());
                int count = 0;
                count = orders.Rows.Count;
                for (int i = 0; i < orders.Rows.Count; i++)
                {
                    DataRow dr = orders.Rows[i];
                    if (Convert.ToInt32(dr["Seriel"].ToString()) == num)
                    {
                        if (dr["S"].ToString() == "N")
                        {
                            totalNetAmount -= float.Parse(dr["Total"].ToString());
                            totalDiscount -= float.Parse(dr["Discount"].ToString())* float.Parse(dr["Quantity"].ToString());
                            calculateFinalAmount();
                            dr.Delete();
                        }
                        else
                        {
                            ErrorBox error = new ErrorBox("Sorry Can Not Delete Ordered Items\nUse Return.");
                            error.ShowDialog();
                        }
                    }
                }
                bindGrid();
                if (count == 1)
                    resetData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                //ErrorBox error = new ErrorBox("Error Occured in Deletion");
                //error.ShowDialog();
            }
        }

        private void txtAmountReceived_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                calculateFinalAmount();
                if (e.KeyCode == Keys.Down)
                {
                    button5.Select();
                }
            }
            catch (Exception ex)
            {

            }
        }
        string bcode = "";
        public string generateCode()
        {
            try
            {
                bcode = "";
                DateTime dt = new DateTime(DateTime.Now.Year, 1, 1, 0, 0, 0, 0, DateTimeKind.Local);
                DateTime dtNow = DateTime.Now;
                TimeSpan result = dtNow.Subtract(dt);
                int seconds = Convert.ToInt32(result.TotalSeconds);
                bcode += seconds.ToString();
                int len = bcode.Length;
                if (len < 8)
                {
                    for (int i = len; i < 8; i++)
                    {
                        bcode = "0" + bcode;
                    }
                }
                bcode = DateTime.Now.ToString("yy") + "ORD" + bcode;
                return bcode;
            }
            catch (Exception ex)
            {

                throw new Exception("Sorry Could Not Generate Code");
            }
        }
        PrintDocument pdoc = null;
        string status ="Fresh Sales Mode";
        string orderCode;
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                string paymentType = cboPaymentType.Text;
                if (paymentType.Equals("Cash"))
                {
                    if (this.status.Equals("Fresh Sales Mode"))
                    { 
                        if (amountReceived >= grandTotal)
                        {
                            Orders order = new Orders();
                            this.orderCode = generateCode();
                            order.orderCode = this.orderCode;
                            order.date = DateTime.Parse(DateTime.Now.ToShortDateString());
                            order.time = DateTime.Now.ToShortTimeString();
                            order.amount = totalNetAmount;
                            order.discount = totalDiscount;
                            order.totalAmount = grandTotal;
                            order.received = amountReceived;
                            order.change = cashBack;
                            order.salesMan = Common.adminId;
                            order.paymentType = paymentType;
                            order.note = (string.IsNullOrWhiteSpace(txtNote.Text)) ? "-" : txtNote.Text;
                            order.newItem();


                            for (int i = 0; i < orders.Rows.Count; i++)
                            {
                                OrderDetail d = new OrderDetail();
                                d.orderCode = this.orderCode;
                                d.productCode = orders.Rows[i][1].ToString();
                                d.productDescription = orders.Rows[i][2].ToString();
                                d.price = double.Parse(orders.Rows[i][3].ToString());
                                d.discount = double.Parse(orders.Rows[i][4].ToString());
                                d.extendedPrice = double.Parse(orders.Rows[i][5].ToString());
                                d.quantity = double.Parse(orders.Rows[i][6].ToString());
                                d.netAmount = double.Parse(orders.Rows[i][7].ToString());
                                d.itemStatus = "S";
                                d.insertDetail();
                            }

                            //---------------------------- update ledger
                            Ledger led = new Ledger();
                            led.Date = DateTime.Parse(DateTime.Now.ToShortDateString());
                            led.Note = "Sale";
                            led.Particualrs = "Credit";
                            led.Credit = grandTotal;
                            led.insertCredit();


                            resetData();
                            resetFinal();


                            //-------------------------------------------------------  Custom Code
                            PrintDialog pd = new PrintDialog();
                            pdoc = new PrintDocument();
                            PrinterSettings ps = new PrinterSettings();
                            Font font = new Font("calibri", 15);


                            PaperSize psize = new PaperSize("Custom", 100, 2000);
                            //ps.DefaultPageSettings.PaperSize = psize;



                            pd.Document = pdoc;
                            pd.Document.DefaultPageSettings.PaperSize = psize;
                            //pdoc.DefaultPageSettings.PaperSize.Height =320;
                            pdoc.DefaultPageSettings.PaperSize.Height = 820;

                            pdoc.DefaultPageSettings.PaperSize.Width = 520;
                            //-- check of the order has kitchen print

                            pdoc.PrinterSettings.PrinterName = "POS";
                            pdoc.PrintPage += new PrintPageEventHandler(kitchen_PrintPage);
                            pdoc.Print();
                            pdoc.PrintPage -= new PrintPageEventHandler(kitchen_PrintPage);
                        }
                        else
                        {
                            ErrorBox error = new ErrorBox("Please do complete payment wiht Cash");
                            error.ShowDialog();
                        }
                    }
                    else   // Exchange Mode
                    {
                        if (amountReceived >= grandTotal)
                        {
                            Orders order = new Orders();
                            order.orderCode = this.orderCode;
                            order.date = DateTime.Parse(DateTime.Now.ToShortDateString());
                            order.time = DateTime.Now.ToShortTimeString();
                            order.amount = totalNetAmount;
                            order.discount = totalDiscount;
                            order.totalAmount = grandTotal;
                            order.received = amountReceived;
                            order.change = cashBack;
                            order.salesMan = Common.adminId;
                            order.paymentType = paymentType;
                            order.note = (string.IsNullOrWhiteSpace(txtNote.Text)) ? "-" : txtNote.Text;
                            order.updateForExchange();

                            OrderDetail ddd = new OrderDetail();
                            ddd.orderCode = this.orderCode;
                            ddd.cancelItems();

                            for (int i = 0; i < orders.Rows.Count; i++)
                            {
                                OrderDetail d = new OrderDetail();
                                d.orderCode = this.orderCode;
                                d.productCode = orders.Rows[i][1].ToString();
                                d.productDescription = orders.Rows[i][2].ToString();
                                d.price = double.Parse(orders.Rows[i][3].ToString());
                                d.discount = double.Parse(orders.Rows[i][4].ToString());
                                d.extendedPrice = double.Parse(orders.Rows[i][5].ToString());
                                d.quantity = double.Parse(orders.Rows[i][6].ToString());
                                d.netAmount = double.Parse(orders.Rows[i][7].ToString());
                                string st = orders.Rows[i]["S"].ToString();
                                if(st.Equals("N"))
                                    d.itemStatus = "S";
                                else
                                    d.itemStatus= orders.Rows[i]["S"].ToString(); 
                                d.insertDetail();
                            }

                            if (double.Parse(txtCash.Text) < 0)
                            {
                                //---------------------------- update ledger
                                Ledger led = new Ledger();
                                led.Date = DateTime.Parse(DateTime.Now.ToShortDateString());
                                led.Note = "Credit VIA Exchange";
                                led.Particualrs = "Credit";

                                led.Credit = Math.Abs(double.Parse(txtCash.Text));
                                led.insertCredit();
                            }
                            else
                            {
                                //---------------------------- update ledger
                                Ledger led = new Ledger();
                                led.Date = DateTime.Parse(DateTime.Now.ToShortDateString());
                                led.Note = "Debit VIA Exchange";
                                led.Particualrs = "Debit";

                                led.Debit = Math.Abs(double.Parse(txtCash.Text));
                                led.insertDebit();
                            }
                            resetData();
                            resetFinal();

                            //-------------------------------------------------------  Custom Code
                            PrintDialog pd = new PrintDialog();
                            pdoc = new PrintDocument();
                            PrinterSettings ps = new PrinterSettings();
                            Font font = new Font("calibri", 15);


                            PaperSize psize = new PaperSize("Custom", 100, 2000);
                            //ps.DefaultPageSettings.PaperSize = psize;



                            pd.Document = pdoc;
                            pd.Document.DefaultPageSettings.PaperSize = psize;
                            //pdoc.DefaultPageSettings.PaperSize.Height =320;
                            pdoc.DefaultPageSettings.PaperSize.Height = 820;

                            pdoc.DefaultPageSettings.PaperSize.Width = 520;
                            //-- check of the order has kitchen print

                            pdoc.PrinterSettings.PrinterName = "POS";
                            pdoc.PrintPage += new PrintPageEventHandler(kitchen_PrintPage);
                            pdoc.Print();
                            pdoc.PrintPage -= new PrintPageEventHandler(kitchen_PrintPage);
                        }
                        else
                        {
                            ErrorBox error = new ErrorBox("Please do complete payment wiht Cash");
                            error.ShowDialog();
                        }
                    }
                }
                else
                {
                    //credit
                    ErrorBox error = new ErrorBox("Sorry cann't pay with credit");
                    error.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        void kitchen_PrintPage(object sender, PrintPageEventArgs e)
        {
            try
            {
                string id = this.orderCode;
                Orders ord = new Orders();
                ord.orderCode = id;
                DataTable dt = ord.getOrderById();
              
                float amount = float.Parse(dt.Rows[0]["amount"].ToString());
                float grandTotal = float.Parse(dt.Rows[0]["totalAmount"].ToString());
                string emp = dt.Rows[0]["salesMan"].ToString();
                Employee ez = new Employee();
                ez.EmpId = emp;
                string empName = ez.getEmployeeName();
                string ordTime = dt.Rows[0]["time"].ToString();
                string ordDate = dt.Rows[0]["date"].ToString();
                string discount = (string.IsNullOrEmpty(dt.Rows[0]["discount"].ToString())) ? "0" : dt.Rows[0]["discount"].ToString();
                string amountReceived = (string.IsNullOrEmpty(dt.Rows[0]["received"].ToString())) ? "0" : dt.Rows[0]["received"].ToString();
                string change = (string.IsNullOrEmpty(dt.Rows[0]["change"].ToString())) ? "0" : dt.Rows[0]["change"].ToString();

                string paymentType = dt.Rows[0]["paymentType"].ToString();
                string note = dt.Rows[0]["note"].ToString();
                //-----------
                Graphics graphics = e.Graphics;
                Font font = new Font("calibri", 10);
                float fontHeight = font.GetHeight();
                String underLine = "-------------------------------------------------------------";
                int startX = 0;
                int startY = 20;
                int Offset = 10;

                Offset += 0;


                    //-------------
                    //Offset = Offset + 30;
                    System.Drawing.Image imgx;
                    //Create the image object
                    Image ximgx = pictureBox4.Image;
                    imgx = ximgx;
                    //graphics.DrawImage(imgx, startX + 5, Offset);
                    graphics.DrawImage(imgx, 0, Offset, 280, 80);

                    Offset = Offset + 80;
                    var format = new StringFormat() { Alignment = StringAlignment.Center };
                    var rect = new RectangleF(startX, startY + Offset, 270, 30);

                    e.Graphics.DrawString("Tailors and Garments", new Font("Ubuntu", 18), new SolidBrush(Color.Black), rect, format);
                    Offset = Offset + 40;
                    rect = new RectangleF(startX, startY + Offset, 270, 30);
                    e.Graphics.DrawString("Shop No: 4 Alamdar Road, Near Jamia Imam Sadiq Quetta.", new Font("calibri", 8), new SolidBrush(Color.Black), rect, format);
                    Offset = Offset + 26;
                    rect = new RectangleF(startX, startY + Offset, 270, 30);
                    e.Graphics.DrawString("Ph: 081-2664782 Cell: 0300-3852513", new Font("calibri", 8), new SolidBrush(Color.Black), rect, format);
                    Offset = Offset + 12;
                    graphics.DrawString(underLine, new Font("calibri", 10), new SolidBrush(Color.Black), 0, startY + Offset);

                    Offset = Offset + 15;
                    rect = new RectangleF(startX, startY + Offset, 270, 30);
                    e.Graphics.DrawString("CUSTOMER RECEIPT", new Font("Ubuntu", 10), new SolidBrush(Color.Black), rect, format);

                   
                Offset = Offset + 15;
                graphics.DrawString("Cashier:", new Font("Calibri", 10), new SolidBrush(Color.Black), startX, startY + Offset);
                graphics.DrawString(empName, new Font("Calibri", 10), new SolidBrush(Color.Black), startX + 80, startY + Offset);

                Offset = Offset + 15;
                graphics.DrawString("Date:", new Font("Calibri", 10), new SolidBrush(Color.Black), startX, startY + Offset);
                graphics.DrawString(DateTime.Parse(ordDate).ToString("d, MMMM, yyyy"), new Font("Calibri", 10), new SolidBrush(Color.Black), startX + 80, startY + Offset);

                Offset = Offset + 15;
                graphics.DrawString("Time:", new Font("Calibri", 10), new SolidBrush(Color.Black), startX, startY + Offset);
                graphics.DrawString(ordTime, new Font("Calibri", 10), new SolidBrush(Color.Black), startX + 80, startY + Offset);

                Offset = Offset + 15;
                graphics.DrawString(underLine, new Font("calibri", 10), new SolidBrush(Color.Black), 0, startY + Offset);

                //------------------------
                Offset = Offset + 15;
                graphics.DrawString("Item", new Font("Georgia", 10), new SolidBrush(Color.Black), startX, startY + Offset);
                graphics.DrawString("Qty", new Font("Georgia", 10), new SolidBrush(Color.Black), startX + 160, startY + Offset);
                graphics.DrawString("Amount", new Font("Georgia", 10), new SolidBrush(Color.Black), startX + 210, startY + Offset);
                //-------------
                Offset = Offset + 15;
                graphics.DrawString(underLine, new Font("calibri", 10), new SolidBrush(Color.Black), 0, startY + Offset);
                Offset = Offset + 15;

                //----------------------
                OrderDetail items = new OrderDetail();
                items.orderCode = id;

                DataTable dtitems = items.getOrderByOrderId();
                for (int i = 0; i < dtitems.Rows.Count; i++)
                {
                    string status = dtitems.Rows[i]["itemStatus"].ToString();
                    string pname = dtitems.Rows[i]["productDescription"].ToString();
                    string pquantity = dtitems.Rows[i]["quantity"].ToString();
                    string extendedPrice = dtitems.Rows[i]["extendedPrice"].ToString();
                    string totalAmount = dtitems.Rows[i]["netAmount"].ToString();
                    //type-------------------------------------------------------------------------------------
                    if (status.Equals("N") || status.Equals("S"))
                    {
                            graphics.DrawString(pname, new Font("Calibri", 8), new SolidBrush(Color.Black), startX, startY + Offset);
                            graphics.DrawString(extendedPrice+" x "+pquantity.ToString(), new Font("Calibri", 8), new SolidBrush(Color.Black), startX + 160, startY + Offset);
                            graphics.DrawString(totalAmount.ToString(), new Font("Calibri", 8), new SolidBrush(Color.Black), startX + 210, startY + Offset);
                            Offset = Offset + 15;
                    }

                }
                graphics.DrawString(underLine, new Font("calibri", 10), new SolidBrush(Color.Black), 0, startY + Offset);
               
                Offset = Offset + 15;
                graphics.DrawString("Total Amount:", new Font("Calibri", 10), new SolidBrush(Color.Black), startX + 90, startY + Offset);
                graphics.DrawString(amount.ToString(), new Font("Calibri", 10), new SolidBrush(Color.Black), startX + 210, startY + Offset);
                if (double.Parse(discount) > 0)
                {
                    Offset = Offset + 15;
                    graphics.DrawString("Discount:", new Font("Calibri", 10), new SolidBrush(Color.Black), startX + 90, startY + Offset);
                    graphics.DrawString(discount.ToString(), new Font("Calibri", 10), new SolidBrush(Color.Black), startX + 210, startY + Offset);
                }
                Offset = Offset + 15;
                graphics.DrawString("Grand Total:", new Font("Calibri", 10), new SolidBrush(Color.Black), startX + 90, startY + Offset);
                graphics.DrawString(grandTotal.ToString(), new Font("Calibri", 10), new SolidBrush(Color.Black), startX + 210, startY + Offset);
                
                    Offset = Offset + 15;
                    graphics.DrawString("Amount Received:", new Font("Calibri", 10), new SolidBrush(Color.Black), startX + 90, startY + Offset);
                    graphics.DrawString(amountReceived.ToString(), new Font("Calibri", 10), new SolidBrush(Color.Black), startX + 210, startY + Offset);
                    Offset = Offset + 15;
                    graphics.DrawString("Change:", new Font("Calibri", 10), new SolidBrush(Color.Black), startX + 90, startY + Offset);
                    graphics.DrawString(change.ToString(), new Font("Calibri", 10), new SolidBrush(Color.Black), startX + 210, startY + Offset);
                Offset = Offset + 15;
                graphics.DrawString(underLine, new Font("calibri", 10), new SolidBrush(Color.Black), 0, startY + Offset);
                format = new StringFormat() { Alignment = StringAlignment.Far};
                //----------
                Offset = Offset + 5;
                rect = new RectangleF(startX, startY + Offset, 270, 30);
                e.Graphics.DrawString("ہمارے ہاں تمام پرائیویٹ اسکولوں اور سرکاری  اسکولوں", new Font("Jameel Noori Nastaleeq", 15), new SolidBrush(Color.Black), rect, format);
                Offset = Offset + 32;
                //----------
                Offset = Offset + 15;
                e.Graphics.DrawString("For any complain please contact: 081-2664782", new Font("Ubuntu", 8), new SolidBrush(Color.Black), rect, format);
                Offset = Offset + 15;
                graphics.DrawString(underLine, new Font("calibri", 10), new SolidBrush(Color.Black), 0, startY + Offset);
                Offset = Offset + 15;
                e.Graphics.DrawString("Thank You For Visit", new Font("Ubuntu", 8), new SolidBrush(Color.Black), rect, format);
                Offset = Offset + 15;
                graphics.DrawString(underLine, new Font("calibri", 10), new SolidBrush(Color.Black), 0, startY + Offset);
                    Offset = Offset + 15;
                    graphics.DrawString("Software By Softnat Technologies: 03218197593", new Font("calibri", 9), new SolidBrush(Color.Black), startX + 20, startY + Offset);
                    Offset = Offset + 15;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }
        double oldAmount;
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                resetData();
                resetFinal();
                OldSales old = new OldSales();
                old.ShowDialog();
                if (Common.command == true)
                {
                    this.status = "Exchange Mode";
                    this.orderCode = Common.OrderId;
                    Orders ord = new Orders();
                    ord.orderCode = this.orderCode;
                    DataTable dt = ord.getOrderById();
                    totalNetAmount = double.Parse(dt.Rows[0]["amount"].ToString());
                    totalDiscount = double.Parse(dt.Rows[0]["discount"].ToString());
                    oldAmount = double.Parse(dt.Rows[0]["totalAmount"].ToString());
                    amountReceived = double.Parse(dt.Rows[0]["received"].ToString());
                    cashBack = double.Parse(dt.Rows[0]["change"].ToString());
                    string paymentType = dt.Rows[0]["paymentType"].ToString();
                    if(paymentType.Equals("Credit"))
                        txtAmountReceived.Text = amountReceived.ToString();
                        else
                        txtAmountReceived.Text = oldAmount.ToString();


                    int c = 0;
                    for (int x = 0; x < cboPaymentType.Items.Count; x++)
                    {

                        string str = cboPaymentType.Text;
                        if (str == paymentType)
                        {
                            cboPaymentType.SelectedIndex = c;
                            break;
                        }
                        c++;
                    }


                    calculateFinalAmount();

                    OrderDetail detail = new OrderDetail();
                    detail.orderCode = this.orderCode;
                    DataTable dtx = detail.getOrderByOrderId();
                    orders.Clear();
                    count = 1;
                    for (int i = 0; i < dtx.Rows.Count; i++)
                    {
                        string description = dtx.Rows[i]["productDescription"].ToString();
                        string code = dtx.Rows[i]["productCode"].ToString();
                        int detailId = Int32.Parse(dtx.Rows[i]["id"].ToString());

                        double price = double.Parse(dtx.Rows[i]["price"].ToString());
                        double idiscount = double.Parse(dtx.Rows[i]["discount"].ToString());
                        double extended = double.Parse(dtx.Rows[i]["extendedPrice"].ToString());
                        double quantity = double.Parse(dtx.Rows[i]["quantity"].ToString());
                        double totalPrice = double.Parse(dtx.Rows[i]["netAmount"].ToString());
                        string istatus = dtx.Rows[i]["itemStatus"].ToString();
                        //type-------------------------------------------------------------------------------------
                        if (istatus.Equals("R"))
                            orders.Rows.Add(count, code, description, price.ToString(), idiscount.ToString(), extended.ToString(), quantity.ToString(), totalPrice.ToString(), "*" + istatus);
                        else
                            orders.Rows.Add(count, code, description, price.ToString(), idiscount.ToString(), extended.ToString(), quantity.ToString(), totalPrice.ToString(), istatus);
                        count++;
                    }
                    bindGrid();
                }
                else
                {
                    //--------
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void reset(object sender, EventArgs e)
        {
            resetData();
            resetFinal();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                YesNo y = new YesNo("Are You Sure For Return?");
                y.ShowDialog();
                if (Common.command == true)
                {
                    if (this.status.Equals("Exchange Mode"))
                    {
                        string type = productGrid.SelectedRows[0].Cells[8].Value.ToString();
                        if (type.Equals("N") || type.Equals("R"))
                        {
                            ErrorBox error = new ErrorBox("Sorry Cant Roll Back Fresh/Returned Order\nJust Use Remove Option");
                            error.ShowDialog();
                        }
                        else
                        {
                            double quantity = double.Parse(productGrid.SelectedRows[0].Cells["Quantity"].Value.ToString());
                            double extPrice = double.Parse(productGrid.Rows[0].Cells[7].Value.ToString());
                            //string dId = productGrid.SelectedRows[0].Cells[0].Value.ToString();
                            if (quantity == 1)
                            {

                                Orders ordz = new Orders();
                                ordz.orderCode = this.orderCode;

                                int num = Convert.ToInt32(productGrid.SelectedRows[0].Cells[0].Value.ToString());
                                for (int i = 0; i < orders.Rows.Count; i++)
                                {
                                    DataRow dr = orders.Rows[i];
                                    if (Convert.ToInt32(dr["Seriel"].ToString()) == num)
                                    {
                                        totalNetAmount -= float.Parse(dr["Total"].ToString());
                                        totalDiscount -= (float.Parse(dr["Discount"].ToString()) * float.Parse(dr["Quantity"].ToString()));
                                        dr["S"] = "R";
                                        dr.AcceptChanges();
                                    }
                                }
                                //productGrid.DataSource = orders;
                                bindGrid();
                                calculateFinalAmount();

                            }
                            else
                            {
                                GetAmount obj = new GetAmount();
                                obj.ShowDialog();
                                if (Common.command==true)
                                {
                                    double newQuantity = Common.quantity;
                                    double newPrice = newQuantity * extPrice;

                                    int num = Convert.ToInt32(productGrid.SelectedRows[0].Cells[0].Value.ToString());
                                    for (int i = 0; i < orders.Rows.Count; i++)
                                    {
                                        DataRow dr = orders.Rows[i];
                                        if (Convert.ToInt32(dr["Seriel"].ToString()) == num)
                                        {
                                            if (quantity == newQuantity)
                                            {
                                                totalNetAmount -= float.Parse(dr["Total"].ToString());
                                                discount -= (float.Parse(dr["Discount"].ToString()) * newQuantity);
                                                dr["S"] = "R";
                                                dr["Total"] = "0";
                                                dr.AcceptChanges();
                                            }
                                            else
                                            {
                                                totalNetAmount -= newPrice;
                                                discount -= (float.Parse(dr["Discount"].ToString()) * newQuantity);
                                                dr["Quantity"] = (quantity - newQuantity);
                                                dr["Total"] = "0";
                                                dr.AcceptChanges();

                                                string codes = productGrid.SelectedRows[0].Cells[1].Value.ToString();
                                                string description = productGrid.SelectedRows[0].Cells[2].Value.ToString();
                                                string prices = productGrid.SelectedRows[0].Cells[8].Value.ToString();
                                                string totals = productGrid.SelectedRows[0].Cells[11].Value.ToString();
                                                string units = productGrid.SelectedRows[0].Cells[10].Value.ToString();
                                                orders.Rows.Add(count, codes, description, "0", "0", "0", newQuantity.ToString(), "0", "R");
                                                count++;
                                            }
                                        }
                                    }


                                    productGrid.DataSource = orders;
                                    lblGrandAmount.Text = grandTotal.ToString();
                                    txtAmountReceived.Text = grandTotal.ToString();
                                    lblGrandAmount.Text = grandTotal.ToString();
                                    txtCash.Text = (oldAmount - grandTotal).ToString();
                                    if (double.Parse(txtCash.Text) < 0)
                                        lblCashback.Text = "Receivables";
                                    else
                                        lblCashback.Text = "Payables";
                                    txtCash.Text = (grandTotal - double.Parse(txtAmountReceived.Text)).ToString();
                                }
                                else
                                {
                                    ErrorBox error = new ErrorBox("Command Cancelled");
                                    error.ShowDialog();
                                }
                            }

                        } // -- End of type test
                    }
                    else
                    {
                        ErrorBox error = new ErrorBox("Sorry Cant Exchange in Fresh Order Mode");
                        error.ShowDialog();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void button5_Enter(object sender, EventArgs e)
        {
            button5.BackColor = Color.FromArgb(255, 128, 0);
        }

        private void button5_Leave(object sender, EventArgs e)
        {
            button5.BackColor = Color.Green;

        }

        private void productGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
