<?php
namespace FAAPI;

$path_to_root = "../..";

include_once ($path_to_root . "/inventory/includes/db/items_category_db.inc");

class SalesTypes {
	// Get Items
	public function get($rest) {
		$req = $rest->request();

		$page = $req->get("page");

		if ($page == null) {
			$this->sales_types_all(null);
		} else {
			// If page = 1 the value will be 0, if page = 2 the value will be 1, ...
			$from = -- $page * RESULTS_PER_PAGE;
			$this->sales_types_all($from);
		}
	}

	// Get Specific Item by Id
	public function getById($rest, $id) {
		$type = get_sales_type($id);
		api_success_response(json_encode(api_ensureAssociativeArray($type)));
	}

	// Add Item
	public function post($rest,$id) {
		$req = $rest->request();
		$info = $req->post();

		// Validate Required Fields
		if(empty($info['sales_type'])){
			api_error(200, 'Sales Type Name is required');
		}
		if(!is_numeric($info['factor'])){
			$info['factor'] = 1;
		}
		if(!is_numeric($info['tax_included'])){
			$info['tax_included'] = 0;
		}
                
                if($id){
                    update_sales_type($id, $info['sales_type'],$info['tax_included'],$info['factor']);
                } else {
                    add_sales_type($info['sales_type'],$info['tax_included'],$info['factor']);
                    $id = db_insert_id();
                }
		$type = get_sales_type($id);

		if($type != null){
                    api_success_response(json_encode($type));
		}else {
			api_error(200, 'Could Not Save to Database');
		}
	}

	
	// Delete Specific Item
	public function delete($rest, $id) {
		$req = $rest->request();
		$info = $req->post();

		$catego = get_sales_type($id);
		if($catego == null){
			api_error(200, 'Invalid Sales Type ID');
		}

		delete_sales_type($id);

		$catego = get_sales_type($id);

		if($catego != null){
			api_error(200, 'Could Not Delete from Database: ');
		}else {
			api_success_response("Sales Type has been deleted");
		}
	}

	private function sales_types_all($from = null) {
                $length = RESULTS_PER_PAGE;
		$query = get_all_sales_types(false);

		$info = array();

		while ($data = db_fetch_assoc($query, "error")) {
			$info[] = $data;
		}

		$response['items'] = $info;
                $response['incomplete_results'] = FALSE;
                $response['total_count'] = $length;
                api_success_response(json_encode($response));
	}
}