private void Button3_Click(object sender, EventArgs e) //Select Locker button
        {
            if (listView1.SelectedItems.Count <= 0)
            {
                return;
            }
            ListViewItem  lvi            = listView1.SelectedItems[0];
            string        lockerCode     = String.Format("code = '{0}'", lvi.Text);
            var           locker         = new Locker();
            List <Locker> lockerList     = Locker.Where(lockerCode, 0, 1);
            var           selectedLocker = locker.Get(lockerList[0].Id);

            if (selectedLocker.IsOccupied())
            {
                MessageBox.Show("Error: Locker Occupied" + Environment.NewLine +
                                "You cannot select an occupied locker for the rental process.", "Locker Occupied",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (selectedLocker.IsNotAvailable())
            {
                MessageBox.Show("Error: Locker Not Available" + Environment.NewLine +
                                "You cannot select a not available locker for the rental process.", "Locker Not Available",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                _lockerId  = selectedLocker.Id;
                _cabinetId = selectedLocker.CabinetID;

                var cab  = new Cabinet();
                var item = cab.Get(_cabinetId);
                _typeId = item.TypeID;

                this.Close();
                _lockerSelected = true;
            }
        }
        private void ComboBox1_TextChanged(object sender, EventArgs e) //Auto generate Cabinet Code
        {
            if (comboBox1.SelectedIndex < 0)
            {
                return;
            }

            //Select Code for Cabinet Locker Type
            var item = from selected in _typeList
                       where selected.Name.Contains(comboBox1.Text)
                       select selected;

            _sizeCode = item.First().Code;

            //Auto generate locker code for each cabinet
            int            newCabCodeNo = 0;
            string         cabCond      = "id = (SELECT MAX(id) FROM cabinet WHERE type_id = {0})";
            List <Cabinet> cabList      = Cabinet.Where(String.Format(cabCond, item.First().Id), 0, 1);

            if (!cabList.Any())
            {
                newCabCodeNo = 1;
            }
            else
            {
                string currCabCode   = cabList[0].Code;
                string currCabCodeNo = String.Empty;
                for (int i = 0; i < currCabCode.Length; i++)
                {
                    if (Char.IsDigit(currCabCode[i]))
                    {
                        currCabCodeNo += currCabCode[i];
                    }
                }
                newCabCodeNo = Convert.ToInt32(currCabCodeNo) + 1;
            }
            textBox2.Text = String.Format("{0}-{1}", _sizeCode, newCabCodeNo.ToString("D2"));
        }
        private void SmallCabinetPage()
        {
            string condition = "status {0} AND type_id {1}";

            condition = String.Format(condition, _cabinetStatus, _cabinetSize);

            var cab = new Cabinet();

            smallCabinetPage.FinalIndex = cab.Count(condition);
            smallCabinetPage.LastPage   = Convert.ToInt32(Math.Ceiling(smallCabinetPage.FinalIndex / smallCabinetPage.MaxItems));
            smallCabinetPage.PageSetting();
            if (smallCabinetPage.FinalIndex == 0)
            {
                smallCabinetPage.FirstIndex = 0;
                smallCabinetPage.LastIndex  = 0;
                smallCabinetPage.LastPage   = 1;
            }
            if (smallCabinetPage.PageNumber == smallCabinetPage.LastPage)
            {
                smallCabinetPage.LastIndex = (int)smallCabinetPage.FinalIndex;
            }
            toolStripLabel1.Text = String.Format("Page {0} / {1}", smallCabinetPage.PageNumber, smallCabinetPage.LastPage);
            ReloadSmallCabinetList(smallCabinetPage.IndexLimit, smallCabinetPage.MaxItems, condition);
        }
        public CabinetForm()
        {
            InitializeComponent();
            Controls.Remove(tabControl1);
            Controls.Add(panel1);
            textBox1.Text = Cabinet.CurrentID().ToString();
            _typeList     = Type.Where("status <> 'Disabled'", 0, 100);

            //Load Locker Type Name into Combo Box 1
            foreach (Type t in _typeList)
            {
                _comboBoxItems.Add(t.Id, t.Name);
            }

            if (!_comboBoxItems.Any())
            {
                return;
            }

            comboBox1.DataSource    = new BindingSource(_comboBoxItems, null);
            comboBox1.DisplayMember = "Value";
            comboBox1.ValueMember   = "Key";
            comboBox1.SelectedIndex = -1;
        }
        private void Button2_Click(object sender, EventArgs e) //Save Button
        {
            //Select item the dictonary<int (key), string (value)>, which contains the type_name (comboBox1.Text)
            //In _comboBoxItems, key = type_id, value = type_name
            var dictValue = from selected in _comboBoxItems
                            where selected.Value.Contains(comboBox1.Text)
                            select selected;

            //Check if comboBox1.Text was empty or invalid input,
            //dictValue.Any() determines whether the sequence in dictvalue contains any element
            if (comboBox1.SelectedIndex < 0 || !dictValue.Any())
            {
                MessageBox.Show("Input Error: Invalid input detected!" + Environment.NewLine +
                                "Please ensure that field 'Locker Type' was filled with provided items. ",
                                "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //Get the key of the selected item
            int typeId = Convert.ToInt32(dictValue.First().Key);
            var cab    = new Cabinet
            {
                Code   = textBox2.Text,
                Row    = Convert.ToInt32(numericUpDown1.Value),
                Column = Convert.ToInt32(numericUpDown2.Value),
                TypeID = typeId
            };

            cab.Save();
            int latestCabId = cab.Id;

            var log = new AccessLog
            {
                User        = Login.Username,
                Action      = "Add",
                Item        = "Cabinet",
                ItemId      = textBox1.Text.ToString(),
                Description = "Code: " + textBox2.Text
            };

            log.Insert();

            _insertComplete = true;

            for (int i = 1; i <= (cab.Row * cab.Column); i++)
            {
                log.ItemId = Locker.CurrentID();

                //Auto increment for locker codes
                var locker = new Locker
                {
                    Code      = String.Format("{0}-{1}", cab.Code, i.ToString("D3")),
                    CabinetID = latestCabId
                };
                locker.Save();

                log.User        = "******";
                log.Action      = "Add";
                log.Item        = "Locker";
                log.Description = "Code: " + locker.Code;
                log.Insert();
            }
            this.Close();
        }
        private void LoadTransactionData(Transaction item)
        {
            //Rental
            textBox1.Text = item.Id.ToString();
            textBox2.Text = item.RentalID.ToString();
            textBox3.Text = item.StartDate.ToString("dd-MM-yyyy");
            DateTime endDate = item.StartDate.Date.AddDays(item.Duration);

            textBox4.Text        = endDate.ToString("dd-MM-yyyy");
            textBox5.Text        = item.Duration.ToString();
            numericUpDown1.Value = item.TypeRate * item.Duration;

            //Customer
            textBox7.Text = item.CustomerID.ToString();
            var cusList = Customer.Where(String.Format("id = {0}", item.CustomerID), 0, 1);

            if (cusList.Any())
            {
                textBox8.Text = cusList[0].Name;
                textBox9.Text = cusList[0].Ic;
            }

            //Locker
            textBox10.Text = item.LockerID.ToString();
            var lockerList = Locker.Where(String.Format("id = {0}", item.LockerID), 0, 1);

            if (lockerList.Any())
            {
                textBox11.Text = lockerList[0].Code;
                var cabList = Cabinet.Where(String.Format("id = {0}", lockerList[0].CabinetID), 0, 1);
                if (cabList.Any())
                {
                    textBox12.Text = cabList[0].Code;
                }
            }
            textBox13.Text       = item.TypeName;
            numericUpDown2.Value = item.TypeRate;

            //End Rental
            var tempReturnDate = item.ReturnDate.ToString("dd-MM-yyyy");

            //If the return date is not initialized, do not show the date.
            if (tempReturnDate != "01-01-0001")
            {
                textBox15.Text = tempReturnDate;
            }
            textBox16.Text       = item.OverdueTime.ToString();
            numericUpDown3.Value = item.Fine;

            //RentalStatus
            if (item.OverdueTime > 0)
            {
                checkBox1.Checked = true;
            }

            List <RentalStatus> statusList = RentalStatus.Where(String.Format("transaction_id = {0}", item.Id), 0, 10);
            var statuses = from selected in statusList
                           where selected.StatusId.ToString().Contains("3")
                           select selected;

            if (statuses.Any())
            {
                checkBox2.Checked = true;
            }

            statuses = from selected in statusList
                       where selected.StatusId.ToString().Contains("4")
                       select selected;

            if (statuses.Any())
            {
                checkBox3.Checked = true;
            }
        }
        private void Button10_Click(object sender, EventArgs e) //Next button
        {
            if (numericUpDown9.Value < numericUpDown8.Value)
            {
                MessageBox.Show("Input Error: Insufficient Payment." + Environment.NewLine +
                                "Payment amount must be equal or higher than total price.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            numericUpDown10.Value = numericUpDown9.Value - numericUpDown8.Value;

            button11.Hide();
            button10.Hide();
            button12.Show();

            //Delete Rental Log
            var log = new AccessLog()
            {
                User   = Login.Username,
                Action = "End",
                Item   = "Rental",
                ItemId = selectedRental.Id.ToString()
            };

            log.Insert();
            log = new AccessLog()
            {
                User   = "******",
                Action = "Delete from database",
                Item   = "Rental",
                ItemId = selectedRental.Id.ToString()
            };
            log.Insert();

            var transactionItem = Transaction.Where(String.Format("rental_id = {0}", selectedRental.Id), 0, 1);

            transactionItem[0].ReturnDate  = DateTime.Now.Date;
            transactionItem[0].OverdueTime = _overdueDays;
            transactionItem[0].Fine        = numericUpDown8.Value;
            transactionItem[0].Save();

            log = new AccessLog()
            {
                User        = "******",
                Action      = "Update",
                Item        = "Transaction",
                ItemId      = transactionItem[0].Id.ToString(),
                Description = "Return Date: " + transactionItem[0].ReturnDate.ToString("dd-MM-yyyy") +
                              "; Overdue Time: " + _overdueDays + " day; Fine: " + numericUpDown8.Value
            };
            log.Insert();

            //Insert transaction return status
            RentalStatus transReturnStatus = new RentalStatus();

            if (_keyLostFineAdded)
            {
                transReturnStatus.TransactionId = transactionItem[0].Id;
                transReturnStatus.StatusId      = 3;
                transReturnStatus.Insert();
                log = new AccessLog()
                {
                    User        = "******",
                    Action      = "Add",
                    Item        = "Rental Status",
                    ItemId      = transReturnStatus.TransactionId + ", " + transReturnStatus.StatusId,
                    Description = "Return Status: Key Lost"
                };
                log.Insert();
            }
            if (_lockerDamagedFineAdded)
            {
                transReturnStatus.TransactionId = transactionItem[0].Id;
                transReturnStatus.StatusId      = 4;
                transReturnStatus.Insert();
                log = new AccessLog()
                {
                    User        = "******",
                    Action      = "Add",
                    Item        = "Rental Status",
                    ItemId      = transReturnStatus.TransactionId + ", " + transReturnStatus.StatusId,
                    Description = "Return Status: Locker Damaged"
                };
                log.Insert();
            }
            if (checkBox1.Checked)
            {
                transReturnStatus.TransactionId = transactionItem[0].Id;
                transReturnStatus.StatusId      = 2;
                transReturnStatus.Insert();
                log = new AccessLog()
                {
                    User        = "******",
                    Action      = "Add",
                    Item        = "Rental Status",
                    ItemId      = transReturnStatus.TransactionId + ", " + transReturnStatus.StatusId,
                    Description = "Return Status: Overdue"
                };
                log.Insert();
            }

            //Release the occupied / overdue locker
            string lockerStatus = "";
            var    locker       = new Locker();

            locker = locker.Get(selectedRental.LockerID);

            if (locker.IsOverdued())
            {
                lockerStatus = "Overdue";
            }
            else
            {
                lockerStatus = "Occupied";
            }
            if (!_keyLostFineAdded && !_lockerDamagedFineAdded)
            {
                locker.Reset();
                log = new AccessLog()
                {
                    User        = "******",
                    Action      = "Update",
                    Item        = "Locker",
                    ItemId      = locker.Id.ToString(),
                    Description = "Code: " + locker.Code + "; Status: " + lockerStatus + " to Available"
                };
                log.Insert();

                //Check is the cabinet full, if yes, set to available
                var cabinet = new Cabinet();
                cabinet = cabinet.Get(locker.CabinetID);
                if (cabinet.IsFull())
                {
                    cabinet.Restore();

                    log = new AccessLog()
                    {
                        User        = "******",
                        Action      = "Update",
                        Item        = "Cabinet",
                        ItemId      = cabinet.Id.ToString(),
                        Description = "Code: " + cabinet.Code + "; Status: Full to Available"
                    };
                    log.Insert();
                }
            }
            else
            {
                locker.NotAvailable();
                string reason = "";
                if (_keyLostFineAdded && !_lockerDamagedFineAdded)
                {
                    reason += "Key Lost";
                }
                else if (!_keyLostFineAdded && _lockerDamagedFineAdded)
                {
                    reason += "Locker Damaged";
                }
                else
                {
                    reason += "Key Lost & Locker Damaged";
                }
                log = new AccessLog()
                {
                    User        = "******",
                    Action      = "Disable",
                    Item        = "Locker",
                    ItemId      = locker.Id.ToString(),
                    Description = "Code: " + locker.Code + "; Status: " + lockerStatus + " to Not Available; Reason: " + reason
                };
                log.Insert();
            }

            //Delete the rental
            selectedRental.Delete();
        }
        private void Button9_Click(object sender, EventArgs e) //Change Locker button
        {
            var result = MessageBox.Show("Do you want to change the locker for this rental?", "Change Locker",
                                         MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (result == DialogResult.Yes)
            {   //Check if the rental overdue. If yes, show error message and return.
                var      endDate  = selectedRental.StartDate.AddDays(selectedRental.Duration);
                TimeSpan timeSpan = endDate.Date.Subtract(DateTime.Now.Date);
                int      daysLeft = Convert.ToInt32(timeSpan.Days);
                if (daysLeft < 0)
                {
                    MessageBox.Show("Access Error: Rental Overdued." + Environment.NewLine +
                                    "You cannot change details for an overdued rental.", "Access Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                //Assign the old rental data to a temp variable
                int oldLockerId = selectedRental.LockerID;
                var oldLocker   = new Locker();
                oldLocker = oldLocker.Get(oldLockerId);

                //Open Select Locker Form
                var ChangeLockerForm = new SelectLockerForm(selectedRental.LockerID);
                ChangeLockerForm.ShowDialog();

                //If cancel select, return.
                if (!ChangeLockerForm.LockerSelected)
                {
                    return;
                }

                //Get the new selected type, cabinet and locker for the selected locker
                _typeList    = Type.Where(String.Format("id = {0}", ChangeLockerForm.TypeID), 0, 1);
                _cabinetList = Cabinet.Where(String.Format("id = {0}", ChangeLockerForm.CabinetID), 0, 1);
                _lockerList  = Locker.Where(String.Format("id = {0}", ChangeLockerForm.LockerID), 0, 1);

                //Assign the new locker into rental, and save access log
                selectedRental.LockerID = ChangeLockerForm.LockerID;
                selectedRental.Save();
                var log = new AccessLog()
                {
                    User        = Login.Username,
                    Action      = "Update",
                    Item        = "Rental",
                    ItemId      = selectedRental.Id.ToString(),
                    Description = "Locker: " + oldLocker.Code + " to " + _lockerList[0].Code
                };
                log.Insert();

                //Release the old locker (status = available) and insert into access log
                oldLocker.Reset();
                log.User        = "******";
                log.Action      = "Update";
                log.Item        = "Locker";
                log.ItemId      = oldLocker.Id.ToString();
                log.Description = "Code: " + oldLocker.Code + "; Status: Occupied to Available";
                log.Insert();

                //Check if the old cabinet is full. If yes, set the cabinet to available.
                var oldCabinet = new Cabinet();
                oldCabinet = oldCabinet.Get(oldLocker.CabinetID);
                if (oldCabinet.IsFull())
                {
                    oldCabinet.Restore();
                    log.User        = "******";
                    log.Action      = "Update";
                    log.Item        = "Cabinet";
                    log.ItemId      = oldLocker.CabinetID.ToString();
                    log.Description = "Code: " + oldCabinet.Code + "; Status: Full to Available";
                    log.Insert();
                }

                //Set the new locker is occupied, and insert into access log
                _lockerList[0].Occupied();
                log.User        = "******";
                log.Action      = "Update";
                log.Item        = "Locker";
                log.ItemId      = selectedRental.LockerID.ToString();
                log.Description = "Code: " + _lockerList[0].Code + "; Status: Available to Occupied";
                log.Insert();

                //Check if the new cabinet full. If yes, set cabinet to full, and insert into access log.
                var locker        = new Locker();
                int EmptyLockerNo = locker.Count(String.Format("cabinet_id = {0} AND status = 'Available'",
                                                               _cabinetList[0].Id));
                if (EmptyLockerNo <= 0)
                {
                    _cabinetList[0].Full();
                    log.User        = "******";
                    log.Action      = "Update";
                    log.Item        = "Cabinet";
                    log.ItemId      = _cabinetList[0].Id.ToString();
                    log.Description = "Code: " + _cabinetList[0].Code + "; Status: Available to Full";
                    log.Insert();
                }

                //Change the details in transaction and save in access log
                var selectedTrans = Transaction.Where(String.Format("rental_id = {0}", selectedRental.Id), 0, 1);
                selectedTrans[0].LockerID = _lockerList[0].Id;
                selectedTrans[0].ChangeLocker();
                log.User        = "******";
                log.Action      = "Update";
                log.Item        = "Transaction";
                log.ItemId      = selectedTrans[0].Id.ToString();
                log.Description = "Locker: " + oldLocker.Code + " to " + _lockerList[0].Code;
                log.Insert();

                //Change the locker details in the View Rental Details
                textBox25.Text = _lockerList[0].Id.ToString();
                textBox26.Text = _lockerList[0].Code;
                textBox27.Text = _cabinetList[0].Code;
                textBox28.Text = _typeList[0].Name;
                textBox29.Text = _typeList[0].Rate.ToString("0.00");
            }
        }