#!/usr/bin/php
<?php
    define('CRLF',"\r\n");
    ini_set('include_path',ini_get('include_path') . ":/data/sites/www.landscapeonline.com/includes");

    $requiredClasses[] = 'base/vendor_listing.php';
    $requiredClasses[] = 'base/xlist_class.php';

    require('lol_common.inc');
    
    $xl = new xlist();
    $query = "SELECT id, xlist, status FROM new_vendor WHERE active=1";

    $vlist = $xl->db->getAll($query);

    if(DB::isError($vlist)) {
        printf("Error getting vendor list: "  . $vlist->getMessage() . CRLF);
        return(FALSE);
    }


    $vXl = array();
    // $vlist is a set of hashes with id, xlist, status of vendors
    //  xlist is the comma separated list of xlist_ids
    foreach($vlist as $id => $obj) {
        // for each xlist_id in the xlist of each vendor
        foreach(explode(',',$obj['xlist']) as $x) {
            // add an entry to the stack of xlist counts
            $vXl[] = $x;
        }
    }

    // zzz = [xlist_id] => count
    $zzz = array_count_values($vXl);

    printf("Total Vendors: " . count($vlist) . CRLF);

    $parents = $xl->fetchXlistParentArray();
    foreach($parents as $p) {
        print("{$p['id']}: {$p['name']}" . CRLF);
        $children = $xl->fetchXlistChildrenArray($p['id']);
        $pCount = 0;
        $conditions = array();
        foreach($children as $c) {
            if(!array_key_exists($c['id'], $zzz)) {
                $zzz[$c['id']] = 0;
            } else {
            }
            $pCount += $zzz[$c['id']];
            print("\t{$c['sub_number']}:: {$c['name']}: {$zzz[$c['id']]}" . CRLF);
            $conditions[] = "find_in_set(" . $c['id'] . ", xlist)";
        }
        // recalc total
        print(CRLF . "*** Total entries (not companies) for {$p['name']}: {$pCount} ***" .  CRLF);
        // find the total number of --companies-- that match for this parent
        // SELECT count(id) FROM new_vendor WHERE ( find_in_set(xid[0], xlist) OR find_in_set(xid[1], xlist) OR.. )
        $query = "SELECT count(id) FROM new_vendor WHERE (". implode(" OR ", $conditions) .") AND active=1";
        $count = $xl->db->getOne($query);
        print(CRLF . "*************** Unique Companies: $count *****************" . CRLF . CRLF);

    }
?>
