<?php namespace App\Http\Controllers;
        header("Access-Control-Allow-Origin: *");

		use Session;
		use Request;
		use DB;
		use CRUDBooster;
		use Carbon\Carbon;
		use DateTime;
        use DatePeriod;
        use DateInterval;
		
		class ApiAmbilIklanController extends \crocodicstudio\crudbooster\controllers\ApiController {

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

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

		    }

		    public function hook_query(&$query) {
		        $query->where('expired',0)
		            //->join('cctv','iklan.target_stream','cctv.id')
		            ->where(function ($q) {
                      $q->where('mulai_tayang', '<=',Carbon::now('Asia/Makassar')->format('Y-m-d H:i:s'));
                      $q->where('akhir_tayang', '>=',Carbon::now('Asia/Makassar')->format('Y-m-d H:i:s'));
                    })
		            ->first();
		    }

		    public function hook_after($postdata,&$result) {
		        //This method will be execute after run the main process
		        if($result['api_status']==1){
    		        $mulai = $result['mulai_tayang'];
    		        $setiap = $result['setiap'];
    		        
    		        $array = array();
    		        $interval = new DateInterval('PT'.$setiap.'M');
    		        
    		        $akhir =  new DateTime($result['akhir_tayang']);
    		        $akhir->add($interval);
    		        
    		        $period = new DatePeriod(new DateTime($mulai), $interval, $akhir);
    		        foreach($period as $date) { 
                        $array[] = $date->format('Y-m-d H:i:s'); 
                    }
                    $result['periode'] = $array;
                    
    		        $result['sekarang'] =  Carbon::now('Asia/Makassar')->format('Y-m-d H:i:s'); 
                   
                    
                    DB::table('iklan')->where('id',$result['id'])
                                ->update([
                                  'hit'=> DB::raw('hit+1')
                                ]);
		        }
		    }

		}