unioil-loyalty-app/app/Http/Controllers/API/StationController.php

888 lines
30 KiB
PHP

<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Contracts\StationResourceInterface;
use App\Contracts\AdminActionLogsInterface;
use App\Contracts\LcardActionLogsInterface;
use App\Contracts\StationFuelPricesInterface;
use App\Contracts\StationFavoriteResourceInterface;
// use App\Http\Resources\StationResource;
use App\Libraries\ParameterHelper;
use App\Helpers\CurrentUserHelper;
use App\Helpers\StringHelper;
use App\Helpers\HttpStatusCode;
use App\Http\Resources\StationLocatorResource;
use App\Http\Resources\StationSearchResource;
use App\Libraries\StratuscastLibrary;
use App\Libraries\RNRPHLibrary;
use App\Libraries\StaticContents;
use App\Station;
use App\CodeCity;
class StationController extends Controller
{
const MODULE = 'STATION';
public $station;
protected $format;
protected $module;
protected $model;
protected $admin_logs;
protected $lcard_logs;
protected $station_favorite;
protected $station_fuel_prices;
public function __construct(StationResourceInterface $station,
HttpStatusCode $httpStatusCode,
AdminActionLogsInterface $admin_logs,
LcardActionLogsInterface $lcard_logs,
StationFavoriteResourceInterface $station_favorite,
StationFuelPricesInterface $station_fuel_prices)
{
$this->station = $station;
$this->format = $httpStatusCode;
$this->module = "station";
$this->model = "station";
$this->admin_logs = $admin_logs;
$this->lcard_logs = $lcard_logs;
$this->station_favorite = $station_favorite;
$this->station_fuel_prices = $station_fuel_prices;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
public function get_viewable()
{
$details = $this->station->getByField('is_viewable',1);
if(count($details) > 0)
{
$parsed = array();
foreach ($details as $key => $value)
{
if($value['is_active'] == 1)
{
$parsed[] = array(
'station_uuid' => $value['station_uuid'],
'code' => $value['code'],
'description' => $value['description'],
);
}
}
return $this->format->success('Success',$parsed);
}
else
{
return $this->format->noContent('No stations saved');
}
}
public function nearby(Request $request)
{
$this->lcard_logs->log(0,'STATIONLOCATOR','VIEW','Member views nearby stations');
$station = $this->station->nearby($request->longitude, $request->latitude);
if(count($station))
{
$additionals = $this->format->mobile_success("Success",[],false);
$data = StationLocatorResource::collection($station)->additional($additionals);
return $data->response()->setStatusCode(200);
}
else
{
return $this->format->mobile_success("Empty");
}
}
public function favorites()
{
$this->lcard_logs->log(0,'STATIONLOCATOR','VIEW','Member views favorite stations');
$station = $this->station->favorites();
if(count($station))
{
$additionals = $this->format->mobile_success("Success",[],false);
$data = StationLocatorResource::collection($station)->additional($additionals);
return $data->response()->setStatusCode(200);
}
else
{
return $this->format->mobile_success("Empty",[]);
}
}
public function search(Request $request)
{
if($request->has('keyword'))
{
$this->lcard_logs->log(0,'STATIONLOCATOR','SEARCH','Member searches for keyword '.$request->search);
$city = $this->station->search_by_keyword($request->keyword);
}
elseif ($request->has('province_uuid'))
{
$this->lcard_logs->log(0,'STATIONLOCATOR','SEARCH','Member searches station via province ');
$city = $this->station->search_by_province($request->province_uuid);
}
else
{
$this->lcard_logs->log(0,'STATIONLOCATOR','SEARCH','Member searches station');
$city = $this->station->search_all();
}
if($city)
{
return $this->format->mobile_success("Success",$city);
// $data = StationSearchResource::collection($city)->additional($additionals);
// return $data->response()->setStatusCode(200);
// return $additionals;
}
else
{
return $this->format->mobile_success("Empty");
}
}
public function by_province(Request $request)
{
$this->lcard_logs->log(0,'STATIONLOCATOR','SEARCH','Member searches station via province ');
$city = $this->station->search_by_province($request->province_uuid);
if($city)
{
$additionals = $this->format->mobile_success("Success",[],false);
$data = StationSearchResource::collection($city)->additional($additionals);
return $data->response()->setStatusCode(200);
}
else
{
return $this->format->mobile_success("Empty");
}
}
public function by_city($uuid)
{
$this->lcard_logs->log(0,'STATIONLOCATOR','SEARCH','Member searches station via city');
$station = $this->station->search_by_city($uuid);
if(count($station))
{
$additionals = $this->format->mobile_success("Success",[],false);
$data = StationLocatorResource::collection($station)->additional($additionals);
return $data->response()->setStatusCode(200);
}
else
{
return $this->format->mobile_success("Empty",[]);
}
}
public function fuel_prices($uuid)
{
$station = $this->station->search_by_uuid($uuid);
if($station)
{
$this->lcard_logs->log($station[0]['sid'],'STATIONLOCATOR','VIEW','Member views station details');
$stratuscast = new StratuscastLibrary();
$stratuscast->getFuelPriceBystation($station[0]['code']);
$db_fuel_prices = $this->station_fuel_prices->getByField([
'station_id' => $station[0]['sid'],
'is_active' => 1,
],
null,
[
'field' => 'updated_at',
'value' => 'asc'
]);
$db = [];
$latest_update = date('M d, Y');
if(count($db_fuel_prices))
{
foreach ($db_fuel_prices as $k => $v)
{
$db[$v['fuel_code']] = $v;
$latest_update = date('M d, Y',strtotime($v['updated_at']));
}
}
$fuel_type = StaticContents::fuelType_code();
$fuel_prices = [];
$except_where_in = []; // delete fuel prices that are not returned by stratuscast
if(count($stratuscast->response['data']))
{
foreach ($stratuscast->response['data'] as $key => $value) {
if($value->price != '')
{
if(isset($db[$value->fuel_code]))
{
if($db[$value->fuel_code]['price'] != $value->price)
$this->station_fuel_prices->update_price($db[$value->fuel_code]['fuel_price_uuid'],$value->price);
}
else
{
$this->station_fuel_prices->store($station[0]['sid'],[
'fuel_code' => $value->fuel_code,
'fuel_name' => isset($fuel_type[$value->fuel_code]) ? $fuel_type[$value->fuel_code] : '',
'price' => $value->price,
]);
}
$fuel_prices[] = [
'fuel_code' => $value->fuel_code,
'fuel_name' => isset($fuel_type[$value->fuel_code]) ? $fuel_type[$value->fuel_code] : '',
'price' => $value->price,
];
$except_where_in[] = $value->fuel_code;
}
}
}
// delete others
$this->station_fuel_prices->delete($station[0]['sid'],$except_where_in);
return $this->format->mobile_success('Success',[
'name' => $station[0]['description'],
'address' => $station[0]['address'],
'longitude' => $station[0]['longitude'],
'latitude' => $station[0]['latitude'],
'favorite' => $station[0]['favorite'] > 0 ? true : false,
'contact_numbers' => explode("/", $station[0]['contact_number']),
'stars' => round($station[0]['average']),
'fuel_prices' => $fuel_prices,
'latest_update' => $latest_update
]);
}
else
return $this->format->mobile_error('Station Not Found');
}
public function set_favorite($uuid)
{
$station = $this->station->getByField('station_uuid',$uuid);
if(count($station))
{
$member_details = CurrentUserHelper::get_currentMember();
if($this->station_favorite->store($station[0]['station_id'], $member_details->lcard_id))
{
$this->lcard_logs->log($station[0]['station_id'],'STATIONLOCATOR','STORE','Member added station to favorites');
return $this->format->mobile_success('Station added to favorites');
}
else
return $this->format->mobile_error('Error on save');
}
else
return $this->format->mobile_error('Station Not Found');
}
public function delete_favorite($uuid)
{
$station = $this->station->getByField('station_uuid',$uuid);
if(count($station))
{
$member_details = CurrentUserHelper::get_currentMember();
if($this->station_favorite->delete($station[0]['station_id'], $member_details->lcard_id))
{
$this->lcard_logs->log($station[0]['station_id'],'STATIONLOCATOR','DELETE','Member deleted a station to favorites');
return $this->format->mobile_success('Station deleted to favorites');
}
else
return $this->format->mobile_error('Error on delete');
}
else
return $this->format->mobile_error('Station Not Found');
}
/*
note : execute to sync details from stratuscast
*/
public function manual_overide()
{
$stratuscast = new StratuscastLibrary();
$stratuscast->getAllFuelPrice();
if(isset($stratuscast->response['data']))
{
foreach ($stratuscast->response['data'] as $key => $value) {
$searched = $this->station->search_by_code($value->station_code);
if(count($searched) > 0)
{
$this->station->update_content($value);
}
else
{
if(!$this->station->store($value))
{
return $this->format->badRequest('Something went wrong');
}
}
}
return $this->format->success('Success');
}
else
{
return $this->format->badRequest('Something went wrong');
}
}
//RNRPH Library
public function get_provinces(){
try {
$rnrph = new RNRPHLibrary();
$rnrph->getAllProvinces();
$return = [];
$previous_province = '';
$ctr = 0;
$current_array = [];
foreach ($rnrph->response['data'] as $key => $province)
{
if($previous_province != $province->name)
{
if($ctr != 0)
$return[] = $current_array;
$current_array = [];
$current_array['name'] = $province->name;
$current_array['city'][] = [
'name' => $province->city_name,
'city_uuid' => $province->city_uuid,
];
}
else
{
$current_array['city'][] = [
'name' => $province->city_name,
'city_uuid' => $province->city_uuid,
];
}
$previous_province = $province->name;
$ctr++;
}
return $this->format->mobile_success('Success',$return);
} catch (Exception $e) {
return $this->format->mobile_error('Something went wrong');
}
}
public function get_stations(){
try {
$rnrph = new RNRPHLibrary();
$rnrph->getAllStations();
$details = $rnrph->response['data'];
if(count($details) > 0)
{
$parsed = array();
foreach ($details as $key => $value)
{
$parsed[] = array(
'station_uuid' => $value->station_uuid,
'code' => $value->code,
'description' => $value->description,
);
}
return $this->format->success('Success',$parsed);
}
else
{
return $this->format->noContent('No stations saved');
}
} catch (Exception $e) {
return $this->format->mobile_error('Something went wrong');
}
}
public function get_cities(){
try {
$rnrph = new RNRPHLibrary();
$rnrph->getAllBranches();
$details = $rnrph->response['data'];
if(count($details) > 0)
{
return $this->format->success('Success',$details);
}
else
{
return $this->format->noContent('No stations saved');
}
} catch (Exception $e) {
return $this->format->mobile_error('Something went wrong');
}
}
public function db_get_station_fuel_prices($id) {
try{
$fuel_prices = [];
$db_fuel_prices = $this->station_fuel_prices->getByField([
'station_id' => $id,
'is_active' => 1,
],
null,
[
'field' => 'updated_at',
'value' => 'asc'
]);
$db = [];
$latest_update = date('M d, Y');
if(count($db_fuel_prices))
{
foreach ($db_fuel_prices as $k => $v)
{
// $db[$v['fuel_code']] = array(
// 'fuel_code' => $v->fuel_code,
// 'fuel_name' => $v->fuel_name,
// 'price' => $v->price
// );
$db[] = array(
'fuel_code' => $v->fuel_code,
'fuel_name' => $v->fuel_name,
'price' => $v->price
);
// $db[] = $v;
$latest_update = date('M d, Y',strtotime($v['updated_at']));
}
return array(
'latest_update' => $latest_update,
'list' => $db
);
}else{
return array(
'latest_update' => "",
'list' => []
);
}
}catch(Exception $e){
return array(
'latest_update' => "",
'list' => []
);
}
}
public function sort_fuels($fuels){
}
public function get_station_fuels(){
try {
$rnrph = new RNRPHLibrary();
$rnrph->getAllStations();
$details = $rnrph->response['data'];
if(count($details) > 0)
{
$stations = array();
foreach ($details as $key => $value)
{
$fuelFromDB = $this->parse_fuels($value->StationFuels);
$stations[] = array(
'name' => $value->description,
'address' => $value->address,
'longitude' => $value->longitude,
'latitude' => $value->latitude,
// 'favorite' => $value->favorite && $value->favorite > 0 ? true : false,
'favorite' => false,
'contact_numbers' => $value->contact_number,
// 'stars' => round($value->rating || 0),
'stars' => 0,
'fuel_prices' => $fuelFromDB['list'],
'latest_update' => $fuelFromDB['latest_update'],
'full' => $value
);
}
return $this->format->success('Success', $stations);
}
else
{
return $this->format->noContent('No stations saved');
}
} catch (Exception $e) {
return $this->format->mobile_error('Something went wrong');
}
}
public function manual_update()
{
$stratuscast = new RNRPHLibrary();
$stratuscast->getAllStations();
if(isset($stratuscast->response['data']))
{
$ids = [];
$st = $this->station->get_active_stations();
foreach ($st as $key => $value) {
array_push($ids,$value->station_id);
}
$this->station->disbale_stations($ids);
foreach ($stratuscast->response['data'] as $key => $value) {
$searched = $this->station->search_by_code($value->code);
if(count($searched) > 0)
{
$this->station->update_stations($value);
}
else
{
if(!$this->station->store($value))
{
return $this->format->badRequest('Something went wrong');
}
}
}
return $this->format->success('Success');
}
else
{
return $this->format->badRequest('Something went wrong');
}
}
public function parse_fuels($fuels) {
try{
$fuel_prices = [];
$db = [];
$latest_update = date('M d, Y');
if(count($fuels))
{
foreach ($fuels as $k => $v)
{
$db[] = array(
'fuel_code' => $v->Fuel->code,
'fuel_name' => $v->Fuel->name,
'price' => $v->price
);
$latest_update = date('M d, Y',strtotime($v->updatedAt));
}
return array(
'latest_update' => $latest_update,
'list' => $db
);
}else{
return array(
'latest_update' => "",
'list' => []
);
}
}catch(Exception $e){
return array(
'latest_update' => "",
'list' => []
);
}
}
function sortByField($multArray,$sortField,$desc=true){
$tmpKey='';
$ResArray=array();
$maIndex=array_keys($multArray);
$maSize=count($multArray)-1;
for($i=0; $i < $maSize ; $i++) {
$minElement=$i;
$tempMin=$multArray[$maIndex[$i]][$sortField];
$tmpKey=$maIndex[$i];
for($j=$i+1; $j <= $maSize; $j++)
if($multArray[$maIndex[$j]][$sortField] < $tempMin ) {
$minElement=$j;
$tmpKey=$maIndex[$j];
$tempMin=$multArray[$maIndex[$j]][$sortField];
}
$maIndex[$minElement]=$maIndex[$i];
$maIndex[$i]=$tmpKey;
}
if($desc)
for($j=0;$j<=$maSize;$j++)
// $ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]];
$ResArray[] = $multArray[$maIndex[$j]];
else
for($j=$maSize;$j>=0;$j--)
// $ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]];
$ResArray[] = $multArray[$maIndex[$j]];
return array_reverse($ResArray);
}
public function get_station_fuel_details($uuid){
try {
$station = $this->station->search_by_uuid($uuid);
if($station && $station[0])
{
// $this->lcard_logs->log($station[0]['sid'],'STATIONLOCATOR','VIEW','Member views station details');
$rnrph = new RNRPHLibrary();
$rnrph->getStationDetails($station[0]['code']);
$details = $rnrph->response['data'];
$db_fuel_prices = $this->station_fuel_prices->getByField([
'station_id' => $station[0]['sid'],
'is_active' => 1,
],
null,
[
'field' => 'updated_at',
'value' => 'asc'
]);
$db = [];
$latest_update = date('M d, Y');
if(count($db_fuel_prices))
{
foreach ($db_fuel_prices as $k => $v)
{
$db[$v['fuel_code']] = $v;
$latest_update = date('M d, Y',strtotime($details->StationFuels[0]->updatedAt));
}
}
$fuel_type = StaticContents::fuelType_code();
$fuel_prices = [];
$except_where_in = []; // delete fuel prices that are not returned by stratuscast
if(count($details->StationFuels))
{
foreach ($details->StationFuels as $key => $value) {
if(isset($db[$value->Fuel->code]))
{
if($db[$value->Fuel->code]['price'] != $value->price)
$this->station_fuel_prices->update_price($db[$value->Fuel->code]['fuel_price_uuid'],$value->price);
}
else
{
$this->station_fuel_prices->store($station[0]['sid'],[
'fuel_code' => $value->Fuel->code,
'fuel_name' => isset($fuel_type[$value->Fuel->code]) ? $fuel_type[$value->Fuel->code] : '',
'price' => $value->price,
]);
}
$fuel_prices[] = [
'fuel_code' => $value->Fuel->code,
'fuel_name' => isset($fuel_type[$value->Fuel->code]) ? $fuel_type[$value->Fuel->code] : '',
'price' => $value->price,
];
$except_where_in[] = $value->Fuel->code;
}
}
// delete others
$this->station_fuel_prices->delete($station[0]['sid'],$except_where_in);
return $this->format->mobile_success('Success',[
'name' => $station[0]['description'],
'address' => $station[0]['address'],
'longitude' => $station[0]['longitude'],
'latitude' => $station[0]['latitude'],
'favorite' => $station[0]['favorite'] > 0 ? true : false,
'contact_numbers' => explode("/", $station[0]['contact_number']),
'stars' => round($station[0]['average']),
'fuel_prices' => $this->sortByField($fuel_prices, "fuel_code"),
'latest_update' => $latest_update
]);
}
else
return $this->format->mobile_error('Station Not Found');
} catch (Exception $e) {
return $this->format->mobile_error('Something went wrong');
}
}
// public function get_station_fuel_details2($uuid){
// try {
// $station = $this->station->search_by_uuid($uuid);
// if($station && $station[0])
// {
// $this->lcard_logs->log($station[0]['sid'],'STATIONLOCATOR','VIEW','Member views station details');
// $rnrph = new RNRPHLibrary();
// $rnrph->getStationDetails($station[0]['code']);
// $details = $rnrph->response['data'];
// $db_fuel_prices = $this->station_fuel_prices->getByField([
// 'station_id' => $station[0]['sid'],
// 'is_active' => 1,
// ],
// null,
// [
// 'field' => 'updated_at',
// 'value' => 'asc'
// ]);
// $db = [];
// $latest_update = date('M d, Y');
// if(count($db_fuel_prices))
// {
// foreach ($db_fuel_prices as $k => $v)
// {
// $db[$v['fuel_code']] = $v;
// $latest_update = date('M d, Y',strtotime($details->StationFuels[0]->updatedAt));
// }
// }
// $fuel_type = StaticContents::fuelType_code();
// $fuel_prices = [];
// $except_where_in = []; // delete fuel prices that are not returned by stratuscast
// if(count($details->StationFuels))
// {
// foreach ($details->StationFuels as $key => $value) {
// if(isset($db[$value->Fuel->code]))
// {
// if($db[$value->Fuel->code]['price'] != $value->price)
// $this->station_fuel_prices->update_price($db[$value->Fuel->code]['fuel_price_uuid'],$value->price);
// }
// else
// {
// $this->station_fuel_prices->store($station[0]['sid'],[
// 'fuel_code' => $value->Fuel->code,
// 'fuel_name' => isset($fuel_type[$value->Fuel->code]) ? $fuel_type[$value->Fuel->code] : '',
// 'price' => $value->price,
// ]);
// }
// $fuel_prices[] = [
// 'fuel_code' => $value->Fuel->code,
// 'fuel_name' => isset($fuel_type[$value->Fuel->code]) ? $fuel_type[$value->Fuel->code] : '',
// 'price' => $value->price,
// ];
// $except_where_in[] = $value->Fuel->code;
// }
// }
// // delete others
// $this->station_fuel_prices->delete($station[0]['sid'],$except_where_in);
// return $this->format->mobile_success('Success',[
// 'name' => $station[0]['description'],
// 'address' => $station[0]['address'],
// 'longitude' => $station[0]['longitude'],
// 'latitude' => $station[0]['latitude'],
// 'favorite' => $station[0]['favorite'] > 0 ? true : false,
// 'contact_numbers' => explode("/", $station[0]['contact_number']),
// 'stars' => round($station[0]['average']),
// 'fuel_prices' => $this->sortByField($fuel_prices, "fuel_code"),
// 'latest_update' => $latest_update
// ]);
// }
// else
// return $this->format->mobile_error('Station Not Found');
// } catch (Exception $e) {
// return $this->format->mobile_error('Something went wrong');
// }
// }
}