<?php namespace App\Http\Controllers;

		use Session;
		use Request;
		use DB;
		use CRUDBooster;

		class ApiKeranjangController extends \crocodicstudio\crudbooster\controllers\ApiController {

		    function __construct() {    
				$this->table       = "keranjang";        
				$this->permalink   = "keranjang";    
				$this->method_type = "get";    
		    }
		

		    public function hook_before(&$postdata) {
		        //This method will be execute before run the main process

		    }

		    public function hook_query(&$query) {
		        //This method is to customize the sql query
                $query->where('keranjang.status','new');
		    }

		    public function hook_after($postdata,&$result) {
		        if(sizeof($result['data'])>0){
		            $numOfItems = 0;
		            $total = 0;
		            $produk = array();
		            $jaraks = array();
		            foreach($result['data'] as $data){
		                $numOfItems +=  $data->qty;
		                
		                $produk = DB::table('produk')->where('id',$data->produk_id)->first();
		                $total += $data->qty * $produk->harga;
		                $photos = DB::table('photo_produk')->where('produk_id',$produk->id)->get();
    		            $satuan = DB::table('berat')->where('id',$produk->satuan_berat)->first();
    		           
    		            if($postdata['user_lat']){
    		                $lokasi = DB::table('lokasi')->where('id',$produk->lokasi_id)
    		                ->select('lokasi.*',DB::raw('111.111 *
                                 DEGREES(ACOS(LEAST(1.0, COS(RADIANS(lat))
                                 * COS(RADIANS('.$postdata['user_lat'].'))
                                 * COS(RADIANS(lon - '.$postdata['user_lon'].'))
                                 + SIN(RADIANS(lat))
                                 * SIN(RADIANS('.$postdata['user_lat'].'))))) AS jarak_km'))
                            ->first();
                            
                            $usaha = DB::table('umkm_usaha')->where('id',$produk->umkm_usaha_id)
        		                ->select('umkm_usaha.*',DB::raw('111.111 *
                                     DEGREES(ACOS(LEAST(1.0, COS(RADIANS(lat))
                                     * COS(RADIANS('.$postdata['user_lat'].'))
                                     * COS(RADIANS(lon - '.$postdata['user_lon'].'))
                                     + SIN(RADIANS(lat))
                                     * SIN(RADIANS('.$postdata['user_lat'].'))))) AS jarak_km'))
                                ->first();
    		            }else{
    		                $lokasi = DB::table('lokasi')->where('id',$produk->lokasi_id)->first();
    		                $usaha = DB::table('umkm_usaha')->where('id',$produk->umkm_usaha_id)->first();
    		            }
    		         
    		            if($photos){
    		                $photonya = array();
    		                foreach($photos as $photo){
    		                    array_push($photonya,CRUDBooster::publicPath($photo->file));
    		                }
    		                $produk->photo = $photonya;
    		            }
    		            
    		            //$rating = DB::table('rating')->whereRaw()->first();
    		            
    		            $produk->rating = $this->rand_float(5,45);
    		            $myfav = DB::table('reaksi')
    		                    ->where('nama_table','produk')
    		                    ->where('key_id',$produk->id)
    		                    ->where('master_reaksi_id','1')
    		                    ->first();
    		            if($myfav){
    		                $produk->isFavorite = $myfav->id;
    		            }else{
    		                $produk->isFavorite = 0;
    		            }
    		            $produk->isPopular = rand(0,1) == 1;
    		            $produk->colors = array('0xFFF6625E', '0xFF836DB8', '0xFFDECB9C');
    		            $produk->satuan_berat = $satuan->simbol;
    		            $produk->etalase_id = 0;
    		            $produk->status_produk_id = 0;
    		            
    		            if($lokasi){
    		                $produk->lokasi = $lokasi->nama;
    		                $produk->usaha = $usaha->nama_usaha;
    		                $produk->jarak = round($lokasi->jarak_km,1);
    		            }else{
    		                $produk->lokasi = "0";
    		                $produk->usaha = $usaha->nama_usaha;
    		                $produk->jarak = round($usaha->jarak_km,1);
        		        }
        		        
        		        array_push($jaraks,$produk->jarak);
    		            
		                $data->produk = $produk;
		                $data->subtotal = $produk->harga * $data->qty;
		            }
		            $result['numOfItems'] = $numOfItems;
		            $result['total'] = $total;
                    if((count(array_unique($jaraks)) === 1)){
                        $result['error'] = "none";
                    }else{
                        $result['error'] = "Pesanan tidak berada dalam lokasi yang sama !" ;
                    }
                    
                    $time = strtotime($postdata['waktu']);

                    $tanggal = date('Y-m-d',$time);
                    $waktu = date("H:i:s",$time);
                    
		            $tarif = DB::table('tarif_kurir')
    		            ->whereDate('tanggal', '=', $tanggal)
    		            ->where('mulai_jam','<=', $waktu)
    		            ->where('akhir_jam','>=', $waktu)
    		            ->first();
    		            
    		        if(!$tarif){
    		           $tarif = DB::table('tarif_kurir')
    		            ->where('default_tarif', 1)
    		            ->where('mulai_jam','<=', $waktu)
    		            ->where('akhir_jam','>=', $waktu)
    		            ->first();
    		        }
    		            
    		        $result['tarif_per_km'] = (int)$tarif->tarif_per_km;
    		        $result['avg_jarak'] = round(array_sum($jaraks)/count($jaraks),1);
    		        $result['biaya_kurir'] = round((array_sum($jaraks)/count($jaraks))*$tarif->tarif_per_km,0);
		        }else{
		            $result['api_status'] = 0;
		            $result['api_message'] = "Keranjang anda kosong";
		            $result['api_authorization'] = "";
		             $result['numOfItems'] = 0;
		             $result['total'] = 0;
		             $result['tarif_per_km'] = 0;
    		        $result['avg_jarak'] = 0;
    		        $result['biaya_kurir'] = 0;
    		        $result['error'] = "none";
		        }

		    }
		    
		    function rand_float($st_num=0,$end_num=1,$mul=10)
            {
                if ($st_num>$end_num) return false;
                $rand =  mt_rand ($st_num, $end_num);
                return round($rand,2);
            }

		}