public IHttpActionResult updateInvoice(string InvoiceId)
 {
     try
     {
         var form         = HttpContext.Current.Request.Form;
         var approvedBy   = form.Get("ApprovedBy");
         var approvedDate = form.Get("approvedDate");
         using (MaxDbEntities db = new MaxDbEntities())
         {
             var invoices = db.Invoices.First(x => x.Id == InvoiceId);
             invoices.InvoiceApprovedBy = (from emp in db.Employees where emp.EmployeeNumber == approvedBy select emp.Id).FirstOrDefault();
             invoices.ApprovedDate      = DateTime.Now;
             db.Entry(invoices).State   = System.Data.Entity.EntityState.Modified;
             db.SaveChanges();
         }
         return(Ok());
     }
     catch (Exception ex)
     {
         new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
         return(InternalServerError());
     }
 }
        public IHttpActionResult DeleteInvoice(string InvoiceId)
        {
            try
            {
                var form        = HttpContext.Current.Request.Form;
                var description = form.Get("Description");
                var invoiceId   = form.Get("InvoiceId");

                using (MaxDbEntities db = new MaxDbEntities())
                {
                    //var invoices = db.Invoices.Where(x => x.Id==InvoiceId).FirstOrDefault();
                    //var invoiceServices = db.InvoiceServices.Where(x => x.InvoiceId == InvoiceId).FirstOrDefault();

                    //  var deleteRecord = db.DeleteClientPayment(InvoiceId);

                    var invoiceSer = db.InvoiceServices.First(x => x.InvoiceId == InvoiceId);
                    var Inv        = db.Invoices.First(x => x.Id == InvoiceId);

                    if (InvoiceId == null)
                    {
                        return(Content(HttpStatusCode.InternalServerError, "Invalid data, please try again!"));
                    }

                    if (invoiceSer.PaymentId == null)
                    {
                        DeletedInvoice        Di    = new DeletedInvoice();
                        DeletedInvoiceService DInvs = new DeletedInvoiceService();

                        Di.Id                 = Inv.Id;
                        Di.ApprovedDate       = Inv.ApprovedDate;
                        Di.ClientAddress      = Inv.ClientAddress;
                        Di.Client_Id          = Inv.Client_Id;
                        Di.CompanyAddress     = Inv.CompanyAddress;
                        Di.CurrencyType       = Inv.CurrencyType;
                        Di.CurrentBillAmount  = Inv.CurrentBillAmount;
                        Di.InvoiceApprovedBy  = Inv.InvoiceApprovedBy;
                        Di.ApprovedDate       = Inv.ApprovedDate;
                        Di.InvoiceCreatedBy   = Inv.InvoiceCreatedBy;
                        Di.InvoiceCreatedDate = Inv.InvoiceCreatedDate;
                        Di.InvoiceURL         = Inv.InvoiceURL;
                        Di.Status             = Inv.Status;
                        Di.TotalDueAmount     = Inv.TotalDueAmount;
                        Di.TotalInvoiceAmount = Inv.TotalInvoiceAmount;
                        Di.Description        = description;

                        DInvs.AmountPaidDate = invoiceSer.AmountPaidDate;
                        DInvs.BillAmount     = invoiceSer.BillAmount;
                        DInvs.ClientId       = invoiceSer.ClientId;
                        DInvs.DueAmount      = invoiceSer.DueAmount;
                        DInvs.InvoiceId      = invoiceSer.InvoiceId;
                        DInvs.PaymentId      = invoiceSer.PaymentId;
                        DInvs.ServiceId      = invoiceSer.ServiceId;
                        DInvs.Id             = invoiceSer.Id;

                        db.DeletedInvoices.Add(Di);
                        db.DeletedInvoiceServices.Add(DInvs);

                        db.InvoiceServices.Remove(invoiceSer);
                        db.Invoices.Remove(Inv);
                        db.SaveChanges();
                    }
                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(InternalServerError());
            }
        }
        public IHttpActionResult AddInvoice()
        {
            try
            {
                InvoiceModel invoice = new InvoiceModel();

                var form           = HttpContext.Current.Request.Form;
                var clientId       = form.Get("Client_Id");
                var companyAddress = form.Get("CompanyAddress");
                var clientAddress  = form.Get("ClientAddress");
                var invoiceDate    = form.Get("InvoiceDate");
                var invoiceTime    = form.Get("InvoiceTime");
                var dueAmount      = form.Get("UnpaidBalance");
                if (dueAmount == "null")
                {
                    dueAmount = 0.ToString();
                }
                var CurrentAmount = form.Get("CurrentAmount");
                var totalLines    = form.Get("TotalLines");
                var status        = form.Get("Status");
                var serviceId     = form.Get("ClientService");
                var unitPrice     = form.Get("UnitPrice");
                var invoiceId     = form.Get("InvoiceId");
                var createdBy     = form.Get("CreatedBy");
                var invoiceSer    = JsonConvert.DeserializeObject <List <string> >(form.Get("InvoiceServices"));

                using (MaxDbEntities db = new MaxDbEntities())

                {
                    Invoice        inData    = new Invoice();
                    InvoiceService inService = new InvoiceService();

                    inData.Client_Id          = Convert.ToInt32(clientId);
                    inData.Id                 = invoiceId;
                    inData.CompanyAddress     = companyAddress;
                    inData.ClientAddress      = clientAddress;
                    inData.InvoiceCreatedBy   = (from Emp in db.Employees where Emp.EmployeeNumber == createdBy select Emp.Id).FirstOrDefault();
                    inData.InvoiceCreatedDate = Convert.ToDateTime(invoiceDate);

                    string currency = (from client in db.Clients where client.Id == inData.Client_Id select client.Currency).FirstOrDefault();
                    inData.CurrencyType = currency;

                    inData.CurrentBillAmount  = Convert.ToDecimal(CurrentAmount);
                    inData.TotalDueAmount     = Convert.ToDecimal(dueAmount);
                    inData.TotalInvoiceAmount = Convert.ToDecimal(CurrentAmount);

                    foreach (string id in invoiceSer)
                    {
                        string unitprice = (from client in db.Clients where client.Id == inData.Client_Id select client.PaymentAmount).FirstOrDefault().ToString();

                        inService.InvoiceId  = inData.Id;
                        inService.ClientId   = Convert.ToInt32(clientId);
                        inService.ServiceId  = Convert.ToInt32(serviceId);
                        inService.UnitPrice  = Convert.ToDecimal(unitPrice);
                        inService.TotalLines = Convert.ToInt32(totalLines);
                        inService.BillAmount = Convert.ToDecimal(CurrentAmount);
                        inService.DueAmount  = inService.BillAmount;
                    }
                    db.Invoices.Add(inData);
                    db.InvoiceServices.Add(inService);
                    db.SaveChanges();
                }
                return(Ok());
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(InternalServerError());
            }
        }
        public async Task <IHttpActionResult> PayAmount()
        {
            try
            {
                var form = HttpContext.Current.Request.Form;

                var clientId        = form.Get("Client_Id");
                var TotalamountPaid = form.Get("paymentAmount");
                var paymentDate     = form.Get("paymentDate");
                var currency        = form.Get("Currency");
                var description     = form.Get("Description");

                var invoiceServiceIds = JsonConvert.DeserializeObject <List <string> >(form.Get("ClientPayment"));

                var file      = HttpContext.Current.Request.Files;
                var ChequePdf = file["ChequePdf"];

                if (ChequePdf != null)
                {
                    var fileExtension   = Path.GetExtension(ChequePdf.FileName);
                    var validExtensions = new string[] { ".doc", ".docx", ".pdf", ".txt" };

                    if (!validExtensions.Contains(fileExtension))
                    {
                        return(Content(HttpStatusCode.InternalServerError, "Invalid file type for resume!!"));
                    }
                }


                using (MaxDbEntities db = new MaxDbEntities())
                {
                    var invoiceServices = db.InvoiceServices.Where(x => invoiceServiceIds.Contains(x.InvoiceId)).OrderByDescending(x => x.InvoiceId);

                    ClientReceivable clientRecv = new ClientReceivable();

                    clientRecv.Client_Id   = Convert.ToInt32(clientId);
                    clientRecv.Currency    = currency;
                    clientRecv.PaymentDate = Convert.ToDateTime(paymentDate);
                    clientRecv.Description = description;
                    clientRecv.AmountPaid  = Convert.ToDecimal(TotalamountPaid);

                    var files           = HttpContext.Current.Request.Files;
                    var ScannedDocument = files["ChequePdf"];
                    if (ScannedDocument != null)
                    {
                        var fileDirecory = HttpContext.Current.Server.MapPath("~/ClientCheque");
                        if (!Directory.Exists(fileDirecory))
                        {
                            Directory.CreateDirectory(fileDirecory);
                        }
                        var fileName = DateTime.Now.Ticks + "_" + ScannedDocument.FileName;
                        var filepath = Path.Combine(fileDirecory, fileName);
                        ScannedDocument.SaveAs(filepath);
                        clientRecv.ScannedDocument = Path.Combine(ConfigurationManager.AppSettings["ApiUrl"], "ClientCheque", fileName);
                    }

                    var totalAmountAvailable = Convert.ToDecimal(TotalamountPaid);

                    foreach (string id in invoiceServiceIds)
                    {
                        var invoiceService = db.InvoiceServices.Where(x => x.InvoiceId == id).FirstOrDefault();
                        ClientReceivableService clientSer = new ClientReceivableService();

                        clientSer.Description = description;
                        clientSer.ServiceId   = invoiceService.Id;

                        if (totalAmountAvailable > 0)
                        {
                            if (Convert.ToDecimal(totalAmountAvailable) > Convert.ToDecimal(invoiceService.DueAmount))
                            {
                                totalAmountAvailable    -= Convert.ToDecimal(invoiceService.DueAmount);
                                clientSer.PaidAmount     = invoiceService.DueAmount;
                                invoiceService.DueAmount = 0;
                            }

                            else
                            {
                                invoiceService.DueAmount = invoiceService.DueAmount - totalAmountAvailable;
                                clientSer.PaidAmount     = Convert.ToDecimal(totalAmountAvailable);
                                clientRecv.Balance       = 0;
                                totalAmountAvailable     = 0;
                            }

                            clientRecv.Balance = totalAmountAvailable;
                        }

                        else
                        {
                            invoiceService.DueAmount = Convert.ToDecimal(invoiceService.DueAmount);
                            clientSer.PaidAmount     = 0;
                        }

                        invoiceService.AmountPaidDate = Convert.ToDateTime(paymentDate);
                        clientSer.ClientReceivable    = clientRecv;
                        db.ClientReceivableServices.Add(clientSer);
                        invoiceService.ClientReceivable = clientRecv;
                        db.Entry(invoiceService).State  = System.Data.Entity.EntityState.Modified;
                    }

                    db.ClientReceivables.Add(clientRecv);
                    db.SaveChanges();
                }
                return(Ok());
            }

            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(InternalServerError());
            }
        }