<?php

namespace App\Http\Controllers\Frontend;

use App\Product;
use App\Cart;
use DB;
use Illuminate\Support\Facades\Input;
use Session;
use View;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AjaxController extends Controller
{
    public function index(Request $request, $act){

        if(method_exists($this, $act)){
            return $this->{trim($act)}($request);
        } else {
            echo 'Method '.$act.' does not exist';
        }
    }


    public function addforcompare($request){


        if( $request->has('id') && is_numeric($request->id) ){


            $maxCompareProducts = 3;

            $numOfCompareProducts = (Session::has('compareproducts') && is_array(session('compareproducts')))
                ? count(session('compareproducts')) : 0;

            $numOfCompareProducts = intval($numOfCompareProducts);


            $id = trim($_POST['id']);

            if(Session::has('compareproducts') && in_array($id, session('compareproducts') )){

                $result = 'false,show,Proizvod je vec u listi za poredjenje';

            } else if ($numOfCompareProducts >= $maxCompareProducts){

                $result = 'false,alert,Vec sta dodali maksimalni broj od '.$maxCompareProducts.' proizvoda za poredjenje';

            }  else {

                session()->push('compareproducts', $id);

                $result = 'true,show,Proizvod uspesno dodat na listu za poredjenje';
            }


        } else { // ako nisu poslati i kod

            $result = 'false,alert,Doslo je do greske';
        }

        echo $result;

    } // addforcompare


    public function removefromcompare($request){


        if( $request->has('id') && is_numeric($request->id) ){

            $id = intval(trim($_POST['id']));


            $key=array_search($id,session('compareproducts'));

            if($key!==false){
                session()->forget('compareproducts.'.$key);
                $result = '1,';
            } else {
                $result = '0,Doslo je do greske';
            }




        } else { // ako nisu poslati i kod

            $result = '0,Doslo je do greske';
        }

        echo $result;

    } // addforcompare


    public function removeallfromcompare($request){

        if( $request->has('action') && trim($request->action) == 'removeall' ){

                session()->forget('compareproducts');

                $result = 'true,';

        } else {

            $result = 'false,Doslo je do reske';

        }

        echo $result;

    } //  removeallfromcompare


    private function productsfilter($request){

        //echo getCurentExeTime();
        $lang = (session()->has('clang')) ? session('clang') : app()->getLocale();


        $html = '';

        $sqlq = array();

        if(!empty(Input::get())):


            $sql = 'SELECT c.cat_id, c.cat_vat, ct.cat_name, ct.cat_title_sufix, b.brand_id, b.brand_name, p.prod_id,  p.prod_name, p.`prod_ifdisc`,  
                    ct.`cat_sale_sticker`, p.prod_simg, p.prod_bimg, IF(cf.`filter_desc` = "a", p.prod_atdes,`prod_sdesc`) as sdesc, p.prod_price, p.pos_id , pt.pos_name, p.`prod_feat`, 
                    COALESCE( p.`prod_sticker` , pt.pos_sticker , NULL ) AS `sticker`,  
                    COALESCE( c.`cat_reg_disc` , cf.`reg_disc` , 0 ) AS `regdisc`, 
                    COALESCE( c.`cat_sale_disc` , cf.`sale_discount` , 0 ) AS `saledisc`, 
                    p.`prod_oldprice`, p.`prod_ifsale`, p.`prod_sticker`, r.`slug`, p.`prod_if_price`    
			        FROM `config` cf, `products`  p '
                    .((Input::has('prod')) ? 'FORCE INDEX (`catBrandActive` ) ' : 'FORCE INDEX (`catActive`) ' )
                    .'INNER JOIN brands  b USE INDEX (`PRIMARY`) ON p.brand_id = b.brand_id 
			        INNER JOIN categories  c USE INDEX (`PRIMARY`) ON p.cat_id = c.cat_id
			        INNER JOIN `category_translations` ct ON c.`cat_id` = ct.`cat_id` AND ct.`ct_lang` = "'.$lang.'"  
			        
			        LEFT JOIN `position_translations` pt ON p.`pos_id` = pt.`pos_id` AND pt.`lang` = "'.$lang.'"  
			        INNER JOIN `routes` r ON p.`prod_id` = r.`object_id` AND r.`object` = "Product"  AND r.`lang` = "'.$lang.'" 
			        WHERE  p.prod_status  = 1   ';

                    //LEFT JOIN `positions` pp USE INDEX (`PRIMARY`) ON p.pos_id = pp.pos_id


            $n = 0;

            foreach(Input::get() as $postkey => $postval ):
                if(!empty(Input::get($postkey)) && count(Input::get($postkey)) > 0):
                    if (preg_match("/^f_/", $postkey, $matches)):

                        $attrrpid =  preg_replace("/[^0-9]/", '', $postkey);  // provera da li se dobijeni broj nalazi u listi atributa
                        $atrvalidsp = implode(', ', (array_filter($postval, "is_numeric")));  // prethodno ocistiti vrednosti na samo numericke array walk ili....
                        $sqlq[] = '(pav.atr_id = '.$attrrpid.' AND pav.atr_val_id IN ('.$atrvalidsp.') )' ;
                        $n++;

                    endif;
                endif;
            endforeach;

            if(count($sqlq)){

                $sqlasq = 'SELECT pav.prod_id
			               FROM product_attribute_values pav FORCE INDEX (`atr_id_2`)
			               WHERE ';
                $sqlasq .= implode(' OR ' , $sqlq );
                $sqlasq .= ' GROUP BY CONCAT(pav.prod_id, pav.`atr_id`) ';


                $sqla = 'SELECT `prod_id`
			             FROM ('.$sqlasq.') sq
			             GROUP BY `prod_id`
			             HAVING COUNT(*) = '.$n.'
			             ORDER BY prod_id';



                $prodids   = collect(DB::select($sqla))->pluck('prod_id')->toArray();
                $csprodids = (is_array($prodids) && count($prodids)) ? implode(',' , $prodids ) : -1;

                $sql .=  ' AND p.prod_id IN ('.$csprodids.') ';


            }

            $cid   = (is_numeric(trim(Input::get('cid')))) ? trim(Input::get('cid')) : -1;
            $price = (is_numeric(trim(Input::get('price')))) ? trim(Input::get('price')) : 1000000000000000000000;


            $sql .= ' AND c.cat_id = '.$cid.'  ';

            $sql .=  ($price) ? '  AND p.prod_price <= '.$price.' ' : '';

            if(Input::has('prod') && !empty(Input::get('prod'))){
                $bids = implode(', ' ,(array_filter(Input::get('prod'), 'is_numeric')));
                $sql .= 'AND p.brand_id IN ('.$bids.')';
            } else {

                $sql .= ' AND p.brand_id  > 0 ';

            }

            $sql .= ' ORDER BY p.prod_price  ';







            if(
                !empty($sqlq) ||
                ( Input::has('prod') && !empty(Input::get('prod'))  ) ||
                ( Input::has('price') && trim(Input::get('price')) != '')
            ){
                $filterarray = collect(DB::select($sql));
            }

        endif;



        if(isset($filterarray)){
            if(count($filterarray) > 0){

                $view = View::make('frontend.components.products_list', ['products' => $filterarray, 'type' => 'r', 'num' => 4]);
                $html = $view->render();



            } else {
                $html = '<div id="filtersinfo">
    Nisu pronadjeni proizvodi koji odgovaraju odabranim kriterijumima<br />
    pokusajte sa drugim izborom ponovo...
    <br /><br />
    <button class="btn btn-default btn-xs resetfilters" type="button">Poništi izabrane opcije</button>
</div>';

            }

        }  else {

            $html = 'reset';

        }

        echo $html;//.'<div class="col-xs-12 text-center">'.getCurentExeTime().'</div>';

    } // productsfilter


    public function savecart($request){


        try {

            //obrada proizvoda u korpi
            if($request->has('pid') && !empty($request->pid) ){


                // sredjivanje podataka

                $pairs = array();

                foreach($request->pid as $i => $val){

                    $id = trim($val);
                    $qnty = trim($request->pqty[$i]);

                    if(is_numeric($id) && is_numeric($qnty)){

                        $pairs[$id] = $qnty;

                    }	// if numeric

                } // foreach

                $result = Cart::updateCart($pairs);
                return $result;

            } else {

                Cart::deleteCartContent();
                return 0;
            }



        } catch (\Illuminate\Database\QueryException $e) {
            // something went wrong with the transaction, rollback
            echo handle_error($e);
        } catch (\Exception $e) {
            // something went wrong elsewhere
            echo handle_error($e);
        }


    } // savecart



    // Method template
    private function method($request){

    }
}
