<?php

/* * ********************************************
  Author: Andres Amaya
  Name: REST API Utils
  Free software under GNU GPL
 * ********************************************* */

function api_login() {
    $app = \Slim\Slim::getInstance('SASYS');
    $app->hook('slim.before', function () use ($app) {
//        if(isset($_GET['CheckIsLive'])){
//            api_success_response(json_encode(utf8ize(Array("current_user"=>$_SESSION["wa_current_user"]),true)));
//            $app->stop();
//        }
        $req = $app->request();
        $company = $req->headers('X-COMPANY');
        $user = $req->headers('X-USER');
        $password = $req->headers('X-PASSWORD');
        // TESTING
        /* $company = 0;
          $user = 'admin';
          $password = '123'; */

        $succeed = $_SESSION["wa_current_user"]->login($company, $user, $password);
        if (!$succeed) {
            api_error(200, 'Bad Login For Company: ' . $company . ' With User: ' . $user);
        }
    }, 1);
}

function api_response($code, $body) {
    $app = \Slim\Slim::getInstance('SASYS');
    $app->response()->status($code);
    $app->response()->body(html_entity_decode($body, ENT_QUOTES | ENT_HTML5));
}

function api_success_response($body = NULL) {
    $app = \Slim\Slim::getInstance('SASYS');
    $app->response()->status(200);
    try{
        $bodyarray = json_decode($body,TRUE);
        $bodyarray = array_merge(array('success' => 1, 'msg' => "Success"),$bodyarray);
    } catch (Exception $e){
        $bodyarray = array('success' => 1, 'msg' => "Success");
    }
    $body = json_encode($bodyarray);
    $app->response()->body(html_entity_decode($body, ENT_QUOTES | ENT_HTML5));
    //$app->response()->['Content-Type'] = $content_type;
}

function api_create_response($body) {
    $app = \Slim\Slim::getInstance('SASYS');
    $app->response()->status(201);
    $app->response()->body(html_entity_decode($body, ENT_QUOTES | ENT_HTML5));
    //$app->response()->['Content-Type'] = $content_type;
}

function api_error($code, $msg) {
    $app = \Slim\Slim::getInstance('SASYS');
    $app->halt($code, json_encode(array('success' => 0, 'msg' => $msg)));
}

function api_field_error($code, $msg, $field) {
    $app = \Slim\Slim::getInstance('SASYS');
    $app->halt($code, json_encode(array('success' => 0, 'msg' => $msg, 'field' => $field)));
}

function api_ensureAssociativeArray($a) {
    if (!$a) {
        $a = array();
    }
    foreach ($a as $key => $value) {
        if (is_int($key)) {
            unset($a[$key]);
        }
    }
    return $a;
}

function utf8ize($d) {
        if (is_array($d)) 
            foreach ($d as $k => $v) 
                $d[$k] = utf8ize($v);
    
         else if(is_object($d))
            foreach ($d as $k => $v) 
                $d->$k = utf8ize($v);
    
         else 
            return utf8_encode($d);
    
        return $d;
    }

?>