<?php
// Ben Sibelman, 1/21/2008
// updatehtml.php: This code is called whenever the Linkbar site administrator adds, modifies, or deletes any
// item in the shopping directory tree (category, subcategory, or link).  It regenerates the cached HTML code
// for the shopping directory, which is later processed to add custom user-specific information and displayed
// on the Linkbar.org main page.

// Helper function for sorting links by donation amount, putting links with absolute per-purchase dollar amounts first,
// followed by links with purchase percentage amounts, then links with no donation amount and finally subcategory titles.
function donatesort ($item1, $item2) {
    if (strpos($item1['rate'], '$') === false) {
        if (strpos($item2['rate'], '$') === false) {
            if ($item1['rate'] != "" && $item2['rate'] != "") {    // They both have a percent amount
                if ((float)$item1['rate'] < (float)$item2['rate']) {
                    return 1;   // item1 has a lower percentage, so it goes later in the list
                } else if ((float)$item1['rate'] > (float)$item2['rate']) {
                    return -1;
                } else {
                    return strcasecmp($item1['name'], $item2['name']);  // only if rates are equal do we do a string comparison
                }
            } else if ($item1['rate'] == "" xor $item2['rate'] == "") { // One has a donation amount, the other doesn't
                if ($item1['rate'] != "" && $item2['rate'] == "") {
                    return -1;  // Links with a donation amount amount go before links without one
                } else {
                    return 1;
                }
            } else {            // Neither item has a percent amount
                if ($item1['subcategory'] == 0 && $item2['subcategory'] > 0) {
                    return -1;  // Links with no donation amount go before subcategories
                } else if ($item1['subcategory'] > 0 && $item2['subcategory'] == 0) {
                    return 1;
                } else {
                    return strcasecmp($item1['name'], $item2['name']);  // only if all else is equal do we do a string comparison
                }
            }
        } else {
            return 1;   // item2 has a dollar amount, item1 doesnt, so item2 goes first
        }
    } else {
        if (strpos($item2['rate'], '$') === false) {
            return -1;     // item1 has a dollar amount, item2 doesn't, so item1 goes first
        } else {           // They both have a dollar amount
            $rate1 = (float)substr($item1['rate'], 1);
            $rate2 = (float)substr($item2['rate'], 1);
            if ($rate1 < $rate2) {
                return 1;  // item1 has a lower dollar amount, so it goes later in the list
            } else if ($rate1 > $rate2) {
                return -1;
            } else {
                return strcasecmp($item1['name'], $item2['name']); // only if rates are equal do we do a string comparison
            }
        }
    }
}

// Helper function for producing the HTML for a link, with appropriate Member ID tag.
function linkcode ($fields)
{
    $linkhtml = "<a href='" . $fields['link'];
    if (substr($fields['link'], strlen($fields['link']) - 1) == '=') {
        $linkhtml .= "*****";   // This will be replaced by the appropriate Member ID code before the HTML is displayed
    } else {
        if (substr_count($fields['link'], "clickserve.cc-dt.com") > 0) {     // Add appropriate Member ID field if none is present
            $linkhtml .= "&mid=*****";
        } else if (substr_count($fields['link'], "click.linksynergy.com") > 0) {
            $linkhtml .= "&u1=*****";
        } else if (substr_count($fields['link'], "service.bfast.com") > 0) {
            $linkhtml .= "&bfinfo=*****";
        }
    }
    $linkhtml .= "' target='_blank'>" . $fields['name'] . "</a>";
    return $linkhtml;
}

// This function updates the stored HTML code for the shopping directory.
function linkbar_shopdir_adminapi_updatehtml ($args)
{
    // Get the shopping links, categories, and subcategories
    // (note: 10000 is an arbitrary upper limit we're unlikely to ever reach)
    $values = xarModAPIFunc('dynamicdata','user','getitems',
                                 array('module'   => 'linkbar_shopdir',
                                       'itemtype' => 0,
                                       'numitems' => 10000,
                                       'startnum' => 1));

    // This is the array that contains the whole tree, with the first level indexed by category name,
    // the second level by the row IDs of links and subcategory title entries within the category,
    // the third level by property names of those entries as well as a 'subcategories' item for subcategory titles,
    // and the levels under 'subcategories' being indexed again by link row IDs and then by property names
    $categories = array();

    // We map the category IDs to their names, which serve as the keys to the $categories array, in this reference array
    $cattable = array();

    // To sort the links in subcategories, we need to store the ID of the subcategory title entry
    // indexed by its category and subcategory ID
    $subcattable = array();

    // First find all the category titles (link & subcategory fields blank) and sort them alphabetically
    foreach ($values as $fields) {
        if ($fields['link'] == "" && $fields['subcategory'] == 0) {
            $categories[$fields['name']] = array();
            $cattable[$fields['category']] = $fields['name'];
            $subcattable[$fields['name']] = array();  // Leave room for a list of subcategories
        }
    }
    ksort($categories);

    // Then sort the links outside subcategories (subcategory field blank)
    // and the subcategory titles (link field blank) into the categories
    foreach ($values as $itemid => $fields) {
        if ($fields['link'] != "" xor $fields['subcategory'] > 0) {
            $catname = $cattable[$fields['category']];  // Retrieve the category name for this item's category ID
            $categories[$catname][$itemid] = $fields;   // Store all the row's field/property values under its row ID

            if ($fields['subcategory'] > 0) { // Subcategory title
                $categories[$catname][$itemid]['subcategories'] = array(); // Leave room for a list of child links
                $subcattable[$catname][$fields['subcategory']] = $itemid;  // Store the subcategory parent's ID
            }
        }
    }

    // Finally, sort remaining links into subcategories
    foreach ($values as $itemid => $fields) {
        if ($fields['link'] != "" && $fields['subcategory'] > 0) {
            $catname = $cattable[$fields['category']];  // Retrieve the category name for this item's category ID
            $parentid = $subcattable[$catname][$fields['subcategory']];  // Retrieve the parent ID of this subcategory
            $categories[$catname][$parentid]['subcategories'][$itemid] = $fields;
        }
    }

    // Sort the links within categories and subcategories by their donation amounts
    foreach ($categories as $catname => $category) {
        uasort($categories[$catname], "donatesort");
        foreach($subcattable[$catname] as $itemid) {
            if (isset($categories[$catname][$itemid]['subcategories'])) {
               if (is_array($categories[$catname][$itemid]['subcategories'])) {
                   usort($categories[$catname][$itemid]['subcategories'], "donatesort");
               }
            }
        }
    }

    // Write the HTML
    $html = '<table width="100%"  border="0" cellspacing="0" cellpadding="0">
                    <tr>
                      <td width="5px"> </td>
                      <td width="283px" align="left" valign="top">
                          <table width="100%"  border="0" cellpadding="0" cellspacing="0">';

    $classicthemedir = xarTplGetThemeDir(); // Current theme (had better be the Linkbar theme or one very similar)
    $half = intval(count($categories)/2);
    $catnum = 1;
    foreach ($categories as $catname => $category) {
        if (count($category) > 3 || count($subcattable[$catname]) > 0) {
             $tablestyle = 'display: none;';    // This section is large enough to be closeable
        } else {
             $tablestyle = '';
        }
        $html .= "<tr>
                    <td width='28' align='center' valign='top'><div style='padding-top:5px '><img src='$classicthemedir/images/123.jpg' width='6' height='6'></div></td>
                    <td align='left' valign='top'>";
        if($tablestyle != '') {
            $html .= "<a onclick='javascript:ExpandCollapse($catnum)' class='category_header' style='cursor:pointer'>$catname</a><br>";

            // List of first three links in this category
            $html .= "<div id='quick-$catnum' class='shortlist_link'>";
            $i = 0;
            foreach ($category as $fields) {
                if ($fields['subcategory'] == 0) {
                    $html .= linkcode($fields) . ", ";
                    $i++;
                } else {    // Search inside subcategories in case there aren't three links outside subcategories
                    foreach ($fields['subcategories'] as $fields2) {
                        $html .= linkcode($fields2) . ", ";
                        $i++;
                        if ($i == 3) break;
                    }
                }
                if ($i == 3) break;
            }
            $html .= "...</font></div>";
        } else {
            $html .= "<a class='category_header'>$catname</a><br>";
        }

        // Body of the category
        $html .= "<div id='rec-$catnum' style='$tablestyle'>
                    <table width='267px' cellspacing='0' cellpadding='0'>
                      <tbody width='267px'>";

        // Loop through the entries in the category
        foreach ($category as $fields) {
            if ($fields['subcategory'] == 0) {  // Ordinary link
                $html .= '<tr><td align="left" class="regular_link">' . linkcode($fields) . '</td>';

                // This cell of the table will be modified to either remove the donation rate or multiply it by the appropriate percentage,
                // which is why we write the ##### markers
                $html .= '<td align="right" class="regular_link"> #####' . $fields['rate'] . '#####</td></tr>';
            } else {  // Subcategory title
                $html .= '<tr><td align="left" colspan="2" class="regular_link"><u><i>' . $fields['name'];
                if (isset($fields['subcategories']) === FALSE || count($fields['subcategories']) == 0) {
                    $html .= " - empty</i></u></td></tr>"; // Subcategory has no links
                } else {   
                    $html .= '</i></u></td></tr>';

                    // Loop through links in the subcategory
                    foreach ($fields['subcategories'] as $fields2) {
                        $html .= '<tr><td align="left" class="regular_link">  ' . linkcode($fields2) . '</td>';
                        $html .= '<td align="right" class="regular_link"> #####' . $fields2['rate'] . '#####</td></tr>';
                    }
                }
            }
        }
        $html .= '</tbody></table></div></td></tr>';

        // Divider between first and second columns of the directory
        if ($catnum == $half) {
            $html .= '</table></td>
                      <td width="10"> </td>
                      <td width="267px" align="left" valign="top"><table width="100%"  border="0" cellpadding="0" cellspacing="0">';
        }
        $catnum++;
    }
    $html .= '</table>
              </td>
              <td colspan="2" rowspan="10" align="left" valign="top"> </td>
              <td width="20"> </td>
              </tr>
              </table>';

    // Write the template to shopdir.html
    $filename = "themes/shopdir.html";
    if (file_exists($filename)) {
        unlink($filename);
    }
    if (!$handle = fopen($filename, 'w')) {
        xarErrorSet(XAR_SYSTEM_EXCEPTION, 'MODULE_FILE_NOT_EXIST', new SystemException('Cannot open the template.'));
    }
    if (fwrite($handle, $html) === FALSE) {
        xarErrorSet(XAR_SYSTEM_EXCEPTION, 'MODULE_FILE_NOT_EXIST', new SystemException("Cannot write to file ($filename)."));
    }
    fclose($handle);

    return true;
}
?>