<?php
    // $Id: kCart.php,v 1.10 2004/12/18 17:32:07 doug Exp $
    // KCART_kCart class - primarily routines for the kCart settings
    // but also other routines which are generally useful
    // Doug Rinckes

    // require the core classes
    // because phpwebsite changed the way to get the source directory, use
    // getSourceDir() as a version independent solution
    require_once(KCART_kcart::getSourceDir() . "core/Form.php");
    require_once(KCART_kcart::getSourceDir() . "core/Text.php");
    require_once(KCART_kcart::getSourceDir() . "core/Template.php");
    require_once(KCART_kcart::getSourceDir() . "core/WizardBag.php");
    require_once(KCART_kcart::getSourceDir() . "mod/kcart/class/PaymentProcessors.php");
    require_once(KCART_kcart::getSourceDir() . "mod/kcart/class/ProductList.php");
    require_once(KCART_kcart::getSourceDir() . "mod/kcart/class/Product.php");
    require_once(KCART_kcart::getSourceDir() . "mod/kcart/class/UserCart.php");



    class KCART_kCart {
        function error ($error_message) {
            // produce an error popbox
            $title = "<span class=\"errortext\">".$_SESSION['translate']->it ("Error")."</span>";
            $content = $error_message;

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


        function checkDBversion($show_error) {
            // get the current kcart version
            // if it is not correct, then display an error message

            // the current version - not stored in a session variable
            $my_current_version = "2.6.1";

            if (!($row = $GLOBALS['core']->sqlSelect("mod_boost_version", "mod_title", "kcart")))
            return FALSE;
            $installed_version = $row[0]["version"];
            if ($installed_version != $my_current_version) {
                if ($show_error == "yes") {
                    KCART_kCart::error("The KCart shopping cart module is being updated and is temporarily disabled until it is installed and re-activated by the administrator.<p>The current version is $installed_version, the new version is $my_current_version.");
                }
                // the versions do not match
                return FALSE;
            } else {
                // the versions do match
                return TRUE;
            }
        }

        function readCartSettings () {
            // read in the cart settings from the database
            // if they don't exist, initialise with default values
            // puts the settings into the class wide variable classSettings, also
            // returns it in case you are calling it from outside the class
            // note that it does not read in the products

            // read from database
            $cart_config = $GLOBALS['core']->sqlSelect ("mod_kcart_global", "id", 1);
            // if the read failed...
            if (!$cart_config) {
                // the settings are NOT stored in the database
                // so we need to initialise with defaults

                // set the dbversion to the current version of this module stored in boost
                if (!($row = $GLOBALS['core']->sqlSelect("mod_boost_version", "mod_title", "kcart")))
                return FALSE;
                $my_version = $row[0]["version"];
                // create an array with the defaults specified
                $cartSettings = array (
                    "currency_symbol" => PHPWS_Text::parseInput("$"),
                    "currency_code" => PHPWS_Text::parseInput("USD"),
                    "currency_description" => PHPWS_Text::parseInput("All prices are in US dollars"),
                    "viewcart_img_url" => PHPWS_Text::parseInput(""),
                    "emptycart_img_url" => PHPWS_Text::parseInput(""),
                    "add2cart_img_url" => PHPWS_Text::parseInput(""),
                    "updatecart_img_url" => PHPWS_Text::parseInput(""),
                    "show_buynow" => "0",
                    "kcart_active" => 0,
                    "dbversion" => $my_version
                );
                // store the array in database
                $cart_config = $GLOBALS['core']->sqlInsert ($cartSettings, "mod_kcart_global", TRUE, TRUE, FALSE);
                if (!$cart_config) {
                    KCART_kCart::error("SQL Insert failed\n");
                }
            } else {
                // read from database succeeded
                // parse in the database values into the cartSettings array
                foreach (array_keys($cart_config[0]) as $setting_key) {
                    $cartSettings[$setting_key] = $cart_config[0][$setting_key];
                }
            }

            // read the payment processor settings from the database
            $pp_settings = $GLOBALS['core']->sqlSelect ("mod_kcart_pp_settings");
            if ($pp_settings) {
                // for each row of settings we read in, step through the rows
                for ($row_key = 0;$row_key < count($pp_settings);$row_key ++) {
                    // transfer the value into the cartSettings array
                    $cartSettings[$pp_settings[$row_key]['name']] = $pp_settings[$row_key]['value'];
                }
            }
            // get defaults from the payment processor classes
            // the payment processor must check for it's settings and not overwrite them if already set
            $cartSettings = KCART_PaymentProcessors::PPdefaults($cartSettings);
            // return the array
            return($cartSettings);
        }


        function updateCartSettings ($cartSettings) {
            // store the array of settings into the database
            // the settings are either global, or related to a payment processor.  
            // payment processor settings begin with pp_ and are written to the mod_kcart_pp_setting table
            // all other settings are written to the mod_kcart_global table

            // first, split the settings into two arrays
            $global_settings = array();
            $pp_settings = array();
            // delete the payment processor settings
            if (!$GLOBALS['core']->query("DELETE FROM mod_kcart_pp_settings",TRUE)) {
                KCART_kCart::error("Update of cart settings failed\n");
            }
            // set the dbversion to the correct version
            if (!($row = $GLOBALS['core']->sqlSelect("mod_boost_version", "mod_title", "kcart")))
            return FALSE;
            $cartSettings["dbversion"] = $row[0]["version"];


            // for each setting
            foreach (array_keys($cartSettings) as $setting_key) {
                // if it is a payment processor setting
                if (strstr($setting_key,"pp_") == $setting_key) {
                    // put it into the pp table
                    $pp_settings['name'] = $setting_key;
                    $pp_settings['value'] = $cartSettings[$setting_key];
                    $GLOBALS['core']->sqlInsert ($pp_settings, "mod_kcart_pp_settings", TRUE, FALSE, FALSE, FALSE);
                } else {
                    // otherwise it is a global setting
                    $global_settings[$setting_key] = $cartSettings[$setting_key];
                }
                // write the global settings
                if (!$GLOBALS['core']->sqlUpdate ($global_settings, "mod_kcart_global", "id", 1)) {
                    KCART_kCart::error("Update of cart settings failed\n");
                }
            }
        }


        function managekCartSettings ($cartSettings) {
            // process or create the form allowing the user to adjust all the cart settings

            // set the panel layout and title
            // get the current kcart version
            if (!($row = $GLOBALS['core']->sqlSelect("mod_boost_version", "mod_title", "kcart")))
            return FALSE;
            $my_version = $row[0]["version"];
            $GLOBALS["CNT_kcart_productmanager"]['title'] = "KCart v".$my_version;

            // if we are here because the user has submitted the form...
            if (isset($_POST['CART_updateSettings'])) {
                // then for each key of the $_POST array, set the cartSettings to that value
                foreach (array_keys($_POST) as $post_key) {
                    // if the key starts with CART_, then process it
                    if (strstr($post_key,"CART_")) {
                        $sub_post_key = substr($post_key,5);
                        // if the key is already in the cart settings array...
                        if (in_array($sub_post_key,array_keys($cartSettings))) {
                            // then we can configure the setting
                            $cartSettings[substr($post_key,5)] = PHPWS_Text::parseInput ($_POST[$post_key]);
                        }
                    }
                }
            }

            // if the carts active/inactive state has been toggled...
            if (isset($_POST['CART_updateActive'])) {
                // toggle the value
                PHPWS_WizardBag::toggle($cartSettings["kcart_active"]);
            }
            // update the cart settings in the database
            KCART_kCart::updateCartSettings($cartSettings);
            // display the cart setting form
            KCART_kCart::displayCartSettings($cartSettings);
            // update the cart settings in the database again - the display routines in the payment processors
            // _can_ change the values
            KCART_kCart::updateCartSettings($cartSettings);
        }

        function displayCartSettings (&$settings) {
            // display the settings on the screen
            // settings is passed by reference because the display routines can change the settings

            // create a number of hidden form elements
            $elements[0] = PHPWS_Form::formHidden ("module", "kcart");
            $elements[0] .= PHPWS_Form::formHidden ("KCART_manage", "manageCart");
            $elements[0] .= PHPWS_Form::formHidden ("CART_updateActive", 1);

            // if the cart is currently active
            if ($settings["kcart_active"]) {
                // create a button to deactivate it
                $template['STATE'] = $_SESSION['translate']->it ("The cart is active");
                $template['SUBMIT'] .= PHPWS_Form::formSubmit ($_SESSION['translate']->it ("Deactivate shopping cart"), "CART_activity");
            } else {
                // otherwise, create a button to activate it
                $template['STATE'] = $_SESSION['translate']->it ("The shopping cart is NOT active");
                $template['SUBMIT'] .= PHPWS_Form::formSubmit ($_SESSION['translate']->it ("Activate shopping cart"), "CART_activity");
            }
            $elements[0] .= KCART_kCart::processTemplate ($template, "kcart", "cart_activate.tpl");
            $content .= PHPWS_Form::makeForm ("CART_activity", "index.php", $elements, "post", NULL, NULL);
            $content .= "<p>";

            // get down the the cart settings proper
            $textfield_short = 5;
            $textfield_long = 40;
            $elements[0] = PHPWS_Form::formHidden ("module", "kcart");
            $elements[0] .= PHPWS_Form::formHidden ("KCART_manage", "manageCart");
            $elements[0] .= PHPWS_Form::formHidden ("CART_updateSettings", 1);
            $template['CURRENCY_CODE_TEXT'] = $_SESSION['translate']->it ("Currency Code");
            $template['CURRENCY_SYMBOL_TEXT'] = $_SESSION['translate']->it ("Currency Symbol");
            $template['CURRENCY_DESCRIPTION_TEXT'] = $_SESSION['translate']->it ("Currency Description");
            $template['IMAGE_SETTINGS_TEXT'] = $_SESSION['translate']->it ("Image Settings");
            $template['VIEWCART_IMG_TEXT'] = $_SESSION['translate']->it ("View Cart Image URL");
            $template['EMPTYCART_IMG_TEXT'] = $_SESSION['translate']->it ("Empty Cart Image URL");
            $template['ADD2CART_IMG_TEXT'] = $_SESSION['translate']->it ("Add To Cart Image URL");
            $template['UPDATECART_IMG_TEXT'] = $_SESSION['translate']->it ("Update Cart Image URL");
            $template['SHOW_BUYNOW_TEXT'] = $_SESSION['translate']->it ("Buy Now Buttons Or Shopping Cart");
            $template['CURRENCY_HELP'] = $_SESSION['OBJ_help']->show_link("kcart", "currency");
            $template['BUYNOW_HELP'] = $_SESSION['OBJ_help']->show_link("kcart", "buynow");
            $template['IMAGES_HELP'] = $_SESSION['OBJ_help']->show_link("kcart", "images");
            $template['CURRENCY_CODE'] = PHPWS_Form::formTextField ("CART_currency_code", 
            $settings["currency_code"], $textfield_short);
            $template['CURRENCY_SYMBOL'] = PHPWS_Form::formTextField ("CART_currency_symbol", 
            $settings["currency_symbol"], $textfield_short);
            $template['CURRENCY_DESCRIPTION'] = PHPWS_Form::formTextField ("CART_currency_description", 
            $settings["currency_description"], $textfield_long);
            $template['VIEWCART_IMG_URL'] = PHPWS_Form::formTextField ("CART_viewcart_img_url", 
            $settings["viewcart_img_url"], $textfield_long);
            $template['EMPTYCART_IMG_URL'] = PHPWS_Form::formTextField ("CART_emptycart_img_url", 
            $settings["emptycart_img_url"], $textfield_long);
            $template['ADD2CART_IMG_URL'] = PHPWS_Form::formTextField ("CART_add2cart_img_url", 
            $settings["add2cart_img_url"], $textfield_long);
            $template['UPDATECART_IMG_URL'] = PHPWS_Form::formTextField ("CART_updatecart_img_url", 
            $settings["updatecart_img_url"], $textfield_long);
            $template['SHOW_BUYNOW'] = PHPWS_Form::formRadio (
                "CART_show_buynow",0,
                $settings["show_buynow"],
                NULL,
                $_SESSION['translate']->it ("Provide a full shopping cart")."<p>"
            );
            $template['SHOW_BUYNOW'] .= PHPWS_Form::formRadio (
                "CART_show_buynow",1,
                $settings["show_buynow"],
                NULL,
                $_SESSION['translate']->it ("Simply show Buy Now buttons on each product")
            );

            $elements[0] .= KCART_kCart::processTemplate ($template, "kcart", "cart_settings.tpl");

            // configure each of the payment processors
            // settings can be modified by the payment processors configure routines
            // e.g., to update the exchange rate
            $elements[0] .= KCART_PaymentProcessors::configPP($settings);

            $template = array();
            // create the form for updating the settings
            $template['SUBMIT'] = PHPWS_Form::formSubmit ($_SESSION['translate']->it ("Update Global Settings"), "CART_settings");
            $elements[0] .= KCART_kCart::processTemplate ($template, "kcart", "form_submit.tpl");
            $content .= PHPWS_Form::makeForm ("CART_settings", "index.php", $elements, "post", NULL, NULL);

            // create the form for exporting the settings
            $elements[0] = PHPWS_Form::formHidden ("module", "kcart");
            $elements[0] .= PHPWS_Form::formHidden ("KCART_manage", "exportSettings");
            $template['SUBMIT'] = PHPWS_Form::formSubmit ($_SESSION['translate']->it ("Export/Import Settings"), "CART_export");
            $template['SUBMIT_HELP'] = $_SESSION['OBJ_help']->show_link("kcart", "export");
            $elements[0] .= KCART_kCart::processTemplate ($template, "kcart", "form_submit.tpl");
            $content .= PHPWS_Form::makeForm ("CART_export", "index.php", $elements, "post", NULL, NULL);

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


        function exportCartSettings ($cartSettings) {
            // display the cart settings in a text window so that they can be edited, and then re-imported

            // define the field separator
            $separator = "^";

            if (!$_SESSION['OBJ_user']->allow_access ("kcart")) {
                KCART_kCart::error("No access to export settings");
                return;
            }

            // set the panel layout and title
            $GLOBALS["CNT_kcart_productmanager"]['title'] = "KCart: ".$_SESSION['translate']->it ("Export Settings");
            // print the settings into a variable
            foreach (array_keys($cartSettings) as $var) {
                // don't export the dbversion
                if ($var != "dbversion") {
                    $settings .= "setting'$var$separator".$cartSettings[$var]."$separator\n";
                }
            }
            // get the product array
            $products = KCART_ProductList::getProductList();
            // for each product
            foreach ($products as $index => $thisproduct) {
                // print the products into the variable
                $settings .= "product'".$thisproduct["product_code"] . "$separator" .
                $thisproduct["product_description"] . "$separator" .
                $thisproduct["product_price"] . "$separator" . 
                $thisproduct["product_activepages"] . "$separator" .
                $thisproduct["product_active"] . "$separator" .
                $thisproduct["product_imageurl_big"] . "$separator" .
                $thisproduct["product_imageurl_small"] . "$separator\n";
            }


            // create a text area with all the settings in it
            $template["SETTINGS"] = PHPWS_Form::formTextArea ("CART_exportsettings", $settings, 20, 80);
            // create the submit button
            $template["UPDATE"] = PHPWS_Form::formSubmit ($_SESSION['translate']->it ("Import Settings and Products"), "CART_import");
            // create the help button
            $template['IMPORT_HELP'] = $_SESSION['OBJ_help']->show_link("kcart", "import");
            // add the hidden input - identify the module
            $elements[0] = PHPWS_Form::formHidden ("module", "kcart");
            // add the hidden input - identify the operation
            $elements[0] .= PHPWS_Form::formHidden ("KCART_manage", "importSettings");
            // process the template
            $elements[0] .= KCART_kCart::processTemplate ($template, "kcart", "export.tpl");
            // make the form
            $content = PHPWS_Form::makeForm ("CART_import", "index.php", $elements, "post", NULL, NULL);
            // create a button to take us back to the management panel
            $content .= KCART_kCart::managekCartButton($_SESSION['translate']->it("Cancel"));

            // populate the popbox
            $_SESSION['OBJ_layout']->popbox ("Export Settings and Products", $content, NULL, "CNT_kcart_productmanager");
        }


        function importCartSettings () {
            // read in the cart settings that were displayed by exportCartSettings
            // and produce a log describing what has been done

            if (!$_SESSION['OBJ_user']->allow_access ("kcart")) {
                KCART_kCart::error("No access to import settings");
                return;
            }

            // define the field separator list - changed in one version of KCart rather stupidly
            // from # to ^ so now we have to support both
            $separator_list = array(0 => "^", 1 => "#");

            // set the panel layout and title
            $GLOBALS["CNT_kcart_productmanager"]['title'] = "KCart: ".$_SESSION['translate']->it ("Import Settings Log");
            // get in the posted settings from the users submission
            $settings = $_POST["CART_exportsettings"];
            // convert the settings lines into an array
            $lines = explode("\n",$settings);

            // process the posted settings for each line
            foreach ($lines as $line) {
                // break up the line into fields by apostrophe
                $fields = explode("'",$line);
                // break up the first field into multiple fields using $separator
                foreach ($separator_list as $separator) {
                    if (strchr($fields[1],$separator)) {
                        $values = explode("$separator",$fields[1]);
                        break;
                    }
                }
                // if this is a SETTING...
                if (strstr($fields[0],"setting")) {
                    // then the key and value are $values[0] and $values[1]
                    // but we don't want to import the dbversion
                    if ($values[0] != "dbversion") {
                        $cartSettings[$values[0]] = $values[1];
                        // add to the log message
                        $content .= "$values[0] = \"$values[1]\"\n";
                    }
                } else if (strstr($fields[0], "product")) {
                    // it wasn't a setting, it is a product definition
                    // create a new product using the values
                    // note that field 4 is the active flag
                    KCART_Product::saveProduct(
                        array(
                            "product_code"           => $values[0],
                            "product_description"    => $values[1],
                            "product_price"          => $values[2],
                            "product_activepages"    => $values[3],
                            "product_active"         => $values[4],
                            "product_imageurl_big"   => $values[5],
                            "product_imageurl_small" => $values[6]
                        )
                    );
                    // add to the log message
                    $content .= $_SESSION['translate']->it ("Creating product") . " $values[0]\n";
                }
            }
            // update the cart settings into the database
            KCART_kCart::updateCartSettings($cartSettings);
            // generate the popbox with the log messages
            $template["SETTINGS"] = PHPWS_Form::formTextArea ("CART_exportsettings", $content, 20, 100);
            // process the template
            $elements[0] .= KCART_kCart::processTemplate ($template, "kcart", "export.tpl");
            // make the form
            $content = PHPWS_Form::makeForm ("CART_import", "index.php", $elements, "post", NULL, NULL);
            // create a button to take us back to the management panel
            $label = $_SESSION['translate']->it("Go Back");
            $content .= KCART_kCart::managekCartButton($label);

            $GLOBALS["CNT_kcart_productmanager"]['content'] = $content;
            return($cartSettings);
        }


        // return whether kCart is active or not
        function isActive($cartSettings) {
            return($cartSettings["kcart_active"]);
        }

        function managekCartButton ($label) {
            if (!isset($label)) {
                $label = $_SESSION['translate']->it("Go Back");
            }
            // create the button to go back to the main kCart management page
            $template["SUBMIT"] = PHPWS_Form::formSubmit ($_SESSION['translate']->it ($label), "CART_import");
            // add the hidden input - identify the module
            $elements[0] = PHPWS_Form::formHidden ("module", "kcart");
            // add the hidden input - identify the operation
            $elements[0] .= PHPWS_Form::formHidden ("KCART_manage", "manageCart");
            $elements[0] .= KCART_kCart::processTemplate ($template, "kcart", "form_submit.tpl");
            $content = PHPWS_Form::makeForm ("CART_managebutton", "index.php", $elements, "post", NULL, NULL);
            return($content);
        }

        // work out our source http address.
        // another dirty hack to retain backwards compatibility
        function returnSourceHttp () {
            $source = PHPWS_SOURCE_HTTP;
            return($source);
        }


        // some versions of processTemplate return nothing if there are no
        // substitions made.  To cope with this, we add an entry to the template
        // array so we can make a substitution.
        function processTemplate(&$template_array,$module,$file) {

            $template_array["NULL"] = " ";
            return(PHPWS_Template::processTemplate($template_array,$module,$file));
        }


        // function to get the source directory of the phpwebsite install
        function getSourceDir() {
            return(PHPWS_SOURCE_DIR);
        }
    }
?>
