using System;
using System.Data;
using System.Configuration;
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 Westwind.BusinessObjects;
using System.Text;

using ScriptCallbacks.BusinessObjects;

/// <summary>
/// Summary description for busInvoice
/// </summary>
public class busInvoice : wwBusiness<OrdersRow>
{
    public busCustomer Customer
    {
        get
        {
            return _Customer;
        }
        set
        {
            _Customer = value;
        }
    }
    private busCustomer _Customer;

    public busInvoice()
	{
        this.ConnectionString = ConfigurationManager.ConnectionStrings["AjaxAspNet"].ConnectionString;
        this.ConnectType = ServerTypes.SqlServer;
        this.DataRowUpdateMode = DataRowUpdateModes.OptimizedByPk;
        this.Tablename = "Orders";
        this.PkField = "OrderId";
        this.PkType = PkFieldTypes.intType;
	}


    /// <summary>
    ///  Hook up customer child object
    /// </summary>
    /// <param name="Pk"></param>
    /// <returns></returns>
    public override bool Load(int Pk)
    {
        if (!base.Load(Pk))
            return false;

        if (Customer == null)
            Customer = new busCustomer();

        return Customer.Load(this.Entity.Customerid);
    }

    /// <summary>
    /// Creates a DataTable called TInvoiceList in the internal DataSet
    /// </summary>
    /// <param name="MaxInvoices"></param>
    /// <returns></returns>
    public int GetLastInvoices(int MaxInvoices) 
    {
        if (MaxInvoices == 0)
            MaxInvoices = 100;

        string Sql = @"SELECT  TOP "  + MaxInvoices.ToString() + @"    
	MAX(Orders.OrderID) AS OrderId, MAX(Customers.CompanyName) AS Company, MAX(Customers.ContactName) AS Name, MAX(Orders.OrderDate) AS OrderDate, 
                      SUM( ([Order Details].UnitPrice * [Order Details].Quantity) )  AS OrderTotal, Max(freight) as Freight
FROM         Customers INNER JOIN
                      Orders ON Customers.CustomerID = Orders.CustomerID INNER JOIN
                      [Order Details] ON Orders.OrderID = [Order Details].OrderID
group by Orders.Orderid
order by OrderDate Desc";

        return this.Execute(Sql,"TInvoiceList");
    }

    public int GetInvoicesForCustomer(string CustomerId)
    {
        string Sql = @"SELECT      
	MAX(Orders.OrderID) AS OrderId, MAX(Customers.CompanyName) AS Company, MAX(Customers.ContactName) AS Name, MAX(Orders.OrderDate) AS OrderDate, 
                      SUM( ([Order Details].UnitPrice * [Order Details].Quantity) )  AS OrderTotal, Max(freight) as Freight
FROM         Customers INNER JOIN
                      Orders ON Customers.CustomerID = Orders.CustomerID INNER JOIN
                      [Order Details] ON Orders.OrderID = [Order Details].OrderID
WHERE Orders.CustomerId=@CustomerId
group by Orders.Orderid
order by OrderDate Desc";

        
        return this.Execute(Sql, "TCustomerInvoiceList",this.CreateParameter("@CustomerId",CustomerId) );

    }

    /// <summary>
    /// Displays the lineitems of the currently loaded invoice
    /// </summary>
    /// <param name="OrderId"></param>
    /// <returns></returns>
    public string HtmlLineItems()
    {
        int OrderId = (int) this.DataRow["Orderid"]; 

        // *** this is a demo hack at best <g>
        if (!this.Load(OrderId))
            return "";

        int Result = this.Execute(@"
select OrderId,Products.ProductId, ProductName, [order details].UnitPrice,Quantity, (Quantity * [Order details].UnitPrice) as ItemTotal 
 from [Order Details],Products
where OrderId=@OrderId and [Order Details].OrderId = @OrderId and [Order Details].ProductId = Products.ProductId","TLineItems",
this.CreateParameter("@OrderId",OrderId) );     
        
        if (Result < 0) 
        {
            return "";
        }             
        
        StringBuilder sb = new StringBuilder();

        sb.Append("<table class='blackborder' width='500' cellpadding='4' bgcolor='white'>");
        sb.Append("<tr class='gridheader'><th>Description</th><th>Qty</th><th>Price</th><th>Total</th></tr>");

        bool AlternateRow = false;
        decimal OrderTotal = 0.00M;
        foreach (DataRow dr in this.DataSet.Tables["TLineItems"].Rows)
        {
            sb.Append("<tr" + (AlternateRow ? " class='gridalternate'" : "") + "><td>" + dr["productname"] + "</td><td align='center'>" +  dr["Quantity"].ToString() + "</td><td align='right'>" + ((decimal)dr["UnitPrice"]).ToString("n2") + "</td><td align='right'>" + ((decimal)dr["ItemTotal"]).ToString("n2") + "</td></tr>");
            
            AlternateRow = !AlternateRow;
            OrderTotal += (decimal)dr["ItemTotal"];
        }

        decimal Freight = ((decimal)this.DataRow["Freight"]);

        // *** Separator line
        sb.Append("<tr><td colspan='4' class='blockheader' style='height:1px;border:0px;padding:0px;'></td></tr>");

        sb.Append("<tr style='border-top:1px solid black'><td colspan='3' align='right'>Shipping:</td><td align='right'>" + Freight.ToString("n2") + "</td></tr>");
        sb.Append("<tr style='border-top:1px solid black'><td colspan='3' align='right'><b>Order Total:</b></td><td align='right' style='background:silver;color:maroon;font-weight:bold'>" + (OrderTotal + Freight).ToString("c2") + "</td></tr>");        
        sb.Append("</table>");
        return sb.ToString();                                       
    }

}
