<?php
	require_once('../../../../wp-load.php');

	$category 	= $_POST['category'];
	$orderby 	= $_POST['orderby'];
	$order 		= $_POST['order'];
    $per_page   = $_POST['perpage'];
	$num_items 	= $_POST['numitems'];
	$offset 	= $_POST['offset'];
	$tax_query 	= '';

    if($category && $category != '*') {
        $tax_query = array(
            array(
                'taxonomy' => 'portfolio_category',
                'field' => 'name',
                'terms' => $category
            )
       );
    }

    $args = array(
        'post_type' => 'portfolio',
        'orderby' 	=> $orderby,
        'order' 	=> $order,
        'showposts' => $num_items,
        'tax_query' => $tax_query,
        'offset' 	=> $offset
    );
    $portfolio_posts = new WP_Query( $args );
    
    $portfolio_data = "";

    while($portfolio_posts->have_posts()) : 
        $portfolio_posts->the_post(); 
        $portfolio_cat = ""; 
        if (get_the_terms(get_the_ID(), 'portfolio_category')) {
            $first_item = false;
            foreach (get_the_terms(get_the_ID(), 'portfolio_category') as $cat) {
                if($first_item) {
                    $portfolio_cat .= " ";
                }
                $first_item = true;
                $portfolio_cat .= strtolower(str_replace(" ", "-", $cat->name));
            }
        }
        $image_class = "portfolio-thumb";
        if(has_post_thumbnail(get_the_ID())) {
                $image = get_the_post_thumbnail(get_the_ID(), $image_class);
        }
        elseif(get_post_meta(get_the_ID(), $key ='gallery_images', $single = true )) { 
            $exploded_images = explode(',',get_post_meta(get_the_ID(), $key ='gallery_images', $single = true ));
            $image_url = wp_get_attachment_image_src($exploded_images[0], $image_class); 
            $image = "<img src='".$image_url[0]."' />";
        }
        $portfolio_data .= "<article class='col-md-4 col-sm-6 $portfolio_cat page-" . (($offset/$per_page) + 1) . "'>";
        $portfolio_data .= "<a href='".get_permalink()."'>".$image;
        $portfolio_data .= "<div class='hover'><i class='fa fa-cutlery'></i>";
        $portfolio_data .= "<h2>".get_the_title()."</h2>";
        $portfolio_data .= "</div></a>";
        $portfolio_data .= "</article>";
    endwhile;

	echo $portfolio_data;
?>