<?php

class TripsApi extends Api
{
    public $apiName = 'trips';

    /**
     * Method GET
     * Get all records
     * http://DOMAIN/trips
     * @return string
     */
    public function indexAction()
    {
        // Get the parameters
        $members_id = (int)($this->requestParams['members_id'] ?? 22);
        $date1 = date('Y-m-d', strtotime($this->requestParams['date1'] ?? date("Y-m-1", strtotime('first day of last month'))));
        $date2 = date('Y-m-d', strtotime($this->requestParams['date2'] ?? date("Y-m-d")));
        $limit = (int)($this->requestParams['limit'] ?? 1000);
        $offset = (int)($this->requestParams['offset'] ?? 0);

        $db = new Db();
        list ($total, $trips) = Trips::getAll(
            $db->getConnect(), 
            $members_id, 
            $date1, $date2, 
            $limit, $offset);
        if($total>0){
            return $this->response(
                array(
                    'members_id' => $members_id,
                    'date1' => $date1,
                    'date2' => $date2,
                    'limit' => $limit,
                    'offset' => $offset,
                    'count' => count($trips),
                    'total' => (int)$total,
                    'trips' => $trips
                ), 200);
        }
        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()
    {
        //id must be the first parameter after /trips/x
        $id = array_shift($this->requestUri);

        if($id && (int)$id>0){
            $db = new Db();
            $trip = Trips::getById($db->getConnect(), (int)$id);
            if(is_array($trip) && count($trip)>0){
                return $this->response($trip, 200);
            }
        }
        return $this->response(
            array(
                'error'=> 'Data not found'
            ), 404);
    }

    /**
     * Method POST
     * Create new record
     * http://DOMAIN/trips + request parameters name, email
     * @return string
     */
    /*    
curl -d '{"origin": {"lat":1.2833754,"lng":103.8607264}, "destination":"97 Meyer Road, Singapore"}' \
-H "Content-Type: application/json" \
-X POST https://adminsavvy.sworks.float.sg/SAVVY/trips/api/trips

curl -d '{"encrypted_payload": "ba3ea1f5f4032cad1ea80f087bcc05354fa1ecfb7e81187c4f8deeb92b6f5ac742c8ce10a1f56f5e3bd5f18931d067e092c840e6b6ba30b433b5e63dd27fc34a67fa1e22011f74efdf3d22a3755a45687ecb45511bf882400b"}' \
-H "Content-Type: application/json" \
-X POST https://adminsavvy.sworks.float.sg/SAVVY/trips/api/trips

curl -d '{"origin": {"lat":1.2833754,"lng":103.8607264}, "destination":"11 Bayfront Ave, Singapore 018956"}' \
-X POST https://adminsavvy.sworks.float.sg/SAVVY/trips/api/trips
    */
    public function createAction()
    {
        global $httpAuthToken;
        $message = "Unknown error";
        $origin = $this->requestParams["origin"] ?? array();
        $destination = $this->requestParams["destination"] ?? "";
        if ($destination && count($origin)==2) {
            $db = new Db();
            $trip = Trips::getByLocations(
                $db->getConnect(), 
                $origin,
                $destination);
            if ($trip && $trip["id"]>0) {
                $tripOptions = Trips::getOptionsById($db->getConnect(), $trip["id"]);
                if(is_array($tripOptions) && count($tripOptions)>0){
                    $trip = array_merge($trip, array(
                        'count' => count($tripOptions),
                        'options' => $tripOptions
                    ));
                    return $this->response($trip, 200);
                } else {
                    $message = "Trip options not found!";
                }
            } else {
                // New trip
                $trip = self::tripService($origin,$destination);
                if (is_array($trip) && isset($trip["travel_date"])) {
                    return $this->response($trip, 200);
                }
                $message = "Failed to call service";
            }
            //var_dump($message);
            return $this->response(
                array(
                    'message' => 'Not implemented: ' . $message
                ), 500);
        }
        return $this->response(
            array(
                "error" => "Invalid request"
            ), 500);
    }

    /**
     * Method PUT
     * Update single record (by id)
     * http://DOMAIN/trips/1 + request parameters name, email
     * @return string
     */
    public function updateAction()
    {/*
        $parse_url = parse_url($this->requestUri[0]);
        $userId = $parse_url['path'] ?? null;

        $db = (new Db())->getConnect();

        if(!$userId || !Trips::getById($db, $userId)){
            return $this->response("Trip with id=$userId not found", 404);
        }

        $name = $this->requestParams['name'] ?? '';
        $email = $this->requestParams['email'] ?? '';

        if($name && $email){
            if($user = Trips::update($db, $userId, $name, $email)){
                return $this->response('Data updated.', 200);
            }
        }*/
        return $this->response(
            array(
                "error" => "Update error"
            ), 400);
    }

    /**
     * Method DELETE
     * Delete single record (by id)
     * http://DOMAIN/trips/1
     * @return string
     */
    public function deleteAction()
    {/*
        $parse_url = parse_url($this->requestUri[0]);
        $userId = $parse_url['path'] ?? null;

        $db = (new Db())->getConnect();

        if(!$userId || !Trips::getById($db, $userId)){
            return $this->response("Trip with id=$userId not found", 404);
        }
        if(Trips::deleteById($db, $userId)){
            return $this->response('Data deleted.', 200);
        }*/
        return $this->response(
            array(
                "error" => "Delete error"
            ), 500);
    }

    public function tripService($origin,$destination) {
        global $savvyext;
        $httpAuthToken = $savvyext->cfgReadChar('system.oauth2_token');
        $oauth2_url = $savvyext->cfgReadChar('system.oauth2_url');
        // curl -d 'origin_lat=1.2833754&origin_lng=103.8607264&destination=11 Bayfront Ave, Singapore 018956' -X POST $oauth2_url.'trips'/
        $postdata = http_build_query(
            array(
                'origin_lat' => $origin["lat"],
                'origin_lng' => $origin["lng"],
                'destination'=> $destination
            )
        );
        $url = $oauth2_url."trips";
        $opts = array(
            'http' => array(
                'method' => "POST",
                'header'  => 
                    "Content-Type: application/x-www-form-urlencoded\r\n" .
                    "Accept: application/json\r\n" .
                    "Authorization: Server-Token ${httpAuthToken}\r\n",
                'content' => $postdata
            ),
            "ssl" => array(
              "verify_peer"=>false,
              "verify_peer_name"=>false,
            )
        );
        $context = stream_context_create($opts);
        $body = file_get_contents($url, false, $context);
        $trip = json_decode($body,true);
        return $trip;
    }
}

