<?php

class PopularApi extends Api
{
    public $apiName = 'popular';

    public function indexAction()
    {
        return $this->response(
            array(
                'error' => 'Data not found'
            ), 404);
    }

    /**
     * Method GET
     * Get single record (by id)
     * http://DOMAIN/trips/1
     * @return string
     */
    public function viewAction()
    {
        return $this->response(
            array(
                'error'=> 'Data not found'
            ), 404);
    }

    public function createAction()
    {
        syslog(LOG_WARNING,'PopularApi::createAction()');
        $message = 'Data not found';
        $code = 404;
        $time = $this->requestParams['time'] ?? '';
        $location = $this->requestParams['location'] ?? [];
        $country = $this->requestParams['country'] ?? Popular::DEFAULT_COUNTRY;
        $member_id = $this->requestParams['member_id'] ?? 0;
        try {
            $db = new Db();

            // DEUG
            $country = Geocode::mockGPSCountry($db->getConnect(), $member_id, $country, 'default');

            if ($country!='US' && $country!='SG') {
                throw new RuntimeException('Trips has not yet launched in your country. You can still track your travel activity and access exclusive deals. Start exploring!',500);
            }
            if ($member_id<1) {
                throw new RuntimeException('Invalid member ID',500);
            }
            /* if ($time=='' || strtotime($time)<Popular::TIME_LIMIT) { 
                throw new RuntimeException('Invalid time',500);
            } */
            if (!is_array($location) || !array_key_exists('lat',$location) || !array_key_exists('lng',$location)) {
                throw new RuntimeException('You did not provide you GPS location',500);
            }
            if ($location["lat"]==NULL || $location["lng"]==NULL || ($location["lat"]==0 && $location["lng"]==0)) {
                throw new RuntimeException('Invalid GPS location provided',500);
            }
            $address = NULL;
            $street_address = "";

            // DEBUG
            list($location["lat"],$location["lng"]) = Geocode::mockGPSLocation(
                $db->getConnect(), $member_id, $location["lat"], $location["lng"], 'default');

            syslog(LOG_WARNING,"lat=".$location["lat"].",lng=".$location["lng"]);
            list($street_address,$err) = GeocodeApi::reverseGeocode($db, $location["lat"], $location["lng"]);
            if ($street_address=="") {
                throw new RuntimeException($err?"Geocoder failed: $err":'Cannot geocode your GSP location',500);
            }
            syslog(LOG_WARNING,"street_address=".json_encode($street_address));
            list($address,$err) = Geocode::checkLatLngByAddress($db->getConnect(), $street_address, $country);
            if (!is_array($address) || !isset($address["address"])) {
                throw new RuntimeException($err?"Geocoder failed: $err":'Cannot get address for your GPS location',500);
            }
            syslog(LOG_WARNING,json_encode($address));

            // Step 1. Get activities
            list($res,$err) = Popular::getPopular(
                $db->getConnect(), $db->getConnectGPS(),
                $member_id, $location["lat"], $location["lng"], 
                $time, Popular::TIME_DELTA, /* last 2 parameters are not used at the moment */
                Popular::POPULAR_RADIUS, $country
            );
            if (!$res || count($res)<1) {
                if ($err!="") {
                    throw new RuntimeException($err, 500);
                }
                throw new RuntimeException('No popular trips nearby found', 404);
            }
            syslog(LOG_WARNING,'Popular trips has '.count($res).' trips!');
            $destination_cache = [];
            $result = [];
            $i = 0;
            foreach ($res as $trip) {
                list($trip, $destination_cache) = ActivityApi::processAddressTrip($db, $country, $address, $trip, $destination_cache);
                if ($trip==NULL) continue;
                $advice = ActivityApi::processAdvice($db, $member_id, $country, $trip);
                if ($advice && count($advice)>0) {
                    $result[] = $advice;
                    $i++;
                }
                if ($i>=Popular::DEFAULT_OPTIONS) {
                    break;
                }
            }
            $result = ActivityApi::processQuotesTrips($db, $member_id, $country, $result);
            //$result = ActivityApi::processGojekOption($db, $member_id, $country, $result);
            return $this->response(
                array(
                    "trips" => $result,
                    "street_address" => html_entity_decode($street_address)
                ), 200);
        } catch (RuntimeException $e) {
            $message = $e->getMessage();
            $code = $e->getCode();
            syslog(LOG_WARNING,$message);
        }
        return $this->response(
            array(
                "error" => $message
            ), $code);
    }

    public function updateAction()
    {
        return $this->response(
            array(
                "error" => "Update error"
            ), 400);
    }

    public function deleteAction()
    {
        return $this->response(
            array(
                "error" => "Delete error"
            ), 500);
    }

}
