<?php

class AdcVendorsTiles extends AdcWidget{

	static function register_shortcode( $atts ){
		$w = new self();
 		return $w->widget(array(),array());
	}

    public function __construct() {
        parent::__construct("text_widget", "ADC Vendors Tiles",
            array("description" => ""));
    }	

	public function widget($args, $instance) {
 		$settings = $this->getSettings();
 		if (!$settings) return $this->error();
 		$view = new View("vendor_tiles");
 		$categories = $this->api->categories();
 		$view->setVar("categories", $categories);
 		$view->setVar("settings", $settings);
 		$adc_q = get_query_var("q", "");
 		if (!$adc_q)
 			$adc_q = isset($_GET['adc-q'])? $_GET['adc-q'] : "";
 		$adc_category = get_query_var("category", "");
 		if (!$adc_category)
 			$adc_category = isset($_GET['adc-category'])? $_GET['adc-category'] : "";
 		$adc_vendor = get_query_var("vendor", "");
 		if (!$adc_vendor)
 			$adc_vendor = isset($_GET['adc-vendor'])? $_GET['adc-vendor'] : "";
 		$view->setVar("search", array( "q" => $adc_q, "category" => intVal($adc_category), "vendor" => $adc_vendor));
 		$result = $this->api->search($adc_q, intVal($adc_category), $adc_vendor);
 		if (!$result){
    		global $wp_query;
    		$wp_query->set_404();
    		status_header(404);	
    		include( get_query_template( '404' ) );		
    		exit; 			
 		}
 		$view->setVar("result", $result, false);
 		$view->setVar("ajax_url", admin_url('admin-ajax.php') );
 		$view->setVar("links", array(
			array("title" => "Become a Partner", "url" => "#"),
			array("title" => "FAQ", "url" => "#"),
			array("title" => "Submit an Idea", "url" => "#"),
 		));
	    return $view->fetch();
	}    

	public function search($q, $category_id, $start, $count)
	{
 		$settings = $this->getSettings();
		$result = $this->api->search($q, $category_id);
		if ($result){
			header("X-Total-Results: ".$result['total']);
			for($i=$start; $i < $result['total'] && ($count == 0 || $i < $start+$count); $i++){
				$view = new View("vendor_tile");
				$view->setVar("settings", $settings);
				$view->setVar("product",$result['rows'][$i], false);
				echo $view->fetch();
			}
			
		}
	}
}