<?php

class CrashApi extends Api
{
    public $apiName = 'crash';

    public function __construct($requestUri, $encryption=true) {
        $this->requestWhitelist['createAction'] = 1;
        parent::__construct($requestUri, $encryption);
    }
    
    public function indexAction()
    {
        return $this->response(
            array(
                'error' => 'Data not found'
            ), 404);
    }

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

    public function createAction()
    {
        syslog(LOG_WARNING,"CrashApi::createAction()");
        $message = "CrashApi data not found";

        $member_id = $this->requestParams["member_id"] ?? "";
        $ip = $this->clientIP;
        $callstack = $this->requestParams["callstack"] ?? "";
        $data = $this->requestParams["data"] ?? "";
        $notes = $this->requestParams["notes"] ?? "";

        try {
            if ($callback=="" && $data=="" && $notes=="") {
                throw new Exception('No data to save in the crash log');
            }
            $db = new Db();
            $res = Crash::create(
                $db->getConnect(), $member_id, $ip, $callstack, $data, $notes
            );
            if (!$res || !array_key_exists('id',$res) || $res['id']<1) {
                syslog(LOG_WARNING, "$member_id, $ip, $callstack, $data, $notes");
                throw new Exception('Failed to create the crash log record');
            }
            return $this->response([
                "id" => $res["id"],
                "number" => $res["number"]
            ],200);
        } catch (Exception $e) {
            $message = $e->getMessage();
            syslog(LOG_WARNING,$message);
        } 
        return $this->response(
            array(
                "error" => $message
            ), 404);
    }

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

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