<?php
// print_r('xmap vehicle');exit;

/**
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @package Xmap VehicleManager
* @copyright (C) 2012 by OrdaSoft
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @description VehicleManager plugin for VehicleManager Component
*/

defined('_JEXEC') or die ('Direct Access to this location is not allowed.');

$f_path = JPATH_SITE.'/components/com_vehiclemanager/functions.php';
if (!file_exists($f_path)){
    echo "You need to install VehicleManager first<br />"; exit;
}
else require_once ($f_path);

//die("EXIT");

class xmap_com_vehiclemanager {
    var $orderby = 'title';

    function isOfType(&$xmap, &$menu){

        if (strpos($menu->link, 'option=com_vehiclemanager')){
            $menu->name="VehicleManager";
            $menu->option="com_vehiclemanager";
            return true;
        }
        return false;
    }


   public static function &getTree($xmap, &$menu, $params) {

        global $mosConfig_absolute_path;
        $list = array();
        $menu->name="VehicleManager";
        $menu->option="com_vehiclemanager";
        $menu->uid="com_vehiclemanager";

        $link_query = parse_url($menu->link);
        parse_str(html_entity_decode($link_query['query']), $link_vars);
        if (version_compare(JVERSION, "1.6.0", "lt")){
            $view = JArrayHelper::getValue($link_vars,'task','all_categories');
        } else {
            $view = JArrayHelper::getValue($link_vars,'view','all_categories');
        }

        switch ($view){
            case 'all_categories':

                // $catid = JArrayHelper::getValue($link_vars,'catid', 0);
                // xmap_com_vehiclemanager::getCategoryTree($xmap, $menu, $catid, $params);
                xmap_com_vehiclemanager::getCategoryTree($xmap, $menu, $params);
                break;

            case 'alone_category':
                if ($params['show_Vehicle'] == 'true')
                if (version_compare(JVERSION, "1.6.0", "lt")){
                    if (strpos($menu->params, 'catid=')!==false){
                        $catid = substr($menu->params, strpos($menu->params,'=',0)+1,
                                strpos($menu->params,'back',0)-strpos($menu->params,'=',0)-2);
                    }
                } else {
                    $catid = ($menu->params->get('single_category'));
                }

                xmap_com_vehiclemanager::singleCategoryHandler($xmap, $menu, $catid, $params);
                break;

            case 'my_vehicles':
            case 'show_my_cars':
                if ($params['show_Vehicle'] == 'true')
                xmap_com_vehiclemanager::myVehiclesHandler($xmap, $menu, $params);
                break;

            case 'owner_vehicles':
                if ($params['show_Vehicle'] == 'true')
                if (version_compare(JVERSION, "1.6.0", "lt")){
                    if (strpos($menu->params, 'username=')!==false){
                        $username = substr($menu->params, strpos($menu->params,'=',0)+1,
                                strpos($menu->params,'back',0)-strpos($menu->params,'=',0)-2);
                    }
                } else {
//                    $username = ($parent->params->getValue('username'));
                    $username = ($menu->params->get('username'));
                }

                xmap_com_vehiclemanager::singleUserVehiclesHandler($xmap, $menu, $username, $params);
                break;

            case 'owners_list':
                xmap_com_vehiclemanager::ownersListHandler($xmap, $menu, $params);
                break;

            case 'all_vehicle':
                if ($params['show_Vehicle'] == 'true')
                xmap_com_vehiclemanager::getAllVehicles($xmap, $menu, $params);
                break;

            default:
                break;
        }
        return $list;
    }

    static function getAllVehicles (&$xmap, &$menu, $params){
        $Itemid = $menu->id;
        if($params['orderby'] != 'title')
        {
          $orderby =$params['orderby'];
        }
        else
        {
          $orderby='vtitle';
        }
        $database = JFactory::getDBO();

        $s = vmLittleThings::getWhereUsergroupsCondition();
        $query = "SELECT distinct v.id AS id, v.vtitle, c.id AS catid
           \n FROM #__vehiclemanager_vehicles as v
           \n LEFT JOIN #__vehiclemanager_categories AS vc ON v.id=vc.iditem
           \n LEFT JOIN #__vehiclemanager_main_categories AS c ON c.id=vc.idcat
           \n WHERE v.published = '1' AND v.approved = '1' AND c.published = '1'
           AND (".$s.") GROUP BY v.id ORDER BY " . $orderby . "";
        $database->setQuery($query);
        $items = $database->loadObjectList();

        $xmap->changeLevel(1);

        foreach ($items as $vehicle)
            xmap_com_vehiclemanager::printNode($xmap, $menu, $Itemid, $vehicle->id, $vehicle->vtitle,
                    $vehicle->catid, $vehicle->id, true);

        $xmap->changeLevel(-1);
    }


   public static function getVehicles(&$xmap, &$menu, $subcat, $params){
        $Itemid = $menu->id;

        if($params['orderby'] != 'title')
        {
          $orderby =$params['orderby'];
        }
        else
        {
          $orderby='vtitle';
        }
        $xmap->changeLevel(1);

        $database = JFactory::getDBO();
        $s = vmLittleThings::getWhereUsergroupsCondition();

        $q = "SELECT distinct v.id AS id, v.vtitle, c.id AS catid
           \n FROM #__vehiclemanager_vehicles as v
           \n LEFT JOIN #__vehiclemanager_categories AS vc ON v.id=vc.iditem
           \n LEFT JOIN #__vehiclemanager_main_categories AS c ON c.id=vc.idcat
           \n WHERE v.published = '1' AND v.approved = '1' AND c.published = '1'
           AND (".$s.") AND vc.idcat = ".$subcat."
           \n GROUP BY v.id ORDER BY " . $orderby . "";
        $database->setQuery($q);
        $vehicles = $database->loadObjectList();

        foreach($vehicles as $vehicle){
            $node = new stdclass;
            $node->id = $vehicle->id;
            $node->uid = $vehicle->id;
            $node->name = $vehicle->vtitle;
            $node->parent=1;
            $node->browsNav=1;//open new window
            $node->ordering=2;
            $node->priority=$menu->priority;
            $node->chansefreq=$menu->changefreq;
            $node->changefreq=$menu->changefreq;
            $node->modified= date("Y-m-d h:i:s");
            $node->type='component';
            $node->menutype='mainmenu';
            $node->link ='index.php?option=com_vehiclemanager&amp;task=view_vehicle&amp;'
                    . 'catid='.$vehicle->catid.'&amp;id='.$vehicle->id.'&amp;Itemid='.$subcat;
            $xmap->printNode($node);
        }
        $xmap->changeLevel(-1);
    }


    public static function getCategoryTree(&$xmap, &$menu, $params){

        //xmap_com_vehiclemanager::header();
        global $my, $mosConfig_absolute_path;

        $database = JFactory::getDBO();
        $s = vmLittleThings::getWhereUsergroupsCondition();
        $q = "SELECT v.id AS id, v.vtitle AS title, c.name AS category, c.parent_id, c.id AS catid
              FROM #__vehiclemanager_vehicles AS v
              LEFT JOIN #__vehiclemanager_categories AS vc ON v.id=vc.iditem
              AND v.published=1 AND v.approved=1
              LEFT JOIN #__vehiclemanager_main_categories AS c ON c.id=vc.idcat
              WHERE (".$s.")
              AND c.published = '1'
              GROUP BY c.id
              ORDER BY c.parent_id, c.ordering";
        $database->setQuery($q);
        $cats = $database->loadObjectList();


        xmap_com_vehiclemanager::getSubCategory($xmap, $menu, $cats, $params);
    }


   public static function getSubCategory(&$xmap, &$menu, $cats, $params, $parentid = 0) {

        $link_query = parse_url($menu->link);
        parse_str(html_entity_decode($link_query['query']), $link_vars);
        $Itemid = $menu->id;

        $xmap->changeLevel(1);

        foreach($cats as $subcat){
            if($subcat->parent_id==$parentid){
                $node = new stdclass;
                $node->id = $menu->id;
                $node->uid=$menu->uid.'a'.$subcat->catid;
                $node->name = $subcat->category;
                $node->parent=1;
                $node->browsNav=1;
                $node->ordering=2;
                $node->priority=$menu->priority;
                $node->chansefreq=$menu->changefreq;
                $node->changefreq=$menu->changefreq;
                $node->modified= date("Y-m-d h:i:s");
                $node->type='component';
                $node->link = 'index.php?option=com_vehiclemanager&amp;task=showCategory&amp;'
                        . 'catid='.$subcat->catid.'&amp;Itemid='.$Itemid;
                $xmap->printNode($node);
                xmap_com_vehiclemanager::getSubCategory($xmap, $menu, $cats, $params, $subcat->catid);
                if ($params['show_Vehicle'] == 'true'){
                xmap_com_vehiclemanager::getVehicles($xmap, $menu, $subcat->catid, $params);
                }
            }
        }

        $xmap->changeLevel(-1);
    }


    public static function singleCategoryHandler(&$xmap, &$menu, &$catid, $params){
        // The [Single Category] menu type handler
        //xmap_com_vehiclemanager::header();
        $Itemid = $menu->id;
        if($params['orderby'] != 'title')
        {
          $orderby =$params['orderby'];
        }
        else
        {
          $orderby='vtitle';
        }
//        $database = &JFactory::getDBO();
        $database = JFactory::getDBO();
        $s = vmLittleThings::getWhereUsergroupsCondition();
        $query = "SELECT v.*,vc.idcat AS catid, c.title as category_titel
                  \n FROM #__vehiclemanager_vehicles AS v"
                ."\n LEFT JOIN #__vehiclemanager_categories AS vc ON vc.iditem=v.id"
                ."\n LEFT JOIN #__vehiclemanager_main_categories AS c ON c.id=vc.idcat"
                ."\n WHERE vc.idcat = '".$catid."' AND v.published='1' AND v.approved='1' "
                ."\n AND c.published='1' AND (".$s.")"
                ."\n GROUP BY v.id ORDER BY " . $orderby . "";
        $database->setQuery($query);
        $items = $database->loadObjectList();

        $xmap->changeLevel(1);

        foreach($items as $vehicle)
            xmap_com_vehiclemanager::printNode($xmap, $menu, $Itemid, $vehicle->id,
                    $vehicle->vtitle, $catid, $vehicle->id, true);



        $xmap->changeLevel(-1);
    }


   static function myVehiclesHandler(&$xmap, &$menu, $params){
        // The [my vehicles] menu type handler
        //xmap_com_vehiclemanager::header();
        $Itemid = $menu->id;
        if($params['orderby'] != 'title')
        {
          $orderby =$params['orderby'];
        }
        else
        {
          $orderby='vtitle';
        }
        $items = array();

        $my = JFActory::getUser();
        if (!isset($my->name)) return;

        $database = JFActory::getDBO();
        $q = "SELECT v.vtitle as title, v.id as id, c.id AS catid
              FROM `#__vehiclemanager_vehicles` AS v
              LEFT JOIN `#__users` AS u ON u.email=v.owneremail
              LEFT JOIN `#__vehiclemanager_categories` AS vc ON vc.iditem=v.id
              LEFT JOIN `#__vehiclemanager_main_categories` AS c ON vc.idcat=c.id
              WHERE v.owneremail = '".$my->email."'
              GROUP BY id ORDER BY " . $orderby . "";
        $database->setQuery($q);
        $items = $database->loadObjectList();

        $xmap->changeLevel(1);

        if (isset($items[0])) foreach ($items as $vehicle)
            xmap_com_vehiclemanager::printNode($xmap, $menu, $Itemid, $vehicle->id,
                    $vehicle->title, $vehicle->catid, $vehicle->id, true);

        $xmap->changeLevel(-1);
    }


    public static function singleUserVehiclesHandler(&$xmap, &$menu, &$username, $params){
        // The [Single User Vehicles] menu type handler
        //xmap_com_vehiclemanager::header();
        $Itemid = $menu->id;
        if($params['orderby'] != 'title')
        {
          $orderby =$params['orderby'];
        }
        else
        {
          $orderby='vtitle';
        }
//        $database = &JFactory::getDBO();
        $database = JFactory::getDBO();
        $q = "SELECT distinct v.*, c.id AS catid
              FROM `#__vehiclemanager_vehicles` AS v
              LEFT JOIN #__vehiclemanager_categories AS vc ON vc.iditem=v.id
              LEFT JOIN #__vehiclemanager_main_categories AS c ON c.id=vc.idcat
              LEFT JOIN `#__users` AS u ON u.email=v.owneremail
              WHERE v.approved = 1 AND c.published = 1 AND v.published = 1 AND
              u.id='".$username."'
              GROUP BY v.vtitle ORDER BY " . $orderby . "";
        $database->setQuery($q);
        $items = $database->loadObjectList();

        $xmap->changeLevel(1);

        foreach ($items as $vehicle)
            xmap_com_vehiclemanager::printNode($xmap, $menu, $Itemid, $vehicle->id,
                    $vehicle->vtitle, $vehicle->catid, $vehicle->id, true);

        $xmap->changeLevel(-1);
    }


    public static function ownersListHandler(&$xmap, &$menu, $params){
        // The [owners list] menu type handler
        //xmap_com_vehiclemanager::header();
        $Itemid = $menu->id;
        if($params['orderby'] != 'title')
        {
          $orderby =$params['orderby'];
        }
        else
        {
          $orderby='vtitle';
        }
//        $database = &JFactory::getDBO();
        $database = JFactory::getDBO();
        $s = vmLittleThings::getWhereUsergroupsCondition();
        $q1 = "SELECT u.name, u.email, u.id, COUNT(vm.owneremail) AS vehicles
            \n FROM #__vehiclemanager_vehicles AS vm
            \n LEFT JOIN #__vehiclemanager_categories AS vc ON vc.iditem=vm.id
            \n LEFT JOIN #__vehiclemanager_main_categories AS c ON c.id=vc.idcat
            \n LEFT JOIN #__users AS u ON vm.owneremail=u.email
            \n WHERE (".$s.") AND vm.published=1 AND vm.approved=1 AND c.published=1
                AND vm.owneremail!=''
            \n GROUP BY u.name
            \n ORDER BY u.name ";
        $database->setQuery($q1);
        $items = $database->loadObjectList();

        $xmap->changeLevel(1);

        foreach($items as $owner){
            if($owner->name == '') $owner->name = "anonymous" ;
            xmap_com_vehiclemanager::printNode($xmap, $menu, $Itemid, $owner->id, $owner->name,
                    0, 0, false, $owner->name);
            if ($params['show_Vehicle'] == 'true'){
            $s = vmLittleThings::getWhereUsergroupsCondition();
            $q = "SELECT v.*, c.id AS catid FROM `#__vehiclemanager_vehicles` AS v
                  LEFT JOIN #__vehiclemanager_categories AS vc ON vc.iditem=v.id
                  LEFT JOIN #__vehiclemanager_main_categories AS c ON c.id=vc.idcat
                  WHERE v.approved = 1 AND c.published = 1 AND v.published = 1 AND (".$s.") A"
                    . "ND v.owner_id='".$owner->id."'
                  GROUP BY v.id ORDER BY " . $orderby . "";
            $database->setQuery($q);
            $vehicles = $database->loadObjectList();

            $xmap->changeLevel(1);
            //var_dump($vehicles);

            foreach ($vehicles as $vehicle)
                xmap_com_vehiclemanager::printNode($xmap, $menu, $Itemid, $vehicle->id,
                        $vehicle->vtitle, $vehicle->catid, $vehicle->id, true);

            $xmap->changeLevel(-1);
        }
        }

        $xmap->changeLevel(-1);
    }





    public static function printNode(&$xmap, &$menu, $Itemid, $node_uid, $node_name, $catid = 0,
            $vehicleid = 0, $is_vehicle = false, $name = false){
        // [params for Vehicle]: $xmap obj, the `parent` Obj, Itemid, Vehicleid, Vehicle->title,
        // catid, vehicleID, vehicle/category flag = 'true', user=false
        // [params for Category]: $xmap, $parent, Itemid, catid, category title,
        // catid, 0, false, user=false
        // [params for User]: $xmap, $parent, Itemid, userid, username, 0, 0, false, username
        $node = new stdclass;
        $node->id = $Itemid;
        $node->uid = $node_uid;
        $node->name = $node_name;
        $node->parent = 1;
        $node->browsNav = 1;
        $node->ordering = 2;
        $node->priority=$menu->priority;
        $node->chansefreq=$menu->changefreq;
        $node->changefreq=$menu->changefreq;
        $node->modified= date("Y-m-d h:i:s");
        $node->type = 'component';
        $node->menutype = 'mainmenu';
        if ($is_vehicle) $node->link = 'index.php?option=com_vehiclemanager&amp;'
                . 'task=view_vehicle&amp;catid='.$catid.'&amp;Itemid='.$Itemid.'&amp;id='.$vehicleid;
            elseif ($catid > 0) $node->link = 'index.php?option=com_vehiclemanager&amp;'
                    . 'task=showCategory&amp;catid='.$catid.'&amp;Itemid='.$Itemid;
                elseif (isset($name) AND $name != '') $node->link = 'index.php?option='
                        . 'com_vehiclemanager&amp;task=view_user_vehicles&amp;'
                        . 'Itemid='.$Itemid.'&amp;name='.$name;
        $xmap->printNode($node);
    }
}
