<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Session;
use DB;
use App\Lib\Prices;

class Cart extends Model
{
    protected $table = 'cart';

    protected $primaryKey = 'sc_id';


    public static function getNumOfItemsInCart(){

        $sessionid = (session()->has('carttoken')) ? session('carttoken') : -1;

        return Cart::where('sess_id', '=', $sessionid)->count();

        //return $items->count();
    }

    public static  function addToCart($ind, $qnt)
    {
        if (session()->has('carttoken')){
            $sessionid = session('carttoken');
        } else {
            $sessionid = session()->getId();
            Session::put('carttoken', $sessionid);
            Session::save();
        }

        $prices = new Prices();


        $ci = Cart::where('prod_id', '=', $ind)->where('sess_id', '=', $sessionid)->first();

        //dd($ci);
        if ($ci === null) {

            $product  = Product::find($ind);
            $p        = $product->getProdData(); //Da bi se dobili i ostali podaci potrebni za formiranje cene
            $price    = $prices->getPrice($p);


            $cart = new Cart();
            $cart->prod_id  = $ind;
            $cart->sc_qty   = $qnt;
            $cart->sc_price = $price;
            $cart->sess_id  = $sessionid;
            $cart->save();
            return 1;

        } else {
            $eq = $ci->sc_qty;
            $ci->sc_qty = $eq+$qnt;
            $ci->save();

            return 1;

        }

    }


    public static function removeFromCart($ind)
    {
        if (session()->has('carttoken')){
            $sessionid = session('carttoken');
        } else {
            $sessionid = -1;
        }


        $ci = Cart::where('prod_id', '=', $ind)->where('sess_id', '=', $sessionid)->first();

        if($ci){
            $ci->delete();
        }

    }


    public static function getCartContent(){

        try{

            $sessionid = (session()->has('carttoken')) ? session('carttoken') : -1;

            $selectsql = config('queries.defaultProductsSelectSql');
            $fromsql   = config('queries.defaultProductsFromSql');
            $sql     = $selectsql.',sc.sc_qty, sc.sc_price  '.$fromsql.' INNER JOIN cart sc ON p.prod_id = sc.prod_id  											  
                                  WHERE sc.sess_id = :sessid
                                  GROUP BY  sc.prod_id
                                  ORDER BY sc_id DESC';
            $pars = [':sessid' => $sessionid, ':lang' => app()->getLocale()];

            $data = collect(\DB::select($sql,$pars));



            return $data;

        } 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);
        }

    } // getCartContent


    public static function deleteCartContent(){

        try{

            $sessionid = (session()->has('carttoken')) ? session('carttoken') : -1;

            Cart::where('sess_id', '=', $sessionid)->delete();

        } 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);
        }

    } // deleteCartContent


    public static function updateCart($data){

        try{

            DB::beginTransaction();

            if (session()->has('carttoken')){
                $sessionid = session('carttoken');
            } else {
                $sessionid = -1;
            }

            $pids  = array();
            $pairs = array();

            foreach($data as $p => $q) {

                $p = trim($p);
                $q = trim($q);

                if( (is_numeric($p) && $p > 0) && (is_numeric($q) && $q > 0) ) {

                    $pids[]  = $p;
                    $pairs[$p] = $q;
                }


            }

            if(!empty($pairs)){

                // brisanje izbacenih

                $pidsCs = implode(',',$pids);

                DB::delete("DELETE FROM cart WHERE prod_id NOT IN ($pidsCs) AND sess_id = :sessid  LIMIT 1",
                            [':sessid' => $sessionid]
                           );

                // update postojecih

                $u = 0;

                foreach($pairs as $prodid => $qnty){

                    $ci = Cart::where('prod_id', '=', $prodid)->where('sess_id', '=', $sessionid)->first();

                    $ci->sc_qty = $qnty;

                    $ci->save();

                    ++$u;

                }

                $result = $u;



            } else {

                // delete all from cart
                Cart::where('sess_id', '=', $sessionid)->delete();
                $result = 0;

            }

            DB::commit();
            return $result;

        } 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);
        }


    } // updateCart
}
