<?php

namespace App\Http\Controllers;

use Auth;
use App\Admin;
use App\AttributeTranslation;
use App\Category;
use App\Product;
use App\CategoryGroup;
use App\Brand;
use App\Page;
use App\Position;
use App\Route;
use DB;
use App\Metatag;
use App\Slide;
use App\Carousel;
use App\Ad;
use App\Search;
use App\Config;
use App\Department;
use Illuminate\Support\Facades\Notification;
use App\Notifications\NewIntOrder;
use Illuminate\Http\Request;
use App\Attribute;
use App\Cart;
use App\Order;
use App\OrderItem;
use App\Lib\Prices;
use Session;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\RouteDeletedRedirected as Redirected;

class FrontendController extends Controller
{
    public function __construct()
    {
    }

    public function router(Request $request, $slug){

        try {
        $data = Route::select('object','object_id')->where('slug',  $slug)->where('lang',  app()->getLocale())->firstOrFail();

        } catch (ModelNotFoundException $ex) {

            $reddata = Redirected::where('slug',  $slug)->where('lang',  app()->getLocale())->first();

            if(is_null($reddata)){
                return response()->view('errors.404',[],404);
            } else if ($reddata->rd_type  == 'd'){
                return redirect(locRoute('index'), 410);
            } else if ($reddata->rd_type  == 'r'){
                $data = Route::select('slug')->where('object',  $reddata->object)->where('object_id',  $reddata->object_id)->where('lang',  app()->getLocale())->firstOrFail();
                $redirect_url  = tr_url($data->slug);
                return redirect($redirect_url, 301);
            } else {
                return response()->view('errors.404',[],404);
            }
        }


        if(count($data)){
            $object = $data->object;
            $id     = $data->object_id;
            switch ($object) {
                case 'Category':
                    return $this->category($request, $id);
                    break;
                case 'Product':
                    return $this->product($request, $id);
                    break;
                case 'Brand':
                    return $this->brand($request, $id);
                    break;
                case 'CategoryGroup':
                    return $this->categoryGroup($request, $id);
                    break;
                case 'Position':
                    return $this->position($request, $id);
                    break;
                case 'Page':
                    return $this->page($request, $id);
                    break;
                default:
                    return response()->view('errors.404',[],404);
            } // switch

        } // if data




    } // router


    public function index(){

        $data = [];

        $data['metatags']  = Metatag::where('mt_page', '=', 'i')->select('mt_title as title','mt_desc as desc','mt_keyw as keyw', 'mt_h1 as h1')->first();
        $data['slides']    = Slide::with('ctranslation')->get();
        $data['carousels'] = Carousel::where('car_active', 1)->with('ctranslation')->get();
        $data['ads']       = Ad::getHomePageSortedAds();


        return view('frontend.index',$data);

    }


    private function product($request, $id){

        $product = Product::with(['brand','category','description'])->findOrFail($id);



        $data = [];

        $data['product']         = $product;
        $data['similarproducts'] = $product->getSimilarProducts();

        return view('frontend.product',$data);

    }// product


    private function category($request, $id){

        $category = Category::findOrFail($id);

        $data = [];
        $data['category']    = $category;
        $data['products']    = $category->getCategoryProducts();
        $data['brands']      = $category->getCategoryBrandsData();
        $data['pricesdata']  = $category->getCategoryMinMaxPrice();
        $data['filtersdata'] = $category->getCategoryAttributesData();
        $data['sideads']     = Ad::with('ctranslation')->where('ad_pos_id', '=', 4)->orderBy('ad_order', 'asc')->get();

        //echo '<pre>'.print_r($data['brands'],true).'</pre>'.'<pre>'.print_r($data['pricesdata'],true).'</pre>'.
        //echo '<pre>'.print_r($data['sideads'],true).'</pre>'; exit;

        return view('frontend.category',$data);
    }


    private function brand($request, $id){

        $brand = Brand::findOrFail($id);

        $data = [];
        $data['brand']    = $brand;
        $data['products'] = $brand->getBrandProducts();

        $data['brands']      = [];
        $data['pricesdata']  = [];
        $data['filtersdata'] = [];
        $data['sideads']     = Ad::where('ad_pos_id', '=', 4)->orderBy('ad_order', 'asc')->get();

        return view('frontend.brand',$data);
    }


    private function position($request, $id){

        $position = Position::findOrFail($id);

        $data = [];
        $data['position']    = $position;
        $data['products']    = $position->getPositionProducts();
        $data['brands']      = NULL;
        $data['pricesdata']  = NULL;
        $data['filtersdata'] = NULL;

        return view('frontend.position',$data);
    }


    private function page($request, $id){

        $page = Page::findOrFail($id);

        $data = [];
        $data['page']    = $page;

        return view('frontend.page',$data);


    }





    public function compare(){

        $data = [];

        //echo getCurentExeTime().' ';

        $data['products']  = Product::getCompareProductsData();

        //echo getCurentExeTime();

        return view('frontend.compare',$data);

    }


    public function search(){

        $data = [];
        $data['products']    = Search::getResults();
        $data['sideads']     = Ad::where('ad_pos_id', '=', 4)->orderBy('ad_order', 'asc')->get();

        return view('frontend.search',$data);
    }


    private function categoryGroup($request, $id){
        echo 'f1: '.getCurentExeTime().'<br/>'."\n";
        $group = CategoryGroup::findOrFail($id);
        echo 'f2: '.getCurentExeTime().'<br/>'."\n";
        print_r($request->all());
        print_r($group);
    }


    public function categoryBrand(Request $request, $cslug, $bslug){

        $cdata = Route::select('object','object_id')->where('slug',  $cslug)->firstOrFail();
        $catid = $cdata->object_id;
        $category = Category::findOrFail($catid);

        $bdata   = Route::select('object','object_id')->where('slug',  $bslug)->firstOrFail();
        $brandid = $bdata->object_id;
        $brand   = Brand::findOrFail($brandid);

        $data = [];
        $data['category']  = $category;
        $data['brand']     = $brand;
        $data['products']  = $category->getCategoryBrandProducts($brandid);

        $data['brands']      = [];
        $data['pricesdata']  = [];
        $data['filtersdata'] = [];
        $data['sideads']     = Ad::where('ad_pos_id', '=', 4)->orderBy('ad_order', 'asc')->get();

        return view('frontend.categorybrand',$data);
    }





    public function cart(Request $request){

        //echo $request->session()->getId(); dd( $request->session()->all());

        if(!empty($_POST)) {

            //echo print_r($_POST,true);

            $act = ($request->has('act')) ? trim($request->act) : '';
            $ind = ($request->has('ind') && is_numeric(trim($request->ind)) ) ? trim($request->ind) : -1;
            $qnt = ($request->has('qnt') && is_numeric(trim($request->qnt)) ) ? trim($request->qnt) : 1;



            if($act == 'add' && $ind != -1){

                $result = Cart::addToCart($ind,$qnt);

                if($request->has('ret') && $request->ret == 1){
                    echo Cart::getNumOfItemsInCart();
                    exit;
                }

                //return redirect(\route('cart'));

                /*if($result > 0){ $_SESSION['cartactmsg'] = '<div class="addsucess">Proizvod uspesno dodat u korpu</div>';
                } else {         $_SESSION['cartactmsg'] = '<div class="adderror">Doslo je do greske - proizvod nije dodat u korpu</div>';
                }*/
            }


            /*header("Location: ".$this->cartUrl);
            exit;*/

        };

        //echo 'cart' . print_r(Cart::getCartContent(),true);

        $data = [];

        $data['products']     = Cart::getCartContent();

        return view('frontend.cart',$data);

    }

    public function removefromcart(Request $request, $ind)
    {
        Cart::removeFromCart($ind);
        $url = locRoute('cart');
        return redirect($url);
    }

    public function checkout(){
        if(Auth::check())
        {
            $data = [];

            $data['products']     = Cart::getCartContent();

            return view('frontend.checkout',$data);

        } else {
            $url = locRoute('login');
            return redirect($url)->withInput()->with('errmessage', 'Molimo ulogujte se kako bi nastavili');
        }

    }

    public function makeorder(Request $request){

        $cartdata = Cart::getCartContent();

        if(count($cartdata)){

            try{
                DB::beginTransaction();

                $user = auth('web')->user();

                $order = new Order();

                $order->user_id     = $user->id;
                $order->ord_lname   = $user->lname;
                $order->ord_fname   = $user->name;
                $order->ord_adress  = $user->address;
                $order->ord_phone   = $user->phone;
                $order->ord_email   = $user->email;
                $order->com_id      = $user->com_id;
                $order->ord_status  = 0;
                $order->ord_total  = 0;


                $order->save();

                $prices = new Prices();

                $total = 0;

                foreach($cartdata as $p){



                    $prodid   = $p->prod_id;
                    $fullname = strtoupper($p->brand_name).' '.ucfirst($p->prod_name);
                    $qty      = $p->sc_qty;

                    $price = $prices->getPrice($p, true); //$p->sc_price;
                    $vrate    = $p->cat_vat;
                    $nvprice  = $price/((100+$vrate)/100);
                    $vat      = $price-$nvprice;

                    $subtotal = $price*$qty;
                    $total    = $total+$subtotal;


                    $item  = new OrderItem();

                    $item->prod_id          = $prodid;
                    $item->ord_item_name    = $fullname;
                    $item->ord_item_qnty    = $qty;
                    $item->ord_item_price   = $price;
                    $item->ord_item_nvprice	= $nvprice;
                    $item->ord_item_vrate	= $vrate;
                    $item->ord_item_vat     = $vat;

                    $order->items()->save($item);

                }

                $order->ord_total  = $total;
                $order->save();

                DB::commit();

                Cart::deleteCartContent();

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




            $data = [];

            $data['order'] = $order->with('items');

            return view('frontend.thankyou',$data);


        } else {
            $url = locRoute('cart');
            return redirect($url);
        }

    }

    public function currency(Request $request, $cur){

        $currarr = array('rsd','usd');

        $cur = (isset($cur) && in_array($cur,$currarr)) ? trim($cur) : 'rsd';

        Session::put('currency', strtoupper($cur));

        return back();

    }


    public function time(){

        //echo 'custom'; exit;

        /*//$routes = \Artisan::call('route:list', ['--path' => 'api']);
        $routes = app()->routes->getRoutes();
        //dd($routes);
        sort($routes);
        $final = [];
        foreach ($routes as $route){
            //if(in_array('GET', $route->methods))echo $route->uri.' '.print_r($route->methods,true).'<br>';
            //echo $route->uri.'<br>';
            if (
                strncmp($route->uri, 'sr', strlen('sr')) !== 0 && 
                strncmp($route->uri, 'ajax-', strlen('ajax-')) !== 0 &&
                strncmp($route->uri, 'art-', strlen('art-')) !== 0 &&
                strncmp($route->uri, 'cartremove-', strlen('cartremove-')) !== 0 &&
                strncmp($route->uri, 'currency-', strlen('currency-')) !== 0 &&
                strncmp($route->uri, 'panel/', strlen('panel/')) !== 0 &&
                strncmp($route->uri, 'password/', strlen('password/')) !== 0 &&
                strncmp($route->uri, 'user-', strlen('user-')) !== 0 &&
                strncmp($route->uri, 'users/', strlen('users/')) !== 0
                &&
                $route->uri != '/' &&
                $route->uri != 'cart' &&
                $route->uri != 'checkout' &&
                $route->uri != 'compare' &&
                $route->uri != 'contact' &&
                $route->uri != 'login' &&
                $route->uri != 'logout' &&
                $route->uri != 'makeorder' &&
                $route->uri != 'panel' &&
                $route->uri != 'register' &&
                $route->uri != 'search' &&
                $route->uri != 'time' &&
                $route->uri != 'user'
            ){
                //$final[] = $route->uri;
                array_push($final, $route->uri);
            }

        }
        //dd(array_unique($final));
        $forbidenRouteExact = ['/','cart','checkout','compare','contact','login','logout','makeorder','panel','register','search','time','user'];
        $forbidenRouteStart = ['ajax-','art-','cartremove-','currency-','panel/','password/','user-','users/'];*/
        /*echo getCurentExeTime();
        $itStaff = Department::find(1)->staff;
        $cadmin = Admin::find(1);

        if(Count($itStaff)){
            foreach($itStaff as $admin){
                Notification::send($admin, new NewIntOrder($cadmin));
            }
        }*/

        //print_r($data);
        exit;
    }

    /*public function dep(){

    }*/



}
