//-------------------------------
// Increase the cart contents
function increasecart(id){
    // Get the cart contents
    const cart = new Cart( "withinwebcartkeyfinal" );       // ??? can this go somewhere else ???

    // Increment by 1
    cart.increase(id);
    updatebaskettotal();
    //console.log("increase by 1");
}
//-------------------------------
function decreasecart(id){
    // Get the cart contents
    const cart = new Cart( "withinwebcartkeyfinal" );       // ??? can this go somewhere else ???

    // Decrement by 1
    cart.decrease(id);
    updatebaskettotal();
    //console.log("decrease by 1");
}
//-------------------------------
// Add this id to the cart.
function addtocart(id) {    
    // Get the cart contents
    const cart = new Cart( "withinwebcartkeyfinal" );       // ??? can this go somewhere else ???

    // Add the item
    cart.add(id);
    updatebaskettotal();
}
//-------------------------------
// Calculate the total price and add to total display
function updatebaskettotal() {

    // Read local storage using the given key
    const datacart = JSON.parse( localStorage.getItem("withinwebcartkeyfinal") );       // ????? could this be put elsewhere

    var total = 0;
    var totalshipping = 0;
    var numberinbasket = 0;

    // Loop around the data array to calculate the total basket
    for (let i = 0; i < datacart.length; i++) {
        let item = datacart[i];
            numberinbasket++;
            total = Number(total) + Number(item.total);
            totalshipping = Number(totalshipping) + Number(item.shippingtotal);
    }

    $("#totalshipping").text(gblSetUp[0]["currency"] + totalshipping.toFixed(2));
    $("#totalbasket").text(gblSetUp[0]["currency"] + total.toFixed(2));
    $("#numberinbasket").text(numberinbasket);

    //console.log("TOTAL: "  + total);
    //console.log("TOTALSHIPPING: " + totalshipping);

}
//-------------------------------
// From local storage update the cart display
function showCart() {

    // Read local storage using the given key
    const datacart = JSON.parse( localStorage.getItem("withinwebcartkeyfinal") );       // ????? could this be put elsewhere

    //add in currency and paypalemail to cart array.

    // Merge the two arrays
    for(let i = 0, len = datacart.length; i < len; i++) {
        datacart[i]["currency"] = gblSetUp[0]["currency"];
        datacart[i]["paypalemail"] = gblSetUp[0]["paypalemail"];
    }

    // Loop around the data array to display the cart details
    for (let i = 0; i < datacart.length; i++) {
        let item = datacart[i];
          //console.log('item_name: ' + item.item_number);
          //console.log('item_number: ' + item.qty);
          //console.log('item: ' + item.color);
          //console.log('quantity: ' + item.mc_gross);
          //console.log('total: ' + item.total);

        $('.cartresult').append (

            `
            <div class="row">

                <div class="col-md-3">
                    ${item.item_number}
                </div>

                <div class="col-md-2">
                    ${item.qty}
                </div>
                
                <div class="col-md-2">
                    ${item.currency}${item.mc_gross}
                </div>

                <div class="col-md-2">    
                    ${item.currency}${item.total}
                </div>

                <div class="col-md-3">
                   <img id='${item.id}' name='plus' src='assets/plus.jpg' class='cssplus' />
                   &nbsp;&nbsp;
                   <img id='${item.id}' name='minus' src='assets/minus.jpg' class='cssminus' />
                </div>

            </row>
            `

        );


    }
    
    updatebaskettotal();
    purchasebutton();

    //--------------------------------
    // Plus, increasecart
    $('.cssplus').on('click', function (e) {        
        //console.log(e.target.id);
        //console.log(e.target.name);
        //console.log(e);

        increasecart(e.target.id);
        $('.cartresult').text("");
        showCart();
    });

    //--------------------------------
    // Minus, decrease cart
    $('.cssminus').on('click', function (e) {        
        //console.log(e.target.id);
        //console.log(e.target.name);
        //console.log(e);

        decreasecart(e.target.id);
        $('.cartresult').text("");
        showCart();
    });

    //--------------------------------
    //Event when clear cart button is pressed
    $("#clearcart").click(function() {
        const cart = new Cart( "withinwebcartkeyfinal" );       // ??? can this go somewhere else ???
        $('.cartresult').text("");
        cart.empty();
        showCart();
    });	

}

//-------------------------------
// Construct the purchase button to post to PayPal
function purchasebutton() {

   //Clear the entry in the purchasebutton
   $('.purchasebutton').text("");

   // Read local storage using the given key
   const datacart = JSON.parse( localStorage.getItem("withinwebcartkeyfinal") );       // ????? could this be put elsewhere

   //add in currency and paypalemail to cart array.

   // Merge the two arrays
   for(let i = 0, len = datacart.length; i < len; i++) {
       datacart[i]["currency"]      = gblSetUp[0]["currency"];
       datacart[i]["currencycode"]  = gblSetUp[0]["currencycode"];
       datacart[i]["paypalemail"]   = gblSetUp[0]["paypalemail"];

       datacart[i]["postbackurl"]   = gblSetUp[0]["postbackurl"];
       datacart[i]["cancelurl"]     = gblSetUp[0]["cancelurl"];
       datacart[i]["returnurl"]     = gblSetUp[0]["returnurl"]; 
   }

   let item = datacart[0];
   
    $('.purchasebutton').append (
        `
        <input type="hidden" name="cmd" value="_cart" />
        <input type="hidden" name="business" value="${item.paypalemail}" />        
        <input type="hidden" name="currency_code" value="${item.currencycode}" />
        <input type="hidden" name="no_note" value="1" />
        <input type="hidden" name="upload" value="1" />

        <input type="hidden" name="lc" value="US" />

        <input type="hidden" name="notify_url" value="${item.postbackurl}" />
        <input type="hidden" name="cancel_return" value="${item.cancelurl}" />
        <input type="hidden" name="return" value="${item.returnurl}" />
        `
    );


    let j = 0;

    for (let i = 0; i < datacart.length; i++) {
        let item = datacart[i];
        
        j = i + 1;

        console.log(item);

        $('.purchasebutton').append (
            `
            <input type="hidden" name="item_name_`   + j + `" value="${item.item_number}" />
            <input type="hidden" name="amount_`      + j + `" value="${item.mc_gross}" />
            <input type="hidden" name="item_number_` + j + `" value="${item.item_number}" />
            <input type="hidden" name="quantity_`    + j + `" value="${item.qty}" />
            <input type="hidden" name="shipping_`    + j + `" value="${item.shipping}" />
            `
        );

    };

    $('.purchasebutton').append (
        `
        <input type="submit" name="submit" value="Make Purchase" />
        `
    );

}



