<?php
    //
    // Product Management
    // $Id: ProductList.php,v 1.10 2004/12/18 17:32:07 doug Exp $
    // Doug Rinckes
    // Functions that act on a list of products:
    //	reloadProductList
    //	manageProductList
    //	modifyProductList
    //	showProductList
    //


    class KCART_ProductList {

        // generate an array of the products
        // (actually an array (0..n) of product arrays)
        // so product 0s code is stored as:
        // $product[0]["product_code"]
        function getProductList () {
            // Reinitialize the products array  by loading products from the database
            $products = array ();
            $products_result = $GLOBALS['core']->sqlSelect ("mod_kcart_products");
            if ($products_result) {
                foreach ($products_result as $product) {
                    array_push($products, $product);
                }
            }
            return($products);
        }


        // display a list of all the products
        // to allow editing/activating etc of them
        function manageProductList () {
            // titles and column headers
            $title = $_SESSION['translate']->it ("Current Products");
            $template['PRODUCT_CODE_TEXT'] = $_SESSION['translate']->it ("Code");
            $template['PRODUCT_DESCRIPTION_TEXT'] = $_SESSION['translate']->it ("Description");
            $template['PRODUCT_PRICE_TEXT'] = $_SESSION['translate']->it ("Price");
            $template['PRODUCT_ACTIONS_TEXT'] = $_SESSION['translate']->it ("Actions");
            // set the layout template
            $content = KCART_kCart::processTemplate ($template, "kcart", "listproducts_header.tpl");

            // if there is a product array and the number of items is > 0
            $products = KCART_ProductList::getProductList();
            if (is_array ($products) && (count ($products) > 0)) {
                // set a couple of hidden variables
                $hiddens = array ("module" => "kcart", "KCART_manage" => "modifyProductList");

                // step through the products
                // sets $product_code to be the product code and
                // $thisproduct to be a pointer to the product object
                foreach ($products as $index => $thisproduct) {
                    // set a hidden variable to the product code
                    $hiddens['CART_product_code'] = $thisproduct["product_code"];
                    $elements[0] = PHPWS_Form::formHidden ($hiddens);

                    // set the product information fields
                    $template['PRODUCT_CODE'] = $thisproduct["product_code"];
                    $template['PRODUCT_DESCRIPTION'] = $thisproduct["product_description"];
                    $template['PRODUCT_PRICE'] = $thisproduct["product_price"];
                    // if the product is active, use the normal background
                    if ($thisproduct["product_active"]) {
                        $template['BACKG'] = "bg_light";
                    } else {
                        // if not active, show it
                        $template['BACKG'] = "alt_bg_dark";
                    }

                    // if you are allowed to edit the product....
                    if ($_SESSION['OBJ_user']->allow_access ("kcart", "edit_product")) {
                        // create a form to edit
                        $elements[0] .= PHPWS_Form::formSubmit ($_SESSION['translate']->it ("Edit"), "edit_existing_product");
                    }

                    // if you are allowed to delete...
                    if ($_SESSION['OBJ_user']->allow_access ("kcart", "delete_product")) {
                        $elements[0] .= PHPWS_Form::formSubmit ($_SESSION['translate']->it ("Delete"), "delete_product");
                    }

                    // if you are allowed to change the activation status
                    if ($_SESSION['OBJ_user']->allow_access ("kcart", "product_activity")) {
                        if ($thisproduct["product_active"]) {
                            $elements[0] .= PHPWS_Form::formSubmit ($_SESSION['translate']->it ("Deactivate"), "activate_product");
                        } else {
                            $elements[0] .= PHPWS_Form::formSubmit ($_SESSION['translate']->it ("Activate"), "activate_product");
                        }
                    }
                    // process the template for a single product
                    $content .= KCART_kCart::processTemplate ($template, "kcart", "listproducts_item.tpl");
                    // make a form for this product
                    $content .= PHPWS_Form::makeForm ("CART_productAction_".$product_code, "index.php", $elements, "post", NULL, NULL);
                    $content .= "</td></tr>";
                }
                $content .= "</table>";
            } else {
                $content = $_SESSION['translate']->it ("There are no products in the database at this time.");
            }

            // this section builds up the Create New Product button
            // set the module and cart op variable
            $elements[0] = PHPWS_Form::formHidden ("module", "kcart");
            $elements[0] .= PHPWS_Form::formHidden ("KCART_manage", "modifyProductList");
            $template['NEW_SUBMIT'] = PHPWS_Form::formSubmit ($_SESSION['translate']->it ("Create A New Product"), "create_new_product");
            $elements[0] .= KCART_kCart::processTemplate ($template, "kcart", "productmenu.tpl");
            $content .= PHPWS_Form::makeForm ("CART_product", "index.php", $elements, "post", NULL, NULL);

            $_SESSION['OBJ_layout']->popbox ($title, $content, NULL, "CNT_kcart_productmanager");
        }

        // this gets called when
        function modifyProductList ($cartSettings) {
            if (!$_SESSION['OBJ_user']->allow_access ("kcart")) {
                KCART_kCart::error("No access to manage Kcart");
            }

            // go through all the actions which modify the product list
            if (isset($_POST['create_new_product'])) {
                // if we are to create a new product
                KCART_Product::editProduct ("create","");
            } else if (isset ($_POST['edit_existing_product'])) {
                // present the panel to allow the user to edit an existing product 
                KCART_Product::editProduct ("edit",$_POST['CART_product_code']);
            } else if (isset($_POST['save_new_product'])) {
                // if we are to save the new product into the database and incorporate it into the product list
                // firstly, we save the new product details to the database
                KCART_Product::saveProduct (
                    array (
                        "product_code"           => PHPWS_Text::parseInput ($_POST["CART_product_code"]),
                        "product_description"    => PHPWS_Text::parseInput ($_POST["CART_product_description"]),
                        "product_price"          => PHPWS_Text::parseInput ($_POST["CART_product_price"]),
                        "product_activepages"    => PHPWS_Text::parseInput ($_POST["CART_product_activepages"]),
                        "product_imageurl_big"   => PHPWS_Text::parseInput ($_POST["CART_product_imageurl_big"]),
                        "product_imageurl_small" => PHPWS_Text::parseInput ($_POST["CART_product_imageurl_small"]),
                        "product_active"         => 0
                    )
                );
                KCART_ProductList::manageProductList ($cartSettings);
                KCART_kCart::managekCartSettings ($cartSettings);
            } else if (isset($_POST['save_existing_product'])) {
                // after a product has been edited, we need to update it's record in the database
                // note that the user might have changed the product code
                // if they did, we have to delete the original product entry and add a new one 
                if ($_POST['original_product_code'] != $_POST['CART_product_code']) {
                    // if the product code has changed
                    // save the new product entry
                    KCART_Product::saveProduct (
                        array (
                            "product_code"           => PHPWS_Text::parseInput ($_POST["CART_product_code"]),
                            "product_description"    => PHPWS_Text::parseInput ($_POST["CART_product_description"]),
                            "product_price"          => PHPWS_Text::parseInput ($_POST["CART_product_price"]),
                            "product_activepages"    => PHPWS_Text::parseInput ($_POST["CART_product_activepages"]),
                            "product_imageurl_big"   => PHPWS_Text::parseInput ($_POST["CART_product_imageurl_big"]),
                            "product_imageurl_small" => PHPWS_Text::parseInput ($_POST["CART_product_imageurl_small"]),
                            "product_active"         => PHPWS_Text::parseInput ($_POST["CART_product_active"])
                        )
                    );
                    // delete the old product code
                    KCART_Product::deleteProduct ($_POST['original_product_code']);
                } else {
                    // the product code hasn't changed 
                    // just save the new entry
                    KCART_Product::saveProduct (
                        array (
                            "product_code"           => PHPWS_Text::parseInput ($_POST["CART_product_code"]),
                            "product_description"    => PHPWS_Text::parseInput ($_POST["CART_product_description"]),
                            "product_price"          => PHPWS_Text::parseInput ($_POST["CART_product_price"]),
                            "product_activepages"    => PHPWS_Text::parseInput ($_POST["CART_product_activepages"]),
                            "product_imageurl_big"   => PHPWS_Text::parseInput ($_POST["CART_product_imageurl_big"]),
                            "product_imageurl_small" => PHPWS_Text::parseInput ($_POST["CART_product_imageurl_small"]),
                            "product_active"         => PHPWS_Text::parseInput ($_POST["CART_product_active"])
                        )
                    );
                }
                KCART_ProductList::manageProductList ($cartSettings);
                KCART_kCart::managekCartSettings ($cartSettings);
            } else if (isset($_POST['delete_product'])) {
                // if a product is to be deleted
                KCART_Product::deleteProduct ($_POST['CART_product_code']);
                KCART_ProductList::manageProductList ($cartSettings);
                KCART_kCart::managekCartSettings ($cartSettings);
            } else if (isset($_POST['activate_product'])) {
                // toggle the activation of a product
                KCART_Product::toggleProductActive($_POST['CART_product_code']);
                KCART_ProductList::manageProductList ($cartSettings);
                KCART_kCart::managekCartSettings ($cartSettings);
            }
        }

        /*
        * showProductList lists the products which are available to be added to the cart
        * for this page.  Products are defined as available for a list of PAGE_ids, so
        * this process involves finding out the current page id.
        */
        function showProductList ($cartSettings) {

            // if the cart is not active, then we're not going to list the products
            if (!$cartSettings["kcart_active"]) {
                return;
            }

            // work out the page ID
            $pageid = "unknown";
            $active_products = 0;
            if (isset($_POST["PAGE_id"])) {
                $pageid = $_POST["PAGE_id"];
            } else if (isset($_GET["PAGE_id"])) {
                $pageid = $_GET["PAGE_id"];
            } else {
                $pageid = $GLOBALS['core']->requestModule;
            }

            // get the array of products
            $products = KCART_ProductList::getProductList();

            // if there are no products
            if (count($products) <= 0) {
                return;
            }

            $template['PRODUCT_DESCRIPTION_TEXT'] = $_SESSION['translate']->it ("Description");
            $template['PRODUCT_PRICE_TEXT'] = $_SESSION['translate']->it ("Price");
            if ($cartSettings["show_buynow"] == 0) {
                $template['PRODUCT_QUANTITY_TEXT'] = $_SESSION['translate']->it ("Quantity");
                $template['ACTIONS_TEXT'] = $_SESSION['translate']->it ("Actions");
                $content = KCART_kCart::processTemplate ($template, "kcart", "cart/availableproducts_header.tpl");
            } else if ($cartSettings["show_buynow"] == 1) {
                $template['ACTIONS_TEXT'] = $_SESSION['translate']->it ("Actions");
                $content = KCART_kCart::processTemplate ($template, "kcart", "buynow/availableproducts_header.tpl");
            }
            /* step through each product ... */
            foreach ($products as $index => $thisproduct) {
                /* if the product is active ... */
                if ($thisproduct["product_active"] == 1) {
                    /* if the product is active _on_this_page_ ... */
                    if (strstr ($thisproduct["product_activepages"], ":$pageid:")) {
                        /* increase the active products counter */
                        $active_products++;
                        $template['PRODUCT_IMAGE'] = KCART_Product::formatImage($thisproduct["product_imageurl_small"], $thisproduct["product_imageurl_big"]);
                        $template['PRODUCT_DESCRIPTION'] = $thisproduct["product_description"];
                        $template['PRODUCT_PRICE'] = sprintf("%s%.2f",$cartSettings["currency_symbol"], $thisproduct["product_price"]);
                        if ($cartSettings["show_buynow"] == 1) {
                            // if we just provide a "buy now" button"
                            $template['SUBMIT'] = KCART_PaymentProcessors::buildBuyNowForms(
                                $cartSettings,
                                $thisproduct["product_code"],
                                $thisproduct["product_description"],
                                $thisproduct["product_price"],
                                1
                            );
                            $content .= KCART_kCart::processTemplate ($template,"kcart","buynow/availableproducts_item.tpl");
                        } else if ($cartSettings["show_buynow"] == 0) {
                            // if we provide a cart, and not just buynow buttons
                            $template['PRODUCT_QUANTITY'] = PHPWS_Form::formTextField ("CART_product_quantity", "", 5);
                            $template['SUBMIT'] = KCART_PaymentProcessors::formSubmitImage (
                                $_SESSION['translate']->it ("Add to cart"),
                                KCART_PaymentProcessors::return_add2cart_image($cartSettings)
                            );
                            $hiddens = array("KCART_user" => "addToCart", "CART_product_code" => $thisproduct["product_code"]);
                            $elements[0] = PHPWS_Form::formHidden ($hiddens);
                            $elements[0] .= KCART_kCart::processTemplate ($template, "kcart", "cart/availableproducts_item.tpl");
                            $content .= PHPWS_Form::makeForm ("KCART_user", "index.php", $elements, "post", NULL, NULL);

                        }
                    }
                }
            }
            $content .= "</table>";
            /* if there were some active products ... */
            if ($active_products > 0) {
                /* define the content for our block */
                $GLOBALS['CNT_kcart_products']['title'] = $_SESSION['translate']->it("Order Products");
                $content .= "<i>" . $_SESSION['translate']->it ($cartSettings["currency_description"]) . "</i>\n";
                $GLOBALS['CNT_kcart_products']['content'] = $content;
            } else {
                $GLOBALS['CNT_kcart_products']['title'] = "";
                $GLOBALS['CNT_kcart_products']['content'] = "";
            }

        }
    }
?>
