<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Authorization, Origin, X-Requested-With, Content-Type,      Accept");
header("Content-Type: application/json");

class Api extends Controller
{
    function __construct()
    {
        parent::Controller();

        $this->load->model('mapi');
    }

    function login()
    {
        $post = [
            'username'  => $_POST['username'],
            'password'  => $_POST['password']
        ];

        $headers = [
            'Accept: application/json',
        ];
        $ch = curl_init('https://partners.staging.cadline.hu/api/login');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

        $response = json_decode(curl_exec($ch));

        curl_close($ch);

        $ctrID = $response->ctrID;
        unset($response->ctrID);

        $result = $response;

        if ($response->access_token != '')
            $result = '{"message":"Token generated."}';

        $this->mapi->insertApiCallback('login', $result, $ctrID);

        echo json_encode($response);
    }

    function generateNonProfit()
    {
        $headers = getallheaders();
        $message = $this->mapi->checkToken($headers['Authorization']);
        $response = $message;
        $ctrID = $response->ctrID;

        unset($response->ctrID);

        if ($message->message == 'Success.') {
            $name   = $this->input->post('name');
            $email  = $this->input->post('email');
            $expire = $this->input->post('expire');

            $response = $this->mapi->createNonprofit($name, $email, $expire, $ctrID);

            $this->mapi->insertApiCallback('generateNonProfit', json_encode($response), $ctrID);
        }

        echo json_encode($response);
    }
}
