using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ShoppingCartTableAdapters;

public partial class ProductDetails : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.Master.PageSubHeading.Text = ">> Szczegółowe informacje na temat produktu!";
    }
    protected void AddToCart_Click(object sender, EventArgs e)
    {
        if (Page.User.Identity.IsAuthenticated)
        {
            if (Page.User.IsInRole("Customer"))
            {
                CartTableAdapter CartAdapter = new CartTableAdapter();
                MembershipUser myObject = Membership.GetUser();
                Guid UserID = (Guid)myObject.ProviderUserKey;
                ShoppingCart.CartDataTable CartTable = CartAdapter.IsCartExists(UserID);
                object CartId = null;
                if (CartTable.Rows.Count == 0)
                    CartId = CartAdapter.Add(UserID);
                else
                    CartId = int.Parse(CartTable.Rows[0]["CartId"].ToString());
                
                int ProductId = int.Parse(Request.QueryString["ProductId"].ToString());
                ProductsTableAdapter ProductsAdapter = new ProductsTableAdapter();
                ShoppingCart.ProductsDataTable Products;
                Products = ProductsAdapter.GetProductById(ProductId);
                decimal Price = decimal.Parse(Products.Rows[0]["SellingPrice"].ToString());
                CartDetailsTableAdapter CartDetailsAdapter = new CartDetailsTableAdapter();
                ShoppingCart.CartDetailsDataTable CartDetailsTable = CartDetailsAdapter.IsProductExistsInCart(UserID, ProductId);
                if (CartDetailsTable.Rows.Count == 0)
                    CartDetailsAdapter.AddProductToCart(int.Parse(CartId.ToString()), ProductId, 1, Price, DateTime.Now);
                else
                {
                    int newQuantity = int.Parse(CartDetailsTable.Rows[0]["QuantityOrdered"].ToString()) + 1;
                    decimal newPrice = newQuantity * Price;
                    int CartDetailsId = int.Parse(CartDetailsTable.Rows[0]["CartDetailsId"].ToString());
                    CartDetailsAdapter.UpdateProductInCart(newQuantity, newPrice, DateTime.Now, CartDetailsId);
                }
                Response.Redirect("Cart.aspx?UserId=" + UserID.ToString());                
            }
            else
            {
                this.Master.ErrorMessage.Text = "Aby móc kupować, musisz się zalogować.";
            }
        }
        else
        {
            this.Master.ErrorMessage.Text = "** Zaloguj się, aby dokonać zakupu **";
        }
    }
}
