<?php

class TripInsightsApi extends Api
{
    public $apiName = 'tripinsights';
    const INSIGHTS = array(
        "cheaperAlternatives" => 1
    );
    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()
    {
        //id must be the first parameter after /trips/x
        $id = array_shift($this->requestUri);

        if($id && (int)$id>0){

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

    public function createAction()
    {
        $message = "Data not found";
        $member_id = $this->requestParams["member_id"] ?? 0;
        $trackedemail_item_id = $this->requestParams["trackedemail_item_id"] ?? 0;
        
        $result = [
            "insights" => [],
            "count" => 0,
            "messages" => []
        ];

        if ($member_id>0 && $trackedemail_item_id>0) {

            $db = new Db();

            $data = [
                "member_id" => $member_id,
                "trackedemail_item_id" => $trackedemail_item_id
            ];

            foreach (TripInsightsApi::INSIGHTS as $type=>$enabled) {
                if ($type!="" && $enabled==1) {
                    list ($res, $err) = call_user_func("TripInsights::${type}", 
                        $db->getConnect(), $db->getConnectGPS(), $data);
                    if($res!=NULL && is_array($res) && count($res)>0){
                        $result["insights"][] = $res;
                        $result["count"]++;
                    } else {
                        $result["messages"][] = $err!="" ? $err : "Empty result for ${type}";
                    }
                }
            }
            if ($result["count"]>0) {
                return $this->response($result, 200);
            }
        } else {
            $message = "Invalid input";
        }

        return $this->response(
            array(
                "error" => $message,
                "messages" => $result["messages"]
            ), 500);
    }

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

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