using System;
using System.Collections.Generic;
using System.Web.Mvc;
using HMS.Class.BLL;
using HMS.Class.Helper;
using HMS.Models;
using HMS.ViewModel;

namespace HMS.Controllers
{
     [LogOnAuthorize(Roles = "2,7")]
    public class PaymentController : BaseController
    {
        #region Action Methods

        /// <summary>
        /// Index view action.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <param name="searchField">The search field.</param>
        /// <param name="searchValue">The search value.</param>
        /// <param name="sortField">The sort field.</param>
        /// <param name="sortOrder">The sort order.</param>
        /// <returns>
        /// Returns index action result.
        /// </returns>
        public ActionResult Index(int? page, int? pageSize, string searchField, string searchValue, string sortField, string sortOrder)
        {
            if (CommonLogic.GetQueryString("status").Equals("s", StringComparison.CurrentCultureIgnoreCase))
            {
                ViewBag.SuccessMsg = string.Format(StringConstants.RecordSave, "Payment");
            }

            ViewBag.PageNo = page ?? 1;
            ViewBag.PageSize = pageSize ?? MvcApplication.Setting.PageSize;
            ViewBag.SearchField = (string.IsNullOrEmpty(searchField) && !string.IsNullOrEmpty(searchValue)) ? "PaymentDate" : searchField;
            ViewBag.SearchValue = searchValue;
            ViewBag.SortField = !string.IsNullOrEmpty(sortField) ? sortField : "PaymentDate";
            ViewBag.SortOrder = !string.IsNullOrEmpty(sortOrder) ? sortOrder : "DESC";

            string mode = CommonLogic.GetFormDataString("mode");
            string ids = CommonLogic.GetFormDataString("ids");

            if (!string.IsNullOrEmpty(mode) && !string.IsNullOrEmpty(ids))
            {
                try
                {
                    MultiOperationType operationType = (MultiOperationType)Enum.Parse(typeof(MultiOperationType), mode, true);
                    PaymentBLL.UpdateMultipleRecords(operationType, ids);
                }
                catch (Exception ex)
                {
                    return this.Json(new { IsError = true, ErrorMsg = CommonLogic.GetExceptionMessage(ex) });
                }
            }

      
            List<PaymentModel> paymentList = PaymentBLL.GetAll(ViewBag.SearchField, ViewBag.SearchValue, ViewBag.SortField, ViewBag.SortOrder, ViewBag.PageNo, ViewBag.PageSize);
            int totalRecords = 0;

            if (paymentList != null && paymentList.Count > 0)
            {
                totalRecords = paymentList[0].TotalRecordCount;
            }

            ViewBag.ListRecords = paymentList.Count;
            ViewBag.PagedList = paymentList.ToStaticPagedList((int)ViewBag.PageNo, (int)ViewBag.PageSize, totalRecords);

            return Request.IsAjaxRequest() ? (ActionResult)PartialView("Index", paymentList) : this.View(paymentList);
        }

        /// <summary>
        /// Add view action.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns>
        /// Returns add action result.
        /// </returns>
        public ActionResult Add(long? id)
        {
            var paymentVM = new PaymentViewModel(id);
            ViewBag.Heading = "Add Payment";

            if (id.HasValue && id > 0)
            {
                ViewBag.Heading = "Edit Payment";
                paymentVM.Payment = PaymentBLL.GetById(id ?? 0);

                if (paymentVM.Payment == null)
                {
                    paymentVM.Payment = new PaymentModel();
                }
            }

            return Request.IsAjaxRequest() ? (ActionResult)PartialView("Add", paymentVM) : this.View(paymentVM);
        }

        /// <summary>
        /// Add view post action.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="paymentVM">The model.</param>
        /// <returns>
        /// Returns add action result.
        /// </returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Add(long? id, PaymentViewModel paymentVM, List<PaymentDetailModel> paymentDetailList)
        {
            try
            {
                ViewBag.Heading = "Add Payment";

                paymentVM.PaymentDetails = paymentDetailList;

                if (paymentVM.Payment.PaymentId > 0)
                {
                    ViewBag.Heading = "Edit Payment";
                }

                if (ModelState.IsValid)
                {
                    paymentVM.Payment.CompanyId = SqlHelper.ParseNativeLong(CommonLogic.GetSessionValue(StringConstants.CompanyId));
                    paymentVM.Payment.CreatedBy = SqlHelper.ParseNativeLong(CommonLogic.GetSessionValue(StringConstants.UserId));
                    //model.RoleId = RoleType.Patient.GetHashCode();

                   long paymentId = PaymentBLL.Save(paymentVM);
                }
            }
            catch (System.Exception ex)
            {
                ViewBag.ErrorMsg = CommonLogic.GetExceptionMessage(ex);
            }

            return Request.IsAjaxRequest() ? (ActionResult)PartialView("Add", paymentVM) : this.View(paymentVM);
        }
        public ActionResult Invoice(long? id)
        {

            string mode = CommonLogic.GetFormDataString("mode");

            if (!string.IsNullOrEmpty(mode) && mode == "up" )
            {
                try
                {
                    PaymentBLL.UpdatePaymentStatus(PaymentStatusType.Paid, id.Value.ToString());
                }
                catch (Exception ex)
                {
                    return this.Json(new { IsError = true, ErrorMsg = CommonLogic.GetExceptionMessage(ex) });
                }
            }

            var invoiceVM = new InvoiceViewModel(id);
            ViewBag.Heading = "Invoice";

            if (invoiceVM.Payment == null)
            {
                ViewBag.ErrorMsg = "Requested invoice not found.";
            }

            return Request.IsAjaxRequest() ? (ActionResult)PartialView("Invoice", invoiceVM) : this.View(invoiceVM);
        }

        public ActionResult InvoicePrint(long? id)
        {
            var invoiceVM = new InvoiceViewModel(id);
            ViewBag.Heading = "Invoice";

            if (invoiceVM.Payment == null)
            {
                ViewBag.ErrorMsg = "Requested invoice not found.";
            }

            return Request.IsAjaxRequest() ? (ActionResult)PartialView("InvoicePrint", invoiceVM) : this.View(invoiceVM);
        }

        #endregion
    }
}
