using System;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace MyShop
{
    public partial class MainForm : Form
    {
        private string currentUserName;
        private bool canManageData;
        private bool goodsRowSelected;
        private bool customerRowSelected;
        private bool adminLoginLogged;
        private TextBox txtLogPath;
        private Button btnReceiveLogFile;
        private DataGridView dgvLibraryMembers;
        private DataGridView dgvLibraryBooks;
        private DataTable libraryMembersTable;
        private DataTable libraryBooksTable;

        public MainForm()
        {
            InitializeComponent();
            InitializeUsersTabTools();
            PrepareFactorGrid();
            RegisterEditorStateEvents();
            UpdateEditorButtons();
        }

        public MainForm(string userName)
            : this()
        {
            currentUserName = userName;
        }

        private void PrepareFactorGrid()
        {
            colFactorDelete.Image = CreateDeleteImage();
        }

        private Bitmap CreateDeleteImage()
        {
            Bitmap image = new Bitmap(16, 16);

            using (Graphics graphics = Graphics.FromImage(image))
            {
                graphics.Clear(Color.Transparent);

                using (Pen pen = new Pen(Color.Red, 2))
                {
                    graphics.DrawLine(pen, 4, 4, 12, 12);
                    graphics.DrawLine(pen, 12, 4, 4, 12);
                }
            }

            return image;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            ApplyAccessLevel(currentUserName);
            lblFactorDateValue.Text = DateTime.Now.ToString("yyyy/MM/dd");

            // بارگذاری فهرست کالاها پس از ورود موفق کاربر
            this.goodsTableAdapter1.Fill(this.myShopDataSet1.Goods);
            this.customersTableAdapter1.Fill(this.myShopDataSet1.Customers);

        }

        private void ApplyAccessLevel(string userName)
        {
            bool isAdmin = string.Equals(userName, "admin", StringComparison.OrdinalIgnoreCase);

            canManageData = isAdmin;
            UpdateEditorButtons();

            if (isAdmin)
            {
                WriteAdminLoginLog();
                LoadUsers();
            }
            else
            {
                tabMain.TabPages.Remove(tabUsers);
            }
        }

        private void LoadUsers()
        {
            MyShopDataSetTableAdapters.UsersTableAdapter usersTableAdapter = new MyShopDataSetTableAdapters.UsersTableAdapter();
            dgvUsers.DataSource = usersTableAdapter.GetData();
        }

        private void InitializeUsersTabTools()
        {
            Label lblLogPath;
            TabControl tabLibraryInfo;
            TabPage tabMembers;
            TabPage tabBooks;
            Button btnDeleteMember;
            Button btnEditMember;
            Button btnDeleteBook;
            Button btnEditBookTitle;

            dgvUsers.Location = new Point(20, 38);
            dgvUsers.Size = new Size(330, 84);

            txtUserCodeAdmin.Location = new Point(556, 20);
            txtUserNameAdmin.Location = new Point(556, 50);
            txtUserPasswordAdmin.Location = new Point(556, 80);
            lblUserCodeAdmin.Location = new Point(636, 22);
            lblUserNameAdmin.Location = new Point(636, 52);
            lblUserPasswordAdmin.Location = new Point(636, 82);
            btnAddUser.Location = new Point(480, 112);
            btnUpdateUser.Location = new Point(556, 112);
            btnDeleteUser.Location = new Point(632, 112);

            lblLogPath = new Label();
            lblLogPath.Location = new Point(646, 154);
            lblLogPath.Size = new Size(90, 18);
            lblLogPath.Text = "مسیر ذخیره:";

            txtLogPath = new TextBox();
            txtLogPath.Location = new Point(286, 152);
            txtLogPath.Size = new Size(354, 24);
            txtLogPath.RightToLeft = RightToLeft.No;

            btnReceiveLogFile = new Button();
            btnReceiveLogFile.Location = new Point(180, 150);
            btnReceiveLogFile.Size = new Size(100, 26);
            btnReceiveLogFile.Text = "دریافت پرونده";
            btnReceiveLogFile.UseVisualStyleBackColor = true;
            btnReceiveLogFile.Click += new EventHandler(btnReceiveLogFile_Click);

            tabLibraryInfo = new TabControl();
            tabLibraryInfo.Location = new Point(20, 182);
            tabLibraryInfo.Size = new Size(720, 104);
            tabLibraryInfo.RightToLeft = RightToLeft.Yes;
            tabLibraryInfo.RightToLeftLayout = true;

            tabMembers = new TabPage();
            tabMembers.Text = "اعضا";
            tabMembers.UseVisualStyleBackColor = true;

            tabBooks = new TabPage();
            tabBooks.Text = "کتاب‌ها";
            tabBooks.UseVisualStyleBackColor = true;

            dgvLibraryMembers = CreateLibraryGrid();
            btnEditMember = CreateSmallUserTabButton("ویرایش", new Point(548, 10), btnEditMember_Click);
            btnDeleteMember = CreateSmallUserTabButton("حذف", new Point(624, 10), btnDeleteMember_Click);

            dgvLibraryBooks = CreateLibraryGrid();
            btnEditBookTitle = CreateSmallUserTabButton("ویرایش", new Point(548, 10), btnEditBookTitle_Click);
            btnDeleteBook = CreateSmallUserTabButton("حذف", new Point(624, 10), btnDeleteBook_Click);

            tabMembers.Controls.Add(dgvLibraryMembers);
            tabMembers.Controls.Add(btnEditMember);
            tabMembers.Controls.Add(btnDeleteMember);
            tabBooks.Controls.Add(dgvLibraryBooks);
            tabBooks.Controls.Add(btnEditBookTitle);
            tabBooks.Controls.Add(btnDeleteBook);
            tabLibraryInfo.TabPages.Add(tabMembers);
            tabLibraryInfo.TabPages.Add(tabBooks);

            tabUsers.Controls.Add(lblLogPath);
            tabUsers.Controls.Add(txtLogPath);
            tabUsers.Controls.Add(btnReceiveLogFile);
            tabUsers.Controls.Add(tabLibraryInfo);

            FillLibrarySampleData();
        }

        private DataGridView CreateLibraryGrid()
        {
            DataGridView grid = new DataGridView();

            grid.AllowUserToAddRows = false;
            grid.AllowUserToDeleteRows = false;
            grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            grid.BackgroundColor = Color.White;
            grid.Location = new Point(8, 8);
            grid.ReadOnly = false;
            grid.RightToLeft = RightToLeft.Yes;
            grid.RowHeadersWidth = 24;
            grid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            grid.Size = new Size(520, 62);

            return grid;
        }

        private Button CreateSmallUserTabButton(string text, Point location, EventHandler clickHandler)
        {
            Button button = new Button();

            button.Location = location;
            button.Size = new Size(70, 26);
            button.Text = text;
            button.UseVisualStyleBackColor = true;
            button.Click += clickHandler;

            return button;
        }

        private void FillLibrarySampleData()
        {
            libraryMembersTable = new DataTable();
            libraryMembersTable.Columns.Add("کد عضو");
            libraryMembersTable.Columns.Add("نام");
            libraryMembersTable.Columns.Add("نام خانوادگی");
            libraryMembersTable.Columns.Add("موبایل");
            libraryMembersTable.Rows.Add("1", "رضا", "احمدی", "09120000001");
            libraryMembersTable.Rows.Add("2", "مریم", "کریمی", "09120000002");
            dgvLibraryMembers.DataSource = libraryMembersTable;

            libraryBooksTable = new DataTable();
            libraryBooksTable.Columns.Add("کد کتاب");
            libraryBooksTable.Columns.Add("عنوان کتاب");
            libraryBooksTable.Columns.Add("نویسنده");
            libraryBooksTable.Rows.Add("1", "آموزش سی شارپ", "جعفری");
            libraryBooksTable.Rows.Add("2", "پایگاه داده Access", "محمدی");
            dgvLibraryBooks.DataSource = libraryBooksTable;
        }

        private void WriteAdminLoginLog()
        {
            string logPath;
            string logText;

            if (adminLoginLogged)
            {
                return;
            }

            logPath = GetApplicationLogPath();
            logText = "ورود مدیر: " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + Environment.NewLine;

            try
            {
                File.AppendAllText(logPath, logText, System.Text.Encoding.UTF8);
                adminLoginLogged = true;
            }
            catch
            {
                MessageBox.Show("خطا در ثبت زمان ورود مدیر در پرونده Log.txt", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private string GetApplicationLogPath()
        {
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log.txt");
        }

        private void btnReceiveLogFile_Click(object sender, EventArgs e)
        {
            string destinationPath;
            string sourcePath;
            string targetPath;

            destinationPath = txtLogPath.Text.Trim();

            if (destinationPath.Length == 0)
            {
                MessageBox.Show("مسیر ذخیره پرونده را وارد کنید.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            sourcePath = GetApplicationLogPath();
            targetPath = destinationPath;

            try
            {
                if (Path.GetExtension(targetPath).Length == 0)
                {
                    if (!Directory.Exists(targetPath))
                    {
                        Directory.CreateDirectory(targetPath);
                    }

                    targetPath = Path.Combine(targetPath, "Log.txt");
                }

                if (!File.Exists(sourcePath))
                {
                    File.WriteAllText(sourcePath, "", System.Text.Encoding.UTF8);
                }

                File.Copy(sourcePath, targetPath, true);
                MessageBox.Show("پرونده Log.txt با موفقیت ذخیره شد.");
            }
            catch
            {
                MessageBox.Show("خطا در ذخیره پرونده Log.txt", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnEditMember_Click(object sender, EventArgs e)
        {
            BeginGridEdit(dgvLibraryMembers);
        }

        private void btnDeleteMember_Click(object sender, EventArgs e)
        {
            DeleteSelectedGridRow(dgvLibraryMembers);
        }

        private void btnEditBookTitle_Click(object sender, EventArgs e)
        {
            if (dgvLibraryBooks.CurrentRow != null && dgvLibraryBooks.Columns.Contains("عنوان کتاب"))
            {
                dgvLibraryBooks.CurrentCell = dgvLibraryBooks.CurrentRow.Cells["عنوان کتاب"];
            }

            BeginGridEdit(dgvLibraryBooks);
        }

        private void btnDeleteBook_Click(object sender, EventArgs e)
        {
            DeleteSelectedGridRow(dgvLibraryBooks);
        }

        private void BeginGridEdit(DataGridView grid)
        {
            if (grid.CurrentCell == null)
            {
                MessageBox.Show("ابتدا یک ردیف را انتخاب کنید.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            grid.Focus();
            grid.BeginEdit(true);
        }

        private void DeleteSelectedGridRow(DataGridView grid)
        {
            DataRowView rowView;

            if (grid.CurrentRow == null)
            {
                MessageBox.Show("ابتدا یک ردیف را انتخاب کنید.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            rowView = grid.CurrentRow.DataBoundItem as DataRowView;

            if (rowView != null)
            {
                rowView.Delete();
            }
        }

        private void RegisterEditorStateEvents()
        {
            txtGoodsCode.TextChanged += new EventHandler(EditorTextChanged);
            txtGoodsName.TextChanged += new EventHandler(EditorTextChanged);
            txtUnitPrice.TextChanged += new EventHandler(EditorTextChanged);
            txtStock.TextChanged += new EventHandler(EditorTextChanged);

            txtCustomerCode.TextChanged += new EventHandler(EditorTextChanged);
            txtCustomerFirstName.TextChanged += new EventHandler(EditorTextChanged);
            txtCustomerLastName.TextChanged += new EventHandler(EditorTextChanged);
            txtCustomerMobile.TextChanged += new EventHandler(EditorTextChanged);
        }

        private void EditorTextChanged(object sender, EventArgs e)
        {
            UpdateEditorButtons();
        }

        private void UpdateEditorButtons()
        {
            bool goodsComplete = txtGoodsCode.Text.Length > 0 &&
                txtGoodsName.Text.Length > 0 &&
                txtUnitPrice.Text.Length > 0 &&
                txtStock.Text.Length > 0;

            bool customerComplete = txtCustomerCode.Text.Length > 0 &&
                txtCustomerFirstName.Text.Length > 0 &&
                txtCustomerLastName.Text.Length > 0 &&
                txtCustomerMobile.Text.Length > 0;

            btnSave.Enabled = canManageData && goodsComplete;
            btnEdit.Enabled = canManageData && goodsRowSelected;
            btnDelete.Enabled = canManageData && goodsRowSelected;

            btnSaveCustomer.Enabled = canManageData && customerComplete;
            btnEditCustomer.Enabled = canManageData && customerRowSelected;
            btnDeleteCustomer.Enabled = canManageData && customerRowSelected;
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            goodsBindingSource.MoveFirst();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            goodsBindingSource.MovePrevious();
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            goodsBindingSource.MoveNext();
        }

        private void btnFirst_Click(object sender, EventArgs e)
        {
            goodsBindingSource.MoveLast();
        }

        private void dgvProducts_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvGoods.CurrentCell == null)
            {
                return;
            }

            int index = dgvGoods.CurrentCell.RowIndex;

            txtGoodsCode.Text = dgvGoods.Rows[index].Cells[0].Value.ToString();
            txtGoodsName.Text = dgvGoods.Rows[index].Cells[1].Value.ToString();
            txtUnitPrice.Text = dgvGoods.Rows[index].Cells[2].Value.ToString();
            txtStock.Text = dgvGoods.Rows[index].Cells[3].Value.ToString();
            goodsRowSelected = true;
            UpdateEditorButtons();
        }

        private void btnAddGoods_Click(object sender, EventArgs e)
        {
            int goodsCode;
            int unitPrice;
            int stock;

            if (txtGoodsCode.Text.Length == 0 || txtGoodsName.Text.Length == 0 || txtUnitPrice.Text.Length == 0)
            {
                MessageBox.Show("اطلاعات کالا را کامل وارد کنید.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!int.TryParse(txtGoodsCode.Text, out goodsCode) ||
                !int.TryParse(txtUnitPrice.Text, out unitPrice) ||
                !int.TryParse(txtStock.Text, out stock))
            {
                MessageBox.Show("کد کالا، قیمت واحد و موجودی باید عددی باشند.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                goodsTableAdapter1.InsertQuery(goodsCode, txtGoodsName.Text, unitPrice, stock);
                goodsTableAdapter1.Fill(myShopDataSet1.Goods);
                goodsRowSelected = false;
                UpdateEditorButtons();
                MessageBox.Show("با موفقیت ثبت شد.");
            }
            catch
            {
                MessageBox.Show("خطا در ثبت کالا", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDeleteGoods_Click(object sender, EventArgs e)
        {
            int goodsCode;

            if (txtGoodsCode.Text.Length == 0)
            {
                MessageBox.Show("کد کالا را وارد کنید.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!int.TryParse(txtGoodsCode.Text, out goodsCode))
            {
                MessageBox.Show("کد کالا باید عددی باشد.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                goodsTableAdapter1.DeleteQuery(goodsCode);
                goodsTableAdapter1.Fill(myShopDataSet1.Goods);
                ClearGoodsFields();
                MessageBox.Show("با موفقیت حذف شد.");
            }
            catch
            {
                MessageBox.Show("خطا در حذف کالا", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnUpdateGoods_Click(object sender, EventArgs e)
        {
            int goodsCode;
            int unitPrice;
            int stock;

            if (txtGoodsCode.Text.Length == 0 || txtGoodsName.Text.Length == 0 || txtUnitPrice.Text.Length == 0)
            {
                MessageBox.Show("اطلاعات کالا را کامل وارد کنید.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!int.TryParse(txtGoodsCode.Text, out goodsCode) ||
                !int.TryParse(txtUnitPrice.Text, out unitPrice) ||
                !int.TryParse(txtStock.Text, out stock))
            {
                MessageBox.Show("کد کالا، قیمت واحد و موجودی باید عددی باشند.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                goodsTableAdapter1.UpdateQuery(txtGoodsName.Text, unitPrice, stock, goodsCode);
                goodsTableAdapter1.Fill(myShopDataSet1.Goods);
                goodsRowSelected = false;
                UpdateEditorButtons();
                MessageBox.Show("با موفقیت ویرایش شد.");
            }
            catch
            {
                MessageBox.Show("خطا در ویرایش کالا", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtFGoodsCode_KeyDown(object sender, KeyEventArgs e)
        {
            lblPrice.Text = "";
            lblGoodsName.Text = "";
            lblFStockValue.Text = "";

            if (e.KeyCode == Keys.Enter)
            {
                FillSelectedGoodsInfo();
            }
        }

        private void FillSelectedGoodsInfo()
        {
            int goodsCode;
            MyShopDataSet.GoodsDataTable goodsTable = new MyShopDataSet.GoodsDataTable();

            if (txtFGoodsCode.Text.Length == 0)
            {
                return;
            }

            if (!int.TryParse(txtFGoodsCode.Text, out goodsCode))
            {
                MessageBox.Show("کد کالا باید عددی باشد.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtFGoodsCode.Focus();
                return;
            }

            try
            {
                goodsTableAdapter1.FillByGoodsCode(goodsTable, goodsCode);

                if (goodsTable.Rows.Count > 0)
                {
                    lblGoodsName.Text = goodsTable.Rows[0]["GoodsName"].ToString();
                    lblPrice.Text = goodsTable.Rows[0]["GoodsUnitPrice"].ToString();
                    lblFStockValue.Text = goodsTable.Rows[0]["GoodsStock"].ToString();
                    txtFAmount.Focus();
                }
                else
                {
                    MessageBox.Show("کالایی با این کد پیدا نشد.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtFGoodsCode.Focus();
                }
            }
            catch
            {
                MessageBox.Show("خطا در جستجوی کالا", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnFindGoods_Click(object sender, EventArgs e)
        {
            Form dialog = CreateSelectDialog("انتخاب کالا");
            DataGridView grid = CreateSelectGrid();
            Button btnSelect = CreateSelectButton();

            grid.Columns.Add(CreateTextColumn("GoodsCode", "GoodsCode", "کد کالا"));
            grid.Columns.Add(CreateTextColumn("GoodsName", "GoodsName", "نام کالا"));
            grid.Columns.Add(CreateTextColumn("GoodsUnitPrice", "GoodsUnitPrice", "قیمت واحد"));
            grid.Columns.Add(CreateTextColumn("GoodsStock", "GoodsStock", "موجودی"));

            try
            {
                grid.DataSource = goodsTableAdapter1.GetData();
            }
            catch
            {
                MessageBox.Show("خطا در دریافت فهرست کالاها", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            btnSelect.Click += delegate
            {
                if (grid.CurrentRow == null)
                {
                    MessageBox.Show("ابتدا یک کالا را انتخاب کنید.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                txtFGoodsCode.Text = Convert.ToString(grid.CurrentRow.Cells["GoodsCode"].Value);
                FillSelectedGoodsInfo();
                dialog.DialogResult = DialogResult.OK;
                dialog.Close();
            };

            dialog.Controls.Add(grid);
            dialog.Controls.Add(btnSelect);
            dialog.ShowDialog(this);
        }

        private void btnFindCustomer_Click(object sender, EventArgs e)
        {
            Form dialog = CreateSelectDialog("انتخاب مشتری");
            DataGridView grid = CreateSelectGrid();
            Button btnSelect = CreateSelectButton();

            grid.Columns.Add(CreateTextColumn("CustomerCode", "CustomerCode", "کد مشتری"));
            grid.Columns.Add(CreateTextColumn("CustomerFirstName", "CustomerFirstName", "نام"));
            grid.Columns.Add(CreateTextColumn("CustomerLastName", "CustomerLastName", "نام خانوادگی"));
            grid.Columns.Add(CreateTextColumn("CustomerMobile", "CustomerMobile", "موبایل"));

            try
            {
                grid.DataSource = customersTableAdapter1.GetData();
            }
            catch
            {
                MessageBox.Show("خطا در دریافت فهرست مشتری‌ها", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            btnSelect.Click += delegate
            {
                string firstName;
                string lastName;

                if (grid.CurrentRow == null)
                {
                    MessageBox.Show("ابتدا یک مشتری را انتخاب کنید.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                firstName = Convert.ToString(grid.CurrentRow.Cells["CustomerFirstName"].Value);
                lastName = Convert.ToString(grid.CurrentRow.Cells["CustomerLastName"].Value);

                txtFCustomerCode.Text = Convert.ToString(grid.CurrentRow.Cells["CustomerCode"].Value);
                lblFCustomerName.Text = firstName + " " + lastName;
                lblFCustomerMobile.Text = Convert.ToString(grid.CurrentRow.Cells["CustomerMobile"].Value);
                txtFGoodsCode.Focus();
                dialog.DialogResult = DialogResult.OK;
                dialog.Close();
            };

            dialog.Controls.Add(grid);
            dialog.Controls.Add(btnSelect);
            dialog.ShowDialog(this);
        }

        private Form CreateSelectDialog(string title)
        {
            Form dialog = new Form();

            dialog.Text = title;
            dialog.Font = new Font("Tahoma", 8.25F);
            dialog.StartPosition = FormStartPosition.CenterParent;
            dialog.FormBorderStyle = FormBorderStyle.FixedDialog;
            dialog.MaximizeBox = false;
            dialog.MinimizeBox = false;
            dialog.ClientSize = new Size(560, 360);
            dialog.RightToLeft = RightToLeft.Yes;

            return dialog;
        }

        private DataGridView CreateSelectGrid()
        {
            DataGridView grid = new DataGridView();

            grid.AllowUserToAddRows = false;
            grid.AllowUserToDeleteRows = false;
            grid.AutoGenerateColumns = false;
            grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            grid.BackgroundColor = Color.White;
            grid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            grid.Location = new Point(12, 12);
            grid.Name = "dgvSelect";
            grid.ReadOnly = true;
            grid.RightToLeft = RightToLeft.Yes;
            grid.RowHeadersWidth = 24;
            grid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            grid.Size = new Size(536, 284);

            return grid;
        }

        private Button CreateSelectButton()
        {
            Button button = new Button();

            button.Location = new Point(12, 306);
            button.Name = "btnSelect";
            button.Size = new Size(536, 42);
            button.Text = "انتخاب";
            button.UseVisualStyleBackColor = true;

            return button;
        }

        private DataGridViewTextBoxColumn CreateTextColumn(string name, string dataPropertyName, string headerText)
        {
            DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();

            column.Name = name;
            column.DataPropertyName = dataPropertyName;
            column.HeaderText = headerText;
            column.ReadOnly = true;

            return column;
        }

        private void btnInsertGoodsFactor_Click(object sender, EventArgs e)
        {
            tabMain.SelectedTab = tabBuy;
            txtFGoodsCode.Text = txtGoodsCode.Text;
            lblGoodsName.Text = txtGoodsName.Text;
            lblPrice.Text = txtUnitPrice.Text;
            lblFStockValue.Text = txtStock.Text;
            txtFAmount.Focus();
        }

        private void btnClearGoods_Click(object sender, EventArgs e)
        {
            ClearGoodsFields();
        }

        private void ClearGoodsFields()
        {
            txtGoodsCode.Text = "";
            txtGoodsName.Text = "";
            txtUnitPrice.Text = "";
            txtStock.Text = "";
            goodsRowSelected = false;
            UpdateEditorButtons();
        }

        private void btnInsertGoods_Click(object sender, EventArgs e)
        {
            int amount;
            int price;
            int rowIndex;

            if (txtFGoodsCode.Text.Length == 0)
            {
                MessageBox.Show("کد کالا را وارد کنید.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtFGoodsCode.Focus();
                return;
            }

            if (lblGoodsName.Text.Length == 0 || lblPrice.Text.Length == 0)
            {
                FillSelectedGoodsInfo();
            }

            if (lblGoodsName.Text.Length == 0 || lblPrice.Text.Length == 0)
            {
                return;
            }

            if (!int.TryParse(txtFAmount.Text, out amount) || amount <= 0)
            {
                MessageBox.Show("تعداد کالا را درست وارد کنید.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtFAmount.Focus();
                return;
            }

            if (!int.TryParse(lblPrice.Text, out price))
            {
                MessageBox.Show("قیمت کالا درست نیست.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            rowIndex = dgvFactors.Rows.Add();
            dgvFactors.Rows[rowIndex].Cells["colFactorCode"].Value = txtFGoodsCode.Text;
            dgvFactors.Rows[rowIndex].Cells["colFactorName"].Value = lblGoodsName.Text;
            dgvFactors.Rows[rowIndex].Cells["colFactorAmount"].Value = amount;
            dgvFactors.Rows[rowIndex].Cells["colFactorUnitPrice"].Value = price;
            dgvFactors.Rows[rowIndex].Cells["colFactorTotalPrice"].Value = amount * price;

            CalculateFactorTotal();
        }

        private void txtFCustomerCode_KeyDown(object sender, KeyEventArgs e)
        {
            lblFCustomerName.Text = "";
            lblFCustomerMobile.Text = "";

            if (e.KeyCode == Keys.Enter)
            {
                FillSelectedCustomerInfo();
            }
        }

        private void FillSelectedCustomerInfo()
        {
            int customerCode;
            MyShopDataSet.CustomersDataTable customersTable = new MyShopDataSet.CustomersDataTable();
            MyShopDataSetTableAdapters.CustomersTableAdapter customersTableAdapter = new MyShopDataSetTableAdapters.CustomersTableAdapter();

            if (txtFCustomerCode.Text.Length == 0)
            {
                return;
            }

            if (!int.TryParse(txtFCustomerCode.Text, out customerCode))
            {
                MessageBox.Show("کد مشتری باید عددی باشد.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtFCustomerCode.Focus();
                return;
            }

            try
            {
                customersTableAdapter.FillByCustomerCode(customersTable, customerCode);

                if (customersTable.Rows.Count > 0)
                {
                    lblFCustomerName.Text = customersTable.Rows[0]["CustomerFirstName"].ToString() + " " +
                        customersTable.Rows[0]["CustomerLastName"].ToString();
                    lblFCustomerMobile.Text = customersTable.Rows[0]["CustomerMobile"].ToString();
                    txtFGoodsCode.Focus();
                }
                else
                {
                    MessageBox.Show("مشتری با این کد پیدا نشد.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtFCustomerCode.Focus();
                }
            }
            catch
            {
                MessageBox.Show("خطا در جستجوی مشتری", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSaveFactor_Click(object sender, EventArgs e)
        {
            int customerCode;
            int factorCode;
            int i;
            MyShopDataSetTableAdapters.FactorsTableAdapter factorsTableAdapter = new MyShopDataSetTableAdapters.FactorsTableAdapter();
            MyShopDataSetTableAdapters.FactorItemsTableAdapter factorItemsTableAdapter = new MyShopDataSetTableAdapters.FactorItemsTableAdapter();

            if (!int.TryParse(txtFCustomerCode.Text, out customerCode))
            {
                MessageBox.Show("کد مشتری را درست وارد کنید.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtFCustomerCode.Focus();
                return;
            }

            if (dgvFactors.Rows.Count == 0)
            {
                MessageBox.Show("سبد خرید خالی است.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                factorCode = factorsTableAdapter.InsertQuery(customerCode, DateTime.Now);

                for (i = 0; i < dgvFactors.Rows.Count; i++)
                {
                    factorItemsTableAdapter.InsertQuery(
                        factorCode,
                        ToInt(dgvFactors.Rows[i].Cells["colFactorCode"].Value),
                        ToInt(dgvFactors.Rows[i].Cells["colFactorAmount"].Value));
                }

                dgvFactors.Rows.Clear();
                CalculateFactorTotal();
                MessageBox.Show("برگه خرید با موفقیت ثبت شد.");
            }
            catch
            {
                MessageBox.Show("خطا در ثبت برگه خرید", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtSearchProductCode_KeyDown(object sender, KeyEventArgs e)
        {
            int goodsCode;

            if (e.KeyCode != Keys.Enter)
            {
                return;
            }

            if (!int.TryParse(txtSearchProductCode.Text, out goodsCode))
            {
                MessageBox.Show("کد کالا باید عددی باشد.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                goodsTableAdapter1.FillByGoodsCode(myShopDataSet1.Goods, goodsCode);
            }
            catch
            {
                MessageBox.Show("خطا در جستجوی کالا", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtSearchProductName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter)
            {
                return;
            }

            try
            {
                if (txtSearchProductName.Text.Length == 0)
                {
                    goodsTableAdapter1.Fill(myShopDataSet1.Goods);
                }
                else
                {
                    goodsTableAdapter1.FillByGoodsName(myShopDataSet1.Goods, txtSearchProductName.Text);
                }
            }
            catch
            {
                MessageBox.Show("خطا در جستجوی کالا", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgvCustomers_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }

            txtCustomerCode.Text = Convert.ToString(dgvCustomers.Rows[e.RowIndex].Cells["colCustomerCode"].Value);
            txtCustomerFirstName.Text = Convert.ToString(dgvCustomers.Rows[e.RowIndex].Cells["colCustomerFirstName"].Value);
            txtCustomerLastName.Text = Convert.ToString(dgvCustomers.Rows[e.RowIndex].Cells["colCustomerLastName"].Value);
            txtCustomerMobile.Text = Convert.ToString(dgvCustomers.Rows[e.RowIndex].Cells["colCustomerMobile"].Value);
            customerRowSelected = true;
            UpdateEditorButtons();
        }

        private void btnAddCustomer_Click(object sender, EventArgs e)
        {
            if (txtCustomerFirstName.Text.Length == 0 || txtCustomerLastName.Text.Length == 0 || txtCustomerMobile.Text.Length == 0)
            {
                MessageBox.Show("اطلاعات مشتری را کامل وارد کنید.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                customersTableAdapter1.InsertCustomerQuery(txtCustomerFirstName.Text, txtCustomerLastName.Text, txtCustomerMobile.Text);
                customersTableAdapter1.Fill(myShopDataSet1.Customers);
                customerRowSelected = false;
                UpdateEditorButtons();
                MessageBox.Show("مشتری با موفقیت ثبت شد.");
            }
            catch
            {
                MessageBox.Show("خطا در ثبت مشتری", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnUpdateCustomer_Click(object sender, EventArgs e)
        {
            int customerCode;

            if (txtCustomerCode.Text.Length == 0 || txtCustomerFirstName.Text.Length == 0 ||
                txtCustomerLastName.Text.Length == 0 || txtCustomerMobile.Text.Length == 0)
            {
                MessageBox.Show("اطلاعات مشتری را کامل وارد کنید.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!int.TryParse(txtCustomerCode.Text, out customerCode))
            {
                MessageBox.Show("کد مشتری باید عددی باشد.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                customersTableAdapter1.UpdateCustomerQuery(txtCustomerFirstName.Text, txtCustomerLastName.Text, txtCustomerMobile.Text, customerCode);
                customersTableAdapter1.Fill(myShopDataSet1.Customers);
                customerRowSelected = false;
                UpdateEditorButtons();
                MessageBox.Show("مشتری با موفقیت ویرایش شد.");
            }
            catch
            {
                MessageBox.Show("خطا در ویرایش مشتری", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDeleteCustomer_Click(object sender, EventArgs e)
        {
            int customerCode;

            if (!int.TryParse(txtCustomerCode.Text, out customerCode))
            {
                MessageBox.Show("کد مشتری را درست وارد کنید.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                customersTableAdapter1.DeleteCustomerQuery(customerCode);
                customersTableAdapter1.Fill(myShopDataSet1.Customers);
                ClearCustomerFields();
                MessageBox.Show("مشتری با موفقیت حذف شد.");
            }
            catch
            {
                MessageBox.Show("خطا در حذف مشتری", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnClearCustomer_Click(object sender, EventArgs e)
        {
            ClearCustomerFields();
        }

        private void ClearCustomerFields()
        {
            txtCustomerCode.Text = "";
            txtCustomerFirstName.Text = "";
            txtCustomerLastName.Text = "";
            txtCustomerMobile.Text = "";
            customerRowSelected = false;
            UpdateEditorButtons();
        }

        private void btnShowBuyFormCustomer_Click(object sender, EventArgs e)
        {
            tabMain.SelectedTab = tabBuy;
            txtFCustomerCode.Text = txtCustomerCode.Text;
            lblFCustomerName.Text = txtCustomerFirstName.Text + " " + txtCustomerLastName.Text;
            lblFCustomerMobile.Text = txtCustomerMobile.Text;
            txtFGoodsCode.Focus();
        }

        private void txtSearchCustomerCode_KeyDown(object sender, KeyEventArgs e)
        {
            int customerCode;

            if (e.KeyCode != Keys.Enter)
            {
                return;
            }

            if (!int.TryParse(txtSearchCustomerCode.Text, out customerCode))
            {
                MessageBox.Show("کد مشتری باید عددی باشد.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                customersTableAdapter1.FillByCustomerCode(myShopDataSet1.Customers, customerCode);
            }
            catch
            {
                MessageBox.Show("خطا در جستجوی مشتری", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtSearchCustomerName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter)
            {
                return;
            }

            try
            {
                if (txtSearchCustomerName.Text.Length == 0)
                {
                    customersTableAdapter1.Fill(myShopDataSet1.Customers);
                }
                else
                {
                    customersTableAdapter1.FillByCustomerName(myShopDataSet1.Customers, txtSearchCustomerName.Text);
                }
            }
            catch
            {
                MessageBox.Show("خطا در جستجوی مشتری", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgvFactors_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0 && dgvFactors.Columns[e.ColumnIndex] is DataGridViewImageColumn)
            {
                dgvFactors.Rows.RemoveAt(e.RowIndex);
                CalculateFactorTotal();
            }
        }

        private void btnClearFactor_Click(object sender, EventArgs e)
        {
            dgvFactors.Rows.Clear();
            CalculateFactorTotal();
        }

        private void CalculateFactorTotal()
        {
            int total = 0;
            int i;

            for (i = 0; i < dgvFactors.Rows.Count; i++)
            {
                total += ToInt(dgvFactors.Rows[i].Cells["colFactorTotalPrice"].Value);
            }

            lblFTotalValue.Text = total.ToString();
        }

        private int ToInt(object value)
        {
            int result;

            if (value == null)
            {
                return 0;
            }

            if (int.TryParse(value.ToString(), out result))
            {
                return result;
            }

            return 0;
        }

        private void dgvUsers_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }

            txtUserCodeAdmin.Text = Convert.ToString(dgvUsers.Rows[e.RowIndex].Cells["UserCode"].Value);
            txtUserNameAdmin.Text = Convert.ToString(dgvUsers.Rows[e.RowIndex].Cells["Username"].Value);
            txtUserPasswordAdmin.Text = Convert.ToString(dgvUsers.Rows[e.RowIndex].Cells["Password"].Value);
        }

        private void btnAddUser_Click(object sender, EventArgs e)
        {
            MyShopDataSetTableAdapters.UsersTableAdapter usersTableAdapter = new MyShopDataSetTableAdapters.UsersTableAdapter();

            if (txtUserNameAdmin.Text.Length == 0 || txtUserPasswordAdmin.Text.Length == 0)
            {
                MessageBox.Show("نام کاربری و گذرواژه را وارد کنید.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                usersTableAdapter.InsertUserQuery(txtUserNameAdmin.Text, txtUserPasswordAdmin.Text);
                LoadUsers();
                MessageBox.Show("کاربر با موفقیت ثبت شد.");
            }
            catch
            {
                MessageBox.Show("خطا در ثبت کاربر", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnUpdateUser_Click(object sender, EventArgs e)
        {
            int userCode;
            MyShopDataSetTableAdapters.UsersTableAdapter usersTableAdapter = new MyShopDataSetTableAdapters.UsersTableAdapter();

            if (!int.TryParse(txtUserCodeAdmin.Text, out userCode))
            {
                MessageBox.Show("کاربر را از جدول انتخاب کنید.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (txtUserNameAdmin.Text.Length == 0 || txtUserPasswordAdmin.Text.Length == 0)
            {
                MessageBox.Show("نام کاربری و گذرواژه را وارد کنید.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                usersTableAdapter.UpdateUserQuery(txtUserNameAdmin.Text, txtUserPasswordAdmin.Text, userCode);
                LoadUsers();
                MessageBox.Show("کاربر با موفقیت ویرایش شد.");
            }
            catch
            {
                MessageBox.Show("خطا در ویرایش کاربر", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDeleteUser_Click(object sender, EventArgs e)
        {
            int userCode;
            MyShopDataSetTableAdapters.UsersTableAdapter usersTableAdapter = new MyShopDataSetTableAdapters.UsersTableAdapter();

            if (!int.TryParse(txtUserCodeAdmin.Text, out userCode))
            {
                MessageBox.Show("کاربر را از جدول انتخاب کنید.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                usersTableAdapter.DeleteUserQuery(userCode);
                LoadUsers();
                MessageBox.Show("کاربر با موفقیت حذف شد.");
            }
            catch
            {
                MessageBox.Show("خطا در حذف کاربر", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void goodsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {

        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private bool CheckCustomerFormValid()
        {
            int CustomerCode, CustomerMobile;
            if (txtCustomerCode.Text.Length <= 0 || !int.TryParse(txtCustomerCode.Text, out CustomerCode))
                return false;
            if (txtCustomerMobile.Text.Length <= 0 || !int.TryParse(txtCustomerMobile.Text, out CustomerMobile))
                return false;
            if (txtCustomerFirstName.Text.Length <= 0)
                return false;
            if (txtCustomerLastName.Text.Length <= 0)
                return false;
            return true;
        }

        private void SetCustomerInputVisibility()
        {
            if (CheckCustomerFormValid())
            {
                btnSaveCustomer.Enabled = true;
            }
            else
            {
                btnSaveCustomer.Enabled = false;
            }
        }

        private void txtCustomerCode_TextChanged(object sender, EventArgs e)
        {
            SetCustomerInputVisibility();
        }

        private void txtCustomerFirstName_TextChanged(object sender, EventArgs e)
        {
            SetCustomerInputVisibility();
        }

        private void txtCustomerLastName_TextChanged(object sender, EventArgs e)
        {
            SetCustomerInputVisibility();
        }

        private void txtCustomerMobile_TextChanged(object sender, EventArgs e)
        {
            SetCustomerInputVisibility();
        }

        private void lblFCustomerCode_Click(object sender, EventArgs e)
        {

        }
    }
}
