<?php
function respond($http_code, $status_message, $data = NULL)
{
    $CI = & get_instance();
    $CI->output->set_status_header($http_code, $status_message);
    $CI->output->set_output($data);
}

function respond_ok($data = NULL)
{
    if (is_null($data))
    {
        return respond(204, 'No Content'); // No Content
    }
    else
    {
        // set JSON content-type header as we use respond_ok in controllers that
        // extends Cf_REST_Controller (API) and they should return valid JSON.
        header('Content-Type: application/json');

        return respond(200, 'OK', $data); // OK
    }
}

function respond_created($data = null)
{
    return respond(201, 'Created', $data);
}

function respond_unauthorized($data='')
{
    return respond(401, 'Unauthorized',$data);
}

function respond_not_found($data = NULL, $status_message = 'Not Found')
{
    return respond(404, $status_message, $data);
}

function respond_forbidden()
{
    return respond(403);
}

function respond_internal_error($data = NULL, $status_message = 'Internal Server Error')
{
	$dataToLog = json_decode($data);
	if(isset($dataToLog->text) && !empty($dataToLog->text)){
		log_message('error', $dataToLog->text);
	}
    return respond(500, $status_message, $data);
}

function respond_not_acceptable($data = NULL, $status_message = 'Not Acceptable')
{
    return respond(406, $status_message, $data);
}

function download_file($filePath, $name)
{
    //set headers to download file
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $name . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($filePath));
    ob_clean();
    flush();
    readfile($filePath);
}
