using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Security.Cryptography;

namespace Project_management_system
{
    public partial class frmClientProfile : Form
    {
        SqlDataReader rdr = null;

        DataTable dtable = new DataTable();
        SqlConnection con = null;
        SqlCommand cmd = null;
        ConnectionString cs = new ConnectionString();
       
        clsFunc cf = new clsFunc();
        string st1;
        string st2;
        public frmClientProfile()
        {
            InitializeComponent();
        }

        private void GroupBox3_Enter(object sender, EventArgs e)
        {

        }
        private void Autocomplete()
        {
            try
            {

                con = new SqlConnection(cs.ConDB);
                con.Open();


                string ct = "select distinct RTRIM(Categoryname) from Category ";

                cmd = new SqlCommand(ct);
                cmd.Connection = con;

                rdr = cmd.ExecuteReader();

                while (rdr.Read())
                {
                    cmbProjectType.Items.Add(rdr[0]);
                }
                con.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void frmClientProfile_Load(object sender, EventArgs e)
        {
            Autocomplete();

        }



        public static string GetUniqueKey(int maxSize)
        {
            char[] chars = new char[62];
            chars =
            "123456789".ToCharArray();
            byte[] data = new byte[1];
            RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
            crypto.GetNonZeroBytes(data);
            data = new byte[maxSize];
            crypto.GetNonZeroBytes(data);
            StringBuilder result = new StringBuilder(maxSize);
            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length)]);
            }
            return result.ToString();
        }
        private void auto()
        {
            ID.Text = "C-" + GetUniqueKey(3);
        }

        private void txtTotalPaid_TextChanged(object sender, EventArgs e)
        {
            int val1 = 0;
        
            int val3 = 0;
            int.TryParse(txtProjectCost.Text, out val1);
       
            int.TryParse(txtTotalPaid.Text, out val3);

            int I = (val1  - val3);

            txtPreviousDue.Text = I.ToString();
            txtGrandTotal.Text = val1.ToString();

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {

                if (txtProjectName.Text == "")
                {
                    MessageBox.Show("Please enter Project name", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtProjectName.Focus();
                    return;
                }
                if (cmbPaymentMode.Text == "")
                {
                    MessageBox.Show("Please Select Payment Mode", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtProjectName.Focus();
                    return;
                }

                if (txtClientName.Text == "")
                {
                    MessageBox.Show("Please enter ClientName", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtClientName.Focus();
                    return;
                }

                if (txtContactNo.Text == "")
                {
                    MessageBox.Show("Please enter ContactNo.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                   txtContactNo.Focus();
                    return;
                }

                if (cmbProjectType.Text == "")
                {
                    MessageBox.Show("Please Select ProjectCategory.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtContactNo.Focus();
                    return;
                }
            auto();
            con = new SqlConnection(cs.ConDB);
            con.Open();

            string cb = "insert into Client(ID, ClientName,Address, ProjectName,ContactNo,cost, GrandTotal, TotalPaid, ModeOfPayment,PaymentDate, PaymentModeDetails,PaymentDue,DueDate,Email,CategoryID) VALUES (@d1,@d2,@d3,@d4,@d5,@d6,@d7,@d8,@d9,@d10,@d11,@d12,@d13,@d14,@d15)";

            cmd = new SqlCommand(cb);

            cmd.Connection = con;
            cmd.Parameters.AddWithValue("@d1",ID.Text);
            cmd.Parameters.AddWithValue("@d2",txtClientName.Text);
            cmd.Parameters.AddWithValue("@d3", txtAddress.Text);
            cmd.Parameters.AddWithValue("@d4", txtProjectName.Text);
            cmd.Parameters.AddWithValue("@d5",txtContactNo.Text);
            cmd.Parameters.AddWithValue("@d6", txtProjectCost.Text);
            cmd.Parameters.AddWithValue("@d7", txtGrandTotal.Text);
            cmd.Parameters.AddWithValue("@d8", txtTotalPaid.Text);
            cmd.Parameters.AddWithValue("@d9", cmbPaymentMode.Text);
            cmd.Parameters.AddWithValue("@d10", dtpPaymentDate.Text);
            cmd.Parameters.AddWithValue("@d11", txtPaymentModeDetails.Text);
            cmd.Parameters.AddWithValue("@d12", txtPreviousDue.Text);
            cmd.Parameters.AddWithValue("@d13", txtDueDate.Text);
            cmd.Parameters.AddWithValue("@d14", txtEmail.Text);
            cmd.Parameters.AddWithValue("@d15", txtCategoryID.Text);
           
            cmd.ExecuteNonQuery();
            con.Close();
            st1 = lblUser.Text;
            st2 = "added the new Client '" +txtClientName.Text + "'";
            cf.LogFunc(st1, System.DateTime.Now, st2);
            MessageBox.Show("Successfully saved", "Record", MessageBoxButtons.OK, MessageBoxIcon.Information);

            btnSave.Enabled = false;
            }
             catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnUpdate_record_Click(object sender, EventArgs e)
      
        {
            try
            {
                con = new SqlConnection(cs.ConDB);
                con.Open();
       

                string cb = "update Client Set ClientName=@d2,Address=@d3, ProjectName=@d4,ContactNo=@d5,cost=@d6, GrandTotal=@d7, TotalPaid=@d8, ModeOfPayment=@d9,PaymentDate=@d10, PaymentModeDetails=@d11,PaymentDue=@d12,DueDate=@d13,Email=@d14,CategoryID=@d15 Where ID='" + ID.Text + "'";
                cmd = new SqlCommand(cb);
     
                cmd.Connection = con;
                cmd = new SqlCommand(cb);
              cmd.Connection = con;
            cmd.Parameters.AddWithValue("@d2",txtClientName.Text);
            cmd.Parameters.AddWithValue("@d3", txtAddress.Text);
            cmd.Parameters.AddWithValue("@d4", txtProjectName.Text);
            cmd.Parameters.AddWithValue("@d5",txtContactNo.Text);
            cmd.Parameters.AddWithValue("@d6", txtProjectCost.Text);
            cmd.Parameters.AddWithValue("@d7", txtGrandTotal.Text);
            cmd.Parameters.AddWithValue("@d8", txtTotalPaid.Text);
            cmd.Parameters.AddWithValue("@d9", cmbPaymentMode.Text);
            cmd.Parameters.AddWithValue("@d10", dtpPaymentDate.Text);
            cmd.Parameters.AddWithValue("@d11", txtPaymentModeDetails.Text);
            cmd.Parameters.AddWithValue("@d12", txtPreviousDue.Text);
            cmd.Parameters.AddWithValue("@d13", txtDueDate.Text);
            cmd.Parameters.AddWithValue("@d14", txtEmail.Text);
            cmd.Parameters.AddWithValue("@d15", txtCategoryID.Text);
                cmd.ExecuteNonQuery();
                con.Close();
                ClientRecords frm = new ClientRecords();
                frm.GetData();
               st1 = lblUser.Text;
                st2 = "Updated the client '" +txtClientName.Text + "'";
                cf.LogFunc(st1, System.DateTime.Now, st2);
                MessageBox.Show("Successfully updated", "Record", MessageBoxButtons.OK, MessageBoxIcon.Information);
                btnUpdate_record.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
       
        private void Reset()
        {
            txtClientName.Text = "";
            txtAddress.Text = "";
            txtContactNo.Text = "";
            txtDueDate.Text = DateTime.Today.ToString();
            txtEmail.Text= "";
            txtGrandTotal.Text= "";
            txtPaymentModeDetails.Text= "";
            txtPreviousDue.Text= "";
            txtProjectCost.Text= "";
            txtProjectName.Text= "";
            cmbPaymentMode.SelectedIndex=-1;
            cmbProjectType.SelectedIndex =-1;
            txtTotalPaid.Text= "";
            dtpPaymentDate.Text = DateTime.Today.ToString();
            ID.Text = "";
            btnSave.Enabled = true;
            btnDelete.Enabled = false;
            btnUpdate_record.Enabled = false;
            txtClientName.Focus();
        }
        private void delete_records()
        {

            try
            {

                int RowsAffected = 0;
                con = new SqlConnection(cs.ConDB);
                con.Open();
                string cq = "delete from Client where ID='" + ID.Text + "'";
                cmd = new SqlCommand(cq);
                cmd.Connection = con;
                RowsAffected = cmd.ExecuteNonQuery();
                if (RowsAffected > 0)
                {
                    st1 = lblUser.Text;
                    st2 = "deleted the client '" + txtClientName.Text+ "'";
                    cf.LogFunc(st1, System.DateTime.Now, st2);
                    MessageBox.Show("Successfully deleted", "Record", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Reset();
                    Autocomplete();
                }
                else
                {
                    MessageBox.Show("No Record found", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Reset();
                    Autocomplete();
                }
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            delete_records();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Hide();
            ClientRecords frm = new ClientRecords();
            frm.lblUser.Text = lblUser.Text;
            frm.Show();
        }

        private void NewRecord_Click(object sender, EventArgs e)
        {
            Reset();
        }

        private void txtTotalPaid_Validating(object sender, CancelEventArgs e)
        {
            int val1 = 0;
            int val2 = 0;
   
            int.TryParse(txtTotalPaid.Text, out val1);
            int.TryParse(txtGrandTotal.Text, out val2);
    
            if (val1 > val2)
            {
                MessageBox.Show("Total Paid can not be more than Grand Total", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtTotalPaid.Focus();
            }
        }

        private void txtEmail_Validating(object sender, CancelEventArgs e)
        {
            System.Text.RegularExpressions.Regex rEMail = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
            if (txtEmail.Text.Length > 0)
            {
                if (!rEMail.IsMatch(txtEmail.Text))
                {
                    MessageBox.Show("invalid email address", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtEmail.SelectAll();
                    e.Cancel = true;
                }
            }
        }

        private void txtContactNo_Validating(object sender, CancelEventArgs e)
        {
            if (txtContactNo.TextLength < 10)
            {
                MessageBox.Show("Contact no. must contains 10 digits", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtContactNo.Focus();
            }
            if (txtContactNo.TextLength > 15)
            {
                MessageBox.Show("Less than 15 digits are allowed", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtContactNo.Focus();
            }
        }

        private void txtContactNo_KeyPress(object sender, KeyPressEventArgs e)
        {
           
        }

        private void txtProjectCost_TextChanged(object sender, EventArgs e)
        {
            int val1 = 0;

            int val3 = 0;
            int.TryParse(txtProjectCost.Text, out val1);

            int.TryParse(txtTotalPaid.Text, out val3);

            int I = (val1 - val3);

            txtPreviousDue.Text = I.ToString();
            txtGrandTotal.Text = val1.ToString();
        }

        private void cmbProjectType_SelectedIndexChanged(object sender, EventArgs e)
        {
             try
            {
                con = new SqlConnection(cs.ConDB);

                con.Open();
                cmd = con.CreateCommand();
                cmd.CommandText = "SELECT ID from Category WHERE CategoryName = '" + cmbProjectType.Text + "'";  
                rdr = cmd.ExecuteReader();

                if (rdr.Read())
                {
                    txtCategoryID.Text = rdr.GetValue(0).ToString().Trim();
                }
                if ((rdr != null))
                {
                    rdr.Close();
                }
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        }
    }

    

