//commit changes
        protected void Button4_Click(object sender, EventArgs e)
        {
            using (lucia_dataEntities allData = new lucia_dataEntities())
            {
                int account_id = Convert.ToInt32(Request.Cookies["account_id"].Value);
                int customer_id = Convert.ToInt32(Request.Cookies["customer_id"].Value);
                int emp_id = Convert.ToInt32(Request.Cookies["empid"].Value);

                var account = from acc in allData.Accounts
                              where acc.id == account_id
                              select acc;
                foreach (var acc in account)
                {
                    if (String.IsNullOrEmpty(acc.comments))
                        acc.comments = "";
                    acc.status = status;
                    acc.comments += TextBox1.Text;
                    acc.credit_limit = Convert.ToDecimal(creditLimit.Text);
                }

                //create log
                operationLog log = operationLog.CreateoperationLog(emp_id, customer_id, "Modify account:"+logDetails, 1,DateTime.Now);
                allData.AddTooperationLogs(log);

                allData.SaveChanges();
                statusMSG.ForeColor = System.Drawing.Color.FromName("green");
                statusMSG.Text="Changes made successful! You may return now.";
                Button4.Enabled = false;
            }
        }
 protected void Button1_Click(object sender, EventArgs e)
 {
     int account_id = Convert.ToInt32(Request.Cookies["account_id"].Value);
     using (lucia_dataEntities allData = new lucia_dataEntities())
     {
         var result = from account in allData.Accounts
                      where account.id == account_id
                      select account;
         foreach (var r in result)
         {
             if (r.credit_limit >= Convert.ToDecimal(TextBox1.Text))
             {
                 r.credit_limit = Convert.ToDecimal(TextBox1.Text);
                 Button1.Enabled = false;
                 confirmation.Text = "Submission successful! New credit limit is effective.";
             }
             else
             {
                 Credit_Limit_Application newApp = Credit_Limit_Application.CreateCredit_Limit_Application(1, Convert.ToDecimal(TextBox1.Text), "submitted", account_id);
                 allData.AddToCredit_Limit_Application(newApp);
                 Button1.Enabled = false;
                 confirmation.Text = "Submission successful! Please wait for 14 days for processing. Click 'back' button to go back to customer page";
             }
         }
         allData.SaveChanges();
     }
 }
        //reject application
        protected void Button3_Click(object sender, EventArgs e)
        {
            int account_number = Convert.ToInt32(Request.Cookies["account_id"].Value);
            int customer_id = 0;
            int empid = Convert.ToInt32(Request.Cookies["empid"].Value);
            int app_id = 0;
            using (lucia_dataEntities allData = new lucia_dataEntities())
            {
                var credit_application = from ca in allData.Credit_Limit_Application
                                         where ca.acc_id == account_number
                                         select ca;
                foreach (var r in credit_application)
                {
                    r.status = "rejected";
                    app_id = r.id;
                }
                var accounts = from acc in allData.Accounts
                               where acc.id == account_number
                               select acc;
                foreach (var a in accounts)
                    customer_id = a.cust_id;

                //create log
                operationLog log = operationLog.CreateoperationLog(empid, customer_id, "reject credit limit application: "+app_id.ToString(), 1,DateTime.Now);
                allData.AddTooperationLogs(log);

                allData.SaveChanges();
            }
            Button2.Enabled = false;
            Button3.Enabled = false;
            reject_msg.Enabled = true;
            reject_msg.Visible = true;
            reject_msg.Text = "Rejection successful, please return back to management page.";
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            int account_id = Convert.ToInt32(Request.Cookies["account_id"].Value);
            using (lucia_dataEntities allData = new lucia_dataEntities())
            {
                var result = from account in allData.Accounts
                             where account.id == account_id
                             select account;
                foreach (var r in result)
                {
                    credit_limit.Text = "$" + r.credit_limit.ToString();

                    //retrieve all credit limit applications for given customer
                    var applications = from app in allData.Credit_Limit_Application
                                       where app.acc_id == account_id
                                       where app.status == "submitted"
                                       select app;
                    int count = 0;
                    decimal amount = 0;
                    String status = "";
                    foreach (var app in applications)
                    {
                        amount = app.desired_credit_limit;
                        status = app.status;
                        count++;
                    }
                    //Recent application submitted.
                    if (count != 0)
                    {
                        Panel2.Enabled = true;
                        Panel2.Visible = true;
                        appliedCredit.Text = amount.ToString();
                        creditStatus.Text = status;
                    }
                    else
                    {
                        //Customer can submit new application
                        Panel1.Enabled = true;
                        Panel1.Visible = true;
                    }

                    //display application history
                    var history = from app in allData.Credit_Limit_Application
                                  where app.acc_id == account_id
                                  select app;
                    int history_count = 0;
                    foreach (var h in history)
                        history_count++;
                    if (history_count != 0)
                    {
                        Panel4.Enabled = true;
                        Panel4.Visible = true;
                        GridView1.DataSource = history;
                        GridView1.DataBind();
                    }

                }
            }
        }
        //save card details
        protected void Button6_Click(object sender, EventArgs e)
        {
            int card_no = Convert.ToInt32(Request.Cookies["card_number"].Value);
            int customer_number = 0;
            if (product_changed)
            {
                using (lucia_dataEntities allData = new lucia_dataEntities())
                {
                    var result = from reference in allData.Product_Card_Reference
                                 where reference.card_no == card_no
                                 select reference;
                    //delete all old references first
                    foreach (var r in result)
                    {
                        allData.DeleteObject(r);
                    }
                    //create new reference relations
                    for (int j = 0; j < purchaseOptions.Items.Count; j++)
                    {
                        if (purchaseOptions.Items[j].Selected)
                        {
                            Product_Card_Reference rf = Product_Card_Reference.CreateProduct_Card_Reference(card_no, purchaseOptions.Items[j].Text, j);
                            allData.AddToProduct_Card_Reference(rf);
                        }
                    }

                    allData.SaveChanges();
                }

            }
            //save status
            using (lucia_dataEntities allData = new lucia_dataEntities())
            {
                var result = from card in allData.Cards
                             where card.card_no == card_no
                             select card;
                foreach (var r in result)
                {
                    customer_number = r.cust_id;
                    r.status = status.Text;
                }
                if (Request.Cookies["viewMode"].Value == "customerEdit")
                {
                    operationLog log = operationLog.CreateoperationLog(customer_number,customer_number,"Card modification on "+card_no.ToString()+logDetails,1,DateTime.Now);
                    allData.AddTooperationLogs(log);
                    allData.SaveChanges();
                }
                else
                {
                    int empid =Convert.ToInt32(Request.Cookies["empid"].Value);
                    operationLog log = operationLog.CreateoperationLog(empid, customer_number, "Card modification on "+card_no.ToString()+logDetails, 1,DateTime.Now);
                    allData.AddTooperationLogs(log);
                    allData.SaveChanges();
                }
            }
            Change_confirmation.Text = "All changes have been saved!";
            Button6.Enabled = false;
        }
        //search starts
        protected void Button1_Click(object sender, EventArgs e)
        {
            record.Text = "";
            using (lucia_dataEntities allData = new lucia_dataEntities())
            {
                if (RadioButtonList1.SelectedValue == "By Account Number")
                {
                    int account_number = Convert.ToInt32(TextBox1.Text);
                    var account = from acc in allData.Accounts
                                  from cust in allData.Customers
                                  where acc.id == account_number
                                  where acc.cust_id == cust.id
                                  select new { CustomerID = cust.id, AccountID = acc.id, AccountStatus = acc.status, FirstName = cust.contact_first_name, LastName = cust.contact_last_name, CreditLimit = acc.credit_limit };
                    Panel2.Enabled = true;
                    Panel2.Visible = true;
                    int count = 0;
                    foreach (var r in account)
                        count++;
                    if (count == 0)
                        record.Text = "No record found: customer may not have account created. Please note: if a customer has not been approved to have an account yet, you may want to try search by customer option instead.";
                    GridView1.DataSource = account;
                    GridView1.DataBind();

                }
                if (RadioButtonList1.SelectedValue == "By Customer Number")
                {
                    int customer_number = Convert.ToInt32(TextBox1.Text);
                    var customer = from cust in allData.Customers
                                   where cust.id == customer_number
                                   select new { CustomerID = cust.id, FirstName = cust.contact_first_name, LastName = cust.contact_last_name };
                    int count = 0;
                    Panel2.Enabled = true;
                    Panel2.Visible = true;
                    foreach (var r in customer)
                        count++;
                    if (count == 0)
                        record.Text = "No record found: there are no customer records associated with given Customer ID can ben retrieved, please double check your input.";
                    GridView1.DataSource = customer;
                    GridView1.DataBind();
                }
                if (RadioButtonList1.SelectedValue == "By First Name")
                {
                    var customer = from cust in allData.Customers
                                   where cust.contact_first_name == TextBox1.Text
                                   select new { CustomerID = cust.id, FirstName = cust.contact_first_name, LastName = cust.contact_last_name };
                    int count = 0;
                    Panel2.Enabled = true;
                    Panel2.Visible = true;
                    foreach (var r in customer)
                        count++;
                    if (count == 0)
                        record.Text = "No record found: there are no customer records associated with given Customer name can ben retrieved, please double check your input.";
                    GridView1.DataSource = customer;
                    GridView1.DataBind();

                }
            }
        }
        protected void submit_Click(object sender, EventArgs e)
        {
            string passworda = "aaa";
            string usernamea = "aaa";
            string email = "aaa";
            string welcomeName = " ";
            string hello = "This is password recovery of APJ ChemCrad";
            int account_id = Convert.ToInt32(username.Text);
            using (lucia_dataEntities alldata = new lucia_dataEntities())
            {
                var password = from acc in alldata.Accounts
                               from cust in alldata.Customers
                               where account_id== acc.id
                               where acc.cust_id == cust.id
                               select new { acc,cust };

                foreach (var r in password)
                {
                    passworda = r.acc.password;
                    usernamea = Convert.ToString(r.acc.id);
                    email = r.cust.email;
                    welcomeName = r.cust.contact_first_name + " " + r.cust.contact_last_name;

                }

                if (usernamea == username.Text)
                {
                    MailMessage newMsg = new MailMessage();
                    newMsg.To.Add(new MailAddress(email, hello));
                    newMsg.From = new MailAddress("*****@*****.**", "APJ Chem Card");
                    newMsg.Subject = hello;
                    newMsg.Body = "Dear," + welcomeName  + ":\n "
                        + "your user name is: "+usernamea + "\n "
                        +" your password is :" + passworda;

                    try
                    {
                        SmtpClient smtp = new SmtpClient();
                        smtp.Host = "smtp.monash.edu.au";
                        smtp.Send(newMsg);
                        lblMail.Text = "Mail Successfully Sent";
                    }
                    catch (Exception exc)
                    {
                        lblMail.Text = exc.Message;
                    }

                }
                else
                {
                    lblMail.Text = "There is no matching record";
                }

            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            string emppass = "******";
            string empida = " ";
            string empemail = " ";
            string hello = "This is password recovery of APJ ChemCrad for Employee";
            string welcomeName = "";
            int employeeID = Convert.ToInt32(empid.Text);
            using (lucia_dataEntities alldata = new lucia_dataEntities())
            {
                var passwords = from acc in alldata.Accounts
                                from emp in alldata.Employees
                                where acc.id == emp.id
                                select new { acc , emp};
                foreach (var r in passwords)
                {
                    emppass = r.emp.password;
                    empida = Convert.ToString(r.emp.id);
                    empemail = r.emp.email;
                    welcomeName = r.emp.f_name + " " + r.emp.l_name;
                }

                if (empida == empid.Text)
                {
                    MailMessage newMsg = new MailMessage();
                    newMsg.To.Add(new MailAddress(empemail, hello));
                    newMsg.From = new MailAddress("*****@*****.**", "APJ Chem Card");
                    newMsg.Subject = hello;
                    newMsg.Body = "Dear," + welcomeName + ":\n "
                        + "your user name is: " + empida + "\n "
                        + " your password is :" + emppass;

                    try
                    {
                        SmtpClient smtp = new SmtpClient();
                        smtp.Host = "smtp.monash.edu.au";
                        smtp.Send(newMsg);
                        Label2.Text = "Mail Successfully Sent";
                    }
                    catch (Exception exc)
                    {
                        Label2.Text = exc.Message;
                    }

                }
                else
                {

                    Label2.Text = "There is no matching record";
                }

            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            int employee_id = Convert.ToInt32(Request.Cookies["empid"].Value);
            using (lucia_dataEntities allData = new lucia_dataEntities())
            {
                var result = from log in allData.operationLogs
                             where log.fromOperator==employee_id
                             select log;
                GridView1.DataSource = result;
                GridView1.DataBind();

            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (Request.Cookies["viewMode"].Value.Contains("employee"))
            {

                int emp_id = Convert.ToInt32(Request.Cookies["empid"].Value);
                using (lucia_dataEntities alldata = new lucia_dataEntities())
                {
                    var result = from emp in alldata.Employees
                                 where emp.id == emp_id
                                 where emp.password == TextBox1.Text
                                 select emp;
                    if (Page.IsValid)
                    {
                        foreach (var a in result)
                        {
                            a.password = TextBox3.Text;
                        }
                        Label1.Text = "Your password has been sucessfully changed";
                        alldata.SaveChanges();
                    }
                }

            }
            else if (Request.Cookies["viewMode"].Value.Contains("customer"))
            {
                int account_id = Convert.ToInt32(Request.Cookies["account_id"].Value);
                using (lucia_dataEntities alldata = new lucia_dataEntities())
                {
                    var result = from acc in alldata.Accounts
                                 where acc.id == account_id
                                 where acc.password == TextBox1.Text
                                 select acc;
                    if (Page.IsValid)
                    {
                        foreach (var a in result)
                        {
                            a.password = TextBox3.Text;
                        }
                        Label1.Text = "Your password has been sucessfully changed";
                        alldata.SaveChanges();
                    }
                }
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            //int cust_id = 0;
            int defaultID = 0;
            lucia_dataEntities allData = new lucia_dataEntities();
            //Create customer address first;
            Cust_Postal_Address cust_address = Cust_Postal_Address.CreateCust_Postal_Address(defaultID, DropDownList2.Text, txSuburb.Text, txStreet.Text, Convert.ToInt32(txStreetNumber.Text), Convert.ToInt32(txPostCode.Text));
            //assign optional unit number to customer
            if (!String.IsNullOrEmpty(txUnitNumber.Text))
                cust_address.unit_number = Convert.ToInt32(txUnitNumber.Text);
            //add customer address to database set
            allData.AddToCust_Postal_Address(cust_address);

            defaultID++;
            //now create customer, reference cust_address
            Customer customer = Customer.CreateCustomer(defaultID, txBusinessName.Text, txTradingName.Text, Convert.ToInt32(txBusinessYear.Text), txABN.Text, txNatureOperation.Text, cust_address.id, txFirstName.Text, txLastName.Text, txPosition.Text, txPhoneNumber.Text, txMobileNumber.Text, txEmail.Text, Convert.ToDecimal(txCreditLimit.Text), DropDownList1.Text);
            customer.Cust_Postal_Address = cust_address;
            //assign optional middle name for customer
            if (!String.IsNullOrEmpty(txMiddleName.Text))
                customer.contact_middle_name = txMiddleName.Text;
            //assign optional fax
            if (!String.IsNullOrEmpty(txFaxNumber.Text))
                customer.fax_no = txFaxNumber.Text;
            //add customer to database set
            allData.AddToCustomers(customer);

            defaultID++;

            allData.SaveChanges();

            allData.Dispose();

            lucia_dataEntities alldata = new lucia_dataEntities();
            int customer_ida = customer.id;
            Account account = Account.CreateAccount(defaultID, "active", Convert.ToDecimal(txCreditLimit.Text), "0000", Convert.ToDecimal(txCreditLimit.Text), customer_ida);
            alldata.AddToAccounts(account);
            //create log
            int empid = Convert.ToInt32(Request.Cookies["empid"].Value);
            alldata.SaveChanges();
            operationLog log = operationLog.CreateoperationLog(empid, account.cust_id, "create new customer", 1, DateTime.Now);
            alldata.AddTooperationLogs(log);
            alldata.SaveChanges();
            Label22.Text = "Your detail has been successfully saved." + account.id;
            alldata.Dispose();
        }
 protected void Button1_Click(object sender, EventArgs e)
 {
     Label1.Text = "";
     using (lucia_dataEntities allData = new lucia_dataEntities())
     {
         int application_id = Convert.ToInt32(TextBox1.Text);
         var result = from applicaton in allData.Applications
                      where applicaton.id == application_id
                      select applicaton;
         GridView1.DataSource = result;
         GridView1.DataBind();
         int count = 0;
         foreach (var r in result)
             count++;
         if (count == 0)
             Label1.Text = "No records found.";
     }
 }
        public IQueryable<reportViewModel> getTransaction(String fromDt, String toDt, int? customerNumber, int? cardNumber)
        {
            if (String.IsNullOrEmpty(fromDt) || String.IsNullOrEmpty(toDt))
            {
                fromDt = "01/01/0001 12:00:00 AM";
                toDt = "01/01/0001 12:00:00 AM";
            }
            fromDt = fromDt.Split(' ')[0];
            toDt = toDt.Split(' ')[0];
            int fromDay = Convert.ToInt32(fromDt.Split('/')[0]);
            int fromMonth = Convert.ToInt32(fromDt.Split('/')[1]);
            int fromYear = Convert.ToInt32(fromDt.Split('/')[2]);
            int toDay = Convert.ToInt32(toDt.Split('/')[0]);
            int toMonth = Convert.ToInt32(toDt.Split('/')[1]);
            int toYear = Convert.ToInt32(toDt.Split('/')[2]);

            DateTime fromDate = new DateTime(fromYear, fromMonth, fromDay);
            DateTime toDate = new DateTime(toYear, toMonth, toDay);

            lucia_dataEntities allData = new lucia_dataEntities();
            var transactions = from tr in allData.Transactions
                               from cd in allData.Cards
                               from lc in allData.Stations
                               where cd.card_no==cardNumber
                               where lc.id == tr.station_id
                               where cd.card_no == tr.card_no
                               where tr.customer_id == customerNumber
                               where tr.purchase_date >= fromDate
                               where tr.purchase_date <= toDate
                               select new reportViewModel
                               {
                                   cardNumber = tr.card_no,
                                   dateOfPurchase = tr.purchase_date,
                                   product = tr.prod_name,
                                   unit_price_excl_gst = tr.product_unit_price,
                                   unit_price_incl_gst = tr.uni_GST,
                                   total_price_excl_gst = tr.total_price,
                                   total_price_incl_gst = tr.total_GST,
                                   stationLocation = lc.location,
                                   cardType = cd.Card_type,
                                   Name_Rego = cd.register
                               };
            return transactions.AsQueryable();
        }
 //########################################searching performed here############################################
 protected void Button1_Click1(object sender, EventArgs e)
 {
     Label1.Text = "";
     using (lucia_dataEntities allData = new lucia_dataEntities())
     {
         var result = from inv in allData.Invoices
                      where inv.customer_id == customerNumber
                      where inv.from_inv_period >= fromDate
                      where inv.to_inv_period <= toDate
                      select inv;
         GridView1.DataSource = result;
         GridView1.DataBind();
         int i = 0;
         foreach (var r in result)
             i++;
         if (i == 0)
             Label1.Text = "No records found!";
     }
 }
        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (Request.Cookies["viewMode"].Value.Contains("employee"))
            {
                int emp_id = Convert.ToInt32(Request.Cookies["empid"].Value);
                using (lucia_dataEntities alldata = new lucia_dataEntities())
                {
                    var result = from emp in alldata.Employees
                                 where emp.id == emp_id
                                 where emp.password == TextBox1.Text
                                 select emp;
                    int check = 0;

                    foreach (var r in result)
                    {
                        check++;
                    }
                    if (check == 0)
                        args.IsValid = false;
                }

            }
            else if (Request.Cookies["viewMode"].Value.Contains("customer"))
            {

                int account_id = Convert.ToInt32(Request.Cookies["account_id"].Value);
                using (lucia_dataEntities alldata = new lucia_dataEntities())
                {
                    var result = from acc in alldata.Accounts
                                 where acc.id == account_id
                                 where acc.password == TextBox1.Text
                                 select acc;
                    int check = 0;

                    foreach (var r in result)
                    {
                        check++;
                    }
                    if (check == 0)
                        args.IsValid = false;
                }
            }
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     int customer_id = Convert.ToInt32(Request.Cookies["customer_id"].Value);
     using (lucia_dataEntities allData = new lucia_dataEntities())
     {
         var result = from card in allData.Cards
                      where card.cust_id == customer_id
                      where card.status!="closed"
                      select card;
         GridView1.DataSource = result;
         GridView1.DataBind();
     }
     if (Request.Cookies["viewMode"].Value == "employeeSearchView")
     {
         Button1.Enabled = false;
         Button1.Visible = false;
         Button3.Enabled = true;
         Button3.Visible = true;
     }
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            int employee_id = Convert.ToInt32(Request.Cookies["empid"].Value);
            using (lucia_dataEntities allData = new lucia_dataEntities())
            {

                var result = from app in allData.Credit_Limit_Application
                             where app.status == "submitted"
                             select app;
                int count = 0;
                foreach (var r in result)
                    count++;
                if (count == 0)
                    Label1.Text = "No records found.";
                else
                    Label1.Text = "Please select one application item to process.";

                GridView1.DataSource = result;
                GridView1.DataBind();
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            using (lucia_dataEntities allData = new lucia_dataEntities())
            {
                String product = productdd.SelectedValue;
                int stationid = Convert.ToInt32(stationdd.SelectedValue);
                int cardNumber = Convert.ToInt32(carddd.SelectedValue);
                decimal qtty = Convert.ToDecimal(quantity.SelectedValue);
                decimal uni_price = 0;
                decimal uni_price_GST = 0;
                decimal total_price = 0;
                decimal total_price_GST = 0;
                int customer_id = 0;
                var prd = from p in allData.Product_Option
                          where p.name == product
                          select p;
                foreach (var p in prd)
                {
                    uni_price = p.pro_op_price;
                    uni_price_GST = uni_price / 11;
                }
                total_price = uni_price * qtty;
                total_price_GST = uni_price_GST * qtty;

                var cd = from c in allData.Cards
                         where c.card_no == cardNumber
                         select c;
                foreach (var c in cd)
                {
                    customer_id = c.cust_id;
                }

                Transaction tra = Transaction.CreateTransaction(1, product, RandomDay(), cardNumber, qtty, uni_price, uni_price_GST, total_price, total_price_GST, customer_id);

                allData.AddToTransactions(tra);
                tra.station_id = stationid;
                allData.SaveChanges();
                Label1.Text = "Successful.";
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            using (lucia_dataEntities allData = new lucia_dataEntities())
            {
                if (RadioButtonList1.SelectedValue == "By First Name")
                {
                    var result = from emp in allData.Employees
                                 from add in allData.Emp_Add
                                 where emp.emp_add_id == add.id
                                 where emp.f_name == TextBox1.Text
                                 select new { ID = emp.id, FirstName = emp.f_name, LastName = emp.l_name, JobDescription = emp.job_description, UnitNumber = add.unit_number, StreetNumber = add.street_number, Street = add.street, State = add.state, PhoneNumber = emp.work_phone };

                    int count = 0;
                    foreach (var r in result)
                        count++;
                    if (count == 0)
                        warning.Text = "No records can be found.";
                    GridView1.DataSource = result;
                    GridView1.DataBind();

                }
                if (RadioButtonList1.SelectedValue == "By ID")
                {
                    int employeeID= Convert.ToInt32(TextBox1.Text);
                    var result = from emp in allData.Employees
                                 from add in allData.Emp_Add
                                 where emp.emp_add_id==add.id
                                 where emp.id==employeeID
                                 select new { ID = emp.id, FirstName = emp.f_name, LastName = emp.l_name, JobDescription = emp.job_description, UnitNumber = add.unit_number, StreetNumber = add.street_number, Street = add.street, State = add.state };
                    int count = 0;
                    foreach (var r in result)
                        count++;
                    if (count == 0)
                        warning.Text = "No records can be found.";
                    GridView1.DataSource = result;
                    GridView1.DataBind();

                }
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            Label1.Text = "Start streamlining, this may take a while, please wait .....";
            using (lucia_dataEntities allData = new lucia_dataEntities())
            {
                foreach (Card cd in allData.Cards)
                {
                    //get account number
                    foreach (Account acc in allData.Accounts)
                    {
                        if (cd.cust_id == acc.cust_id)
                            cd.acc_id = acc.id;
                    }

                    //get cardholder details and person type
                    foreach (Cardholder ch in allData.Cardholders)
                    {
                        if (ch.card_no == cd.card_no)
                        {
                            cd.Card_type = "Person";
                            cd.register = ch.name;
                        }
                    }

                    //get vech details and veichle type
                    foreach (Vehicle v in allData.Vehicles)
                    {
                        if (v.card_no == cd.card_no)
                        {
                            cd.Card_type = "Vehicle";
                            cd.register = v.registration_no;
                        }
                    }
                }
                allData.SaveChanges();
            }
            Label1.Text = "Successful!";
        }
        //approve application
        protected void Button2_Click(object sender, EventArgs e)
        {
            int account_number = Convert.ToInt32(Request.Cookies["account_id"].Value);
            using (lucia_dataEntities allData = new lucia_dataEntities())
            {
                int customer_id = 0;
                int empid = Convert.ToInt32(Request.Cookies["empid"].Value);
                int app_id = 0;
                var credit_application = from ca in allData.Credit_Limit_Application
                                         where ca.acc_id == account_number
                                         select ca;
                var result = from account in allData.Accounts
                             where account.id == account_number
                             select account;
                foreach (var r in result)
                {
                    r.credit_limit = Convert.ToDecimal(desired_limit.Text);
                    customer_id = r.cust_id;
                }
                foreach (var r in credit_application)
                {
                    app_id = r.id;
                    r.status = "approved";
                }

                //create log
                operationLog log = operationLog.CreateoperationLog(empid, customer_id, "approved credit limit application: "+app_id.ToString(), 1,DateTime.Now);
                allData.AddTooperationLogs(log);
                allData.SaveChanges();
            }
            Button2.Enabled = false;
            Button3.Enabled = false;
            Approve_msg.Enabled = true;
            Approve_msg.Visible = true;
            Approve_msg.Text = "Approval successful, please return back to management page.";
        }
        //Submit button clicked here, so all reference check status needs to be saved
        protected void Button1_Click(object sender, EventArgs e)
        {
            //This variable is used to retrieve proper account number for next page
            //Please note, this variable should only be accessed when successful is true
            //Which means an account item has been created!
            Account ac = new Account();

            using (lucia_dataEntities allData = new lucia_dataEntities())
            {
                int customer_id = Convert.ToInt32(Request.Cookies["selected_customer"].Value);
                int application_id = Convert.ToInt32(Request.Cookies["selected_application"].Value);
                var result = from customer in allData.Customers
                             join application in allData.Applications
                             on customer.id equals application.cust_id
                             where customer.id == customer_id
                             select new { customer, application };
                //This number is used to detect any bugs that may duplicate records
                int i = 0;
                Boolean successful = false;
                foreach (var r in result)
                {
                    i++;
                    //An error is detected!
                    if (i != 1 || r.application.id != application_id)
                    {
                        Response.Cookies["error"].Value = "applicationProcessingError";
                        Response.Redirect("~/applicationManagement/ErrorPage.aspx");
                        return;
                    }

                    //now assign all check fields accordingly
                    r.application.credit_check = get_check(CreditCheck.Checked);
                    r.application.reference_check = get_check(referCheck.Checked);
                    r.application.preliminary_check = get_check(pCheck.Checked);
                    r.application.final_check = get_check(fCheck.Checked);
                    //check if all process checks are completed
                    if (CreditCheck.Checked && referCheck.Checked && pCheck.Checked && fCheck.Checked)
                    {
                        //all checks completed, so create new account;
                        Account account = Account.CreateAccount(i, "active", r.customer.monthly_credit_limit, "0000", r.customer.monthly_credit_limit, r.customer.id);
                        allData.AddToAccounts(account);
                        ac = account;
                        r.application.status = "approved";
                        successful = true;

                    }
                }
                allData.SaveChanges();

                if (successful)
                {
                    MailMessage newMsg = new MailMessage();
                    newMsg.To.Add(new MailAddress(emaila, hello));
                    newMsg.From = new MailAddress("*****@*****.**", "APJ Chem Card");
                    newMsg.Subject = hello;
                    newMsg.Body = "Dear," + usernamea + ":\n "
                        + "Congratulations! Your application has for APJ ChemCard account has been approved.\n " +
                    "Please use the following login details to log into our online system to get access to a vast number of exciting services we are currently offering.\n  User Name:" + usernamea + "\n password:"******"\n\n\n Sincerely\n  APJ";

                    try
                    {
                        SmtpClient smtp = new SmtpClient();
                        smtp.Host = "smtp.monash.edu.au";
                        smtp.Send(newMsg);

                    }
                    catch (Exception exc)
                    {

                    }
                    Response.Cookies["account"].Value = ac.id.ToString();
                    //create log here

                    int empid = Convert.ToInt32(Request.Cookies["empid"].Value);
                    operationLog log = operationLog.CreateoperationLog(empid, customer_id, "New account application approved for customer " + customer_id.ToString(), 1, DateTime.Now);
                    allData.AddTooperationLogs(log);
                    allData.SaveChanges();

                    Response.Redirect("~/applicationManagement/accountSuccessful.aspx");
                }
                else
                {
                    Response.Redirect("~/applicationManagement/applicationProcessConfirmation.aspx");
                    int empid = Convert.ToInt32(Request.Cookies["empid"].Value);
                    operationLog log = operationLog.CreateoperationLog(empid, customer_id, "New account application progress saved for customer " + customer_id.ToString(), 1, DateTime.Now);
                    allData.AddTooperationLogs(log);
                    allData.SaveChanges();
                }
            }
        }
 protected void reject_application(object sender, EventArgs e)
 {
     using (lucia_dataEntities allData = new lucia_dataEntities())
     {
         int application_id = Convert.ToInt32(Request.Cookies["selected_application"].Value);
         int customer_id = 0;
         var result = from application in allData.Applications
                      where application.id == application_id
                      select application;
         foreach (var r in result)
         {
             customer_id = r.cust_id;
             r.status = "rejected";
         }
         int empid = Convert.ToInt32(Request.Cookies["empid"].Value);
         operationLog log = operationLog.CreateoperationLog(empid, customer_id, "New account application rejected for customer " + customer_id.ToString(), 1, DateTime.Now);
         allData.AddTooperationLogs(log);
         allData.SaveChanges();
         Response.Redirect("~/applicationManagement/applicationReject.aspx");
     }
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = Request.Cookies["selected_application"].Value + " with Customer ID: " + Request.Cookies["selected_customer"].Value;
            int customer_id = Convert.ToInt32(Request.Cookies["selected_customer"].Value);
            int application_id = Convert.ToInt32(Request.Cookies["selected_application"].Value);
            Boolean success = true;
            Customer selected_customer = new Customer();
            if (!IsPostBack)
            {
                using (lucia_dataEntities allData = new lucia_dataEntities())
                {
                    //This result have both customer and application
                    var result = from customer in allData.Customers
                                 join application in allData.Applications
                                 on customer.id equals application.cust_id
                                 where customer.id == customer_id
                                 select new { customer, application };
                    //This result_reference includes only reference table

                    var result_reference = from dir in allData.Trade_Reference
                                           where dir.app_id == application_id
                                           select dir;

                    int i = 0;

                    foreach (var r in result)
                    {

                        applicationID.Text = r.customer.id.ToString();
                        registerName.Text = r.customer.registered_business_name;
                        tradingName.Text = r.customer.trading_name;
                        yearStarts.Text = r.customer.year_of_business_commenced.ToString();
                        ABN.Text = r.customer.ABN_ACN;
                        nature.Text = r.customer.nature_of_operation;
                        name.Text = r.customer.contact_first_name + " " + r.customer.contact_middle_name + " " + r.customer.contact_last_name;
                        position.Text = r.customer.position;
                        phoneNo.Text = r.customer.phone_no;
                        fax.Text = r.customer.fax_no;
                        mobile.Text = r.customer.mobile_no;
                        email.Text = r.customer.email;
                        credit.Text = r.customer.monthly_credit_limit.ToString();
                        selected_customer = r.customer;
                        usernamea = r.customer.contact_first_name + " " + r.customer.contact_middle_name + " " + r.customer.contact_last_name;
                        emaila =  email.Text;
                        passworda = "0000";
                        //now display address details for current customer
                        address.Text = "";
                        if (!String.IsNullOrEmpty(r.customer.Cust_Postal_Address.unit_number.ToString()))
                            address.Text += r.customer.Cust_Postal_Address.unit_number.ToString() + "/";
                        address.Text += r.customer.Cust_Postal_Address.street_number.ToString() + "/" + r.customer.Cust_Postal_Address.street + "/" + r.customer.Cust_Postal_Address.suburb + "/" + r.customer.Cust_Postal_Address.state + "/" + r.customer.Cust_Postal_Address.cust_postal_add_code.ToString();
                        //now display payment details for current customer
                        if (!String.IsNullOrEmpty(r.application.payment_option))
                        {
                            //Now there might be a payment item
                            //#########NEED TO FURTHER VALIDATE THIS PART
                            Label18.Text = "";
                            String payment_option = r.application.payment_option;
                            //Now check which payment table to search
                            if (payment_option == credit_card)
                            {
                                var payment_result = from pm in allData.Credit_Card
                                                     where pm.customer_id == r.customer.id
                                                     select pm;
                                foreach (var payment in payment_result)
                                {
                                    Label18.Text = "Payment method: Credit card <br />Credit Card type: " + payment.card_type + "<br />"
                                        + "Credit card number: " + payment.credit_card_no + "<br />Expiry date: " + payment.expiry_date + "<br />"
                                        + "Credit Card in the name of: " + payment.holder_name;
                                }
                            }
                            else if (payment_option == debit_card)
                            {
                                var payment_result = from pm in allData.Direct_Debit
                                                     where pm.customer_id == r.customer.id
                                                     select pm;
                                foreach (var payment in payment_result)
                                {
                                    Label18.Text = "Payment method: Direct Debit <br />Name of the institution: " + payment.name_of_financial_institution +
                                        "<br />Account Name: " + payment.debit_account_name + "<br />Account type: " + payment.debit_account_type + "<br />" +
                                        "BSB: " + payment.BSB_no + "<br />Account number" + payment.account_number;
                                }
                            }
                        }
                        //Display reference check status
                        CreditCheck.Checked = (r.application.credit_check == 1);
                        referCheck.Checked = (r.application.reference_check == 1);
                        pCheck.Checked = (r.application.preliminary_check == 1);
                        fCheck.Checked = (r.application.final_check == 1);
                        i++;
                    }
                    if (i != 1)
                        success = false;
                    i = 0;
                    //Label1.Text += "current i is " + i.ToString();
                    foreach (var r in result_reference)
                    {
                        referenceID.Text = r.trade_ref_id.ToString();
                        refer1.Text = r.trade_ref_description_1;
                        phone1.Text = r.phone_1;
                        TextBox5.Text = r.trade_ref_description_2;
                        phone2.Text = r.phone_2;
                        fuelSupply.Text = r.existing_fuel_supplier;
                        fuelPhone.Text = r.fuel_supplier_phone;
                        i++;

                    }
                    if (i != 1)
                        success = false;
                    i = 0;
                    //Label1.Text += "current i is " + i.ToString();

                    //Now display all cards applied
                    var select_cards = from card in allData.Cards
                                       where card.cust_id == customer_id
                                       select card;
                    GridView2.DataSource = select_cards;
                    GridView2.DataBind();

                    /*var resultt = from dir in r.application.Directors
                                  from add in allData.Dir_Add
                                  where dir.dir_address_id == add.id
                                  select new { FirstName = dir.f_name, MiddleName = dir.m_name, LastName = dir.l_name, Phone = dir.phone, UnitNumber = add.unit_number, StreetNumber = add.street_number, Street = add.street, Suburb = add.suburb, State = add.state, PostCode = add.dir_add_postal_code };
                    GridView3.DataSource = resultt;
                    GridView3.DataBind();
                        */
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text += Request.Cookies["customer_id"].Value;
            int customer_id = Convert.ToInt32(Request.Cookies["customer_id"].Value);
            int num_credit = 0;
            int num_debit = 0;

            //Button3.Enabled = false;
            //Button3.Visible = false;
            if (Request.Cookies["viewMode"].Value.Contains("employee"))
            {
                //Button3.Enabled = true;
                //Button3.Visible = true;
            }

            if (!IsPostBack)
            {
                using (lucia_dataEntities allData = new lucia_dataEntities())
                {
                    var creditt = from cd in allData.Credit_Card
                                   where cd.customer_id == customer_id
                                   select cd;
                    var debitt = from db in allData.Direct_Debit
                                where db.customer_id == customer_id
                                select db;
                    foreach (var r in creditt)
                        num_credit++;
                    foreach (var r in debitt)
                        num_debit++;
                    if (num_credit != 0)
                    {
                        credit.Visible = true;
                        RadioButtonList1.SelectedValue = "Credit Card";
                        foreach (var a in creditt)
                        {
                            creditCName.Text= a.holder_name;
                            creditCardNo.Text = a.credit_card_no;
                            eDate.Text = a.expiry_date;
                            TextBox2.Text = a.card_type;
                        }
                    }
                    if (num_debit != 0)
                    {
                        direct.Visible = true;
                        RadioButtonList1.SelectedValue = "Direct Debit";
                        foreach (var b in debitt)
                        {
                            nameofFI.Text = b.name_of_financial_institution;
                            debitAccName.Text = b.debit_account_name;
                            TextBox1.Text = b.debit_account_type;
                            BSB.Text = b.BSB_no.ToString();
                            debitAccNo.Text = b.account_number.ToString();
                        }
                    }
                }
            }
        }
        //create transactions, from 01/08/2012 to datetime.now, all transactions start from 1st of the month to the first of the next month.
        protected void Button2_Click(object sender, EventArgs e)
        {
            using (lucia_dataEntities allData = new lucia_dataEntities())
            {
                //loop through all card items
                var cards = from cd in allData.Cards
                            select cd;
                foreach (var c in cards)
                {
                    int card_number = c.card_no;
                    int customer_number = c.cust_id;
                    //loop through all months to create all associated transactions
                    for (int i = 8; i <= DateTime.Now.Month; i++)
                    {
                        DateTime fromTime = new DateTime(2012, i, 1);
                        DateTime toTime = new DateTime(2012,i+1,1);
                        //search for whether a card fee has already been issued within the time frame
                        var card_fee_transaction = from cf in allData.Transactions
                                                   where cf.card_no == card_number
                                                   where cf.purchase_date >= fromTime
                                                   where cf.purchase_date <= toTime
                                                   where cf.prod_name == "card fee"
                                                   select cf;
                        int j = 0;
                        foreach (var cft in card_fee_transaction)
                            j++;
                        //no card fee, then create one for it.
                        if (j == 0)
                        {
                            decimal gst = 3 / 11;
                            Transaction newTrans = Transaction.CreateTransaction(j, "card fee", fromTime, card_number, 1, 3, gst, 3, gst, customer_number);
                            allData.AddToTransactions(newTrans);

                        }
                    }
                }
                allData.SaveChanges();

                //create invoice for each customer
                var customers = from c in allData.Customers
                                select c;

                foreach(var c in customers)
                {
                    int customer_number = c.id;
                    for (int i = 1; i <= DateTime.Now.Month; i++)
                    {
                        DateTime fromTime = new DateTime(2012, i, 1);
                        DateTime toTime = new DateTime(2012, i + 1, 1);

                        //now search through all corresponding transactions, and calculate for an invoice item
                        decimal total_due = 0;
                        var transactions = from ts in allData.Transactions
                                           where ts.customer_id==c.id
                                           where ts.purchase_date >= fromTime
                                           where ts.purchase_date <= toTime
                                           select ts;
                        foreach (var t in transactions)
                        {
                            total_due += t.total_price;
                        }
                        if (total_due != 0)
                        {
                            Invoice ninv = Invoice.CreateInvoice(i, new DateTime(2012, i, 14), customer_number, fromTime, toTime, total_due, 0);
                            allData.AddToInvoices(ninv);
                        }
                    }
                }
                allData.SaveChanges();
            }
            Label2.Text = "Successful!";

            Button2.Enabled = false;
        }
 //reset password
 protected void Button7_Click(object sender, EventArgs e)
 {
     Random r = new Random();
     int newpassword = r.Next(1000000, 10000000);
                 int account_id = Convert.ToInt32(Request.Cookies["account_id"].Value);
     using (lucia_dataEntities allData = new lucia_dataEntities())
     {
         var result = from acc in allData.Accounts
                      where acc.id == account_id
                      select acc;
         foreach (var re in result)
             re.password = newpassword.ToString();
         allData.SaveChanges();
         PassWord.Text = "New Password: "******" password reset;";
 }
        protected void Button1_Click(object sender, EventArgs e)
        {
            using (lucia_dataEntities allData = new lucia_dataEntities())
            {
                if (RadioButtonList1.SelectedValue == "By Card Number")
                {
                    int card_number = Convert.ToInt32(TextBox1.Text);
                    var result = from card in allData.Cards
                                 where card.card_no == card_number
                                 select card;
                    int count = 0;
                    foreach (var r in result)
                        count++;
                    if (count == 0)
                        Label1.Text = "No records found.";
                    else
                        Label1.Text = "";
                    GridView1.DataSource = result;
                    GridView1.DataBind();
                }
                if (RadioButtonList1.SelectedValue == "By Holder Name")
                {

                    var result = from cardholder in allData.Cardholders
                                 from card in allData.Cards
                                 where card.card_no == cardholder.card_no
                                 where cardholder.name == TextBox1.Text
                                 select card;
                    int count = 0;
                    foreach (var r in result)
                        count++;
                    if (count == 0)
                        Label1.Text = "No records found.";
                    else
                        Label1.Text = "";
                    GridView1.DataSource = result;
                    GridView1.DataBind();
                }

                if (RadioButtonList1.SelectedValue == "By Registration Number")
                {
                    var result = from vehicle in allData.Vehicles
                                 from card in allData.Cards
                                 where vehicle.card_no == card.card_no
                                 where vehicle.registration_no == TextBox1.Text
                                 select card;
                    int count = 0;
                    foreach (var r in result)
                        count++;
                    if (count == 0)
                        Label1.Text = "No records found.";
                    else
                        Label1.Text = "";
                    GridView1.DataSource = result;
                    GridView1.DataBind();
                }

                if (RadioButtonList1.SelectedValue == "By Account Number")
                {
                    int account_number = Convert.ToInt32(TextBox1.Text);
                    var result = from card in allData.Cards
                                 from account in allData.Accounts
                                 from customer in allData.Customers
                                 where account.id==account_number
                                 where account.cust_id==customer.id
                                 where card.cust_id == customer.id
                                 select card;
                    int count = 0;
                    foreach (var r in result)
                        count++;
                    if (count == 0)
                        Label1.Text = "No records found.";
                    else
                        Label1.Text = "";
                    GridView1.DataSource = result;
                    GridView1.DataBind();
                }

                if (RadioButtonList1.SelectedValue == "By Customer Number")
                {
                    int customer_number = Convert.ToInt32(TextBox1.Text);
                    var result = from card in allData.Cards
                                 where card.cust_id == customer_number
                                 select card;
                    int count = 0;
                    foreach (var r in result)
                        count++;
                    if (count == 0)
                        Label1.Text = "No records found.";
                    else
                        Label1.Text = "";
                    GridView1.DataSource = result;
                    GridView1.DataBind();
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            int account_id = Convert.ToInt32(Request.Cookies["account_id"].Value);
            int customer_id = 0;

            if(!IsPostBack){
                using (lucia_dataEntities allData = new lucia_dataEntities())
                {
                    var account = from acc in allData.Accounts
                                  where acc.id == account_id
                                  select acc;

                    foreach (var acc in account)
                    {
                        status = acc.status;
                        accountNumber.Text = acc.id.ToString();
                        accountStatus.Text = status;
                        customer_id = acc.cust_id;
                        creditLimit.Text = acc.credit_limit.ToString();
                        if(String.IsNullOrEmpty(acc.comments))
                        {
                            comments.Text = "";
                        }else{
                            comments.Text = acc.comments;
                        }
                    }
                    var application = from app in allData.Applications
                                      where app.cust_id == customer_id
                                      select app;
                    var customer = from cust in allData.Customers
                                   where cust.id == customer_id
                                   select cust;

                    foreach (var app in application)
                    {
                        regiDate.Text = app.app_date.ToString();
                    }

                    foreach (var cust in customer)
                    {
                        tradingName.Text = cust.trading_name;
                        phoneNumber.Text = cust.phone_no;
                    }

                    if (status == "active")
                        Button1.Enabled = false;
                    if (status == "disabled")
                        Button2.Enabled = false;
                    if (status == "closed")
                        Button3.Enabled = false;
                }
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            //So far, only customer_id is retrieved here, we will include account id later!!
            //#############################################################################

            int customer_id = Convert.ToInt32(Request.Cookies["Customer_id"].Value);
            using (lucia_dataEntities allData = new lucia_dataEntities())
            {
                var result = from customer in allData.Customers
                             where customer.id == customer_id
                             select customer;
                //Used for error detection;
                int i = 0;
                //Used for temp id generation
                int defaultID = 0;
                foreach (var r in result)
                {
                    //create item with customer_id, reference it with current customer object later
                    //#####################check whether EF needs items to reference to associated objects!############
                    Card newCard = Card.CreateCard(i, 1, tradingName.Text, customer_id, "disabled", 1);
                    newCard.Customer = r;
                    if (RadioButtonList1.SelectedValue == "For Person")
                    {
                        Cardholder cardholder = Cardholder.CreateCardholder(defaultID, personCar.Text, newCard.card_no);
                        for (int j = 0; j < purchaseOptions.Items.Count; j++)
                        {
                            if (purchaseOptions.Items[j].Selected)
                            {
                                Product_Card_Reference rf = Product_Card_Reference.CreateProduct_Card_Reference(newCard.card_no, purchaseOptions.Items[j].Text,defaultID);
                                defaultID++;
                                allData.AddToProduct_Card_Reference(rf);
                            }
                        }
                        allData.AddToCardholders(cardholder);

                    }
                    if (RadioButtonList1.SelectedValue == "For Vehicle")
                    {
                        Vehicle car = Vehicle.CreateVehicle(personCar.Text, newCard.card_no);
                        for (int j = 0; j < purchaseOptions.Items.Count; j++)
                        {
                            if (purchaseOptions.Items[j].Selected)
                            {
                                Product_Card_Reference rf = Product_Card_Reference.CreateProduct_Card_Reference(newCard.card_no, purchaseOptions.Items[j].Text, defaultID);
                                defaultID++;
                                allData.AddToProduct_Card_Reference(rf);
                            }
                        }
                        allData.AddToVehicles(car);
                    }
                    allData.AddToCards(newCard);
                    i++;

                    //Now check whether detector i is greater than 1, which indicates duplicate record in database!!
                    //######################
                    //An error is detected!
                    if (i != 1 || r.id != customer_id)
                    {
                        Response.Cookies["error"].Value = "newCardError!i="+i.ToString();
                        Response.Redirect("~/applicationManagement/ErrorPage.aspx");
                        return;
                    }
                }

                if (Request.Cookies["viewMode"].Value == "customerEdit")
                {
                    operationLog log = operationLog.CreateoperationLog(customer_id, customer_id, "Create new card", 1, DateTime.Now);
                    allData.AddTooperationLogs(log);
                    allData.SaveChanges();
                }
                else
                {
                    int empid = Convert.ToInt32(Request.Cookies["empid"].Value);
                    operationLog log = operationLog.CreateoperationLog(empid, customer_id, "Create new card", 1, DateTime.Now);
                    allData.AddTooperationLogs(log);
                    allData.SaveChanges();
                }

                allData.SaveChanges();
                //redirect to confirmation page
                Response.Redirect("~/accountManagement/cardConfirmation.aspx");
            }
        }