<?php
namespace FAAPI;

$path_to_root = "../..";

include_once ($path_to_root . "/sales/includes/db/customers_db.inc");
include_once ($path_to_root . "/includes/db/crm_contacts_db.inc");
include_once ($path_to_root . "/modules/external/stock/db.php");

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

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

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

	// Get Specific Item by Id
	public function getById($rest, $id) {
		$cust = get_customer($id);
		api_success_response(json_encode(api_ensureAssociativeArray($cust)));
	}
        
        // Get Specific Item by Id
	public function getCustomerDetails($rest, $id) {
		$cust = get_customer_details($id);
		api_success_response(json_encode(api_ensureAssociativeArray($cust)));
	}

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

		// Validate Required Fields
		if (empty($info['name'])) {
			api_error(200, 'Customer Name is required [name]');
		}
		if (empty($info['debtor_ref'])) {
			api_error(200, 'Customer Reference is required [debtor_ref]');
		}
		if (empty($info['address'])) {
			$info['address'] = 'N/A';
		}
		if (empty($info['tax_id'])) {
			$info['discount'] = '';
		}
		if (empty($info['curr_code'])) {
			api_error(200, 'Currency Code is required [curr_code]');
		}
		if (empty($info['credit_status'])) {
			$info['credit_status'] = '1';
		}
		if (empty($info['payment_terms']) || empty($info['payment_terms']['terms_indicator'])) {
			api_error(200, 'Payment Terms is required [payment_terms]');
		}
		if (empty($info['discount'])) {
			$info['discount'] = 0;
		}
		if (empty($info['pymt_discount'])) {
			$info['pymt_discount'] = 0;
		}
		if (empty($info['credit_limit'])) {
			$info['credit_limit'] = 0;
		}
		if (empty($info['sales_type']) || empty($info['sales_type']['id'])) {
			$info['sales_type']['id'] = '1';
		}
                if (empty($info['dimension']) || empty($info['dimension']['id'])) {
			$info['dimension']['id'] = '0';
		}
                if (empty($info['dimension2']) || empty($info['dimension2']['id'])) {
			$info['dimension2']['id'] = '0';
		}
		if (empty($info['notes'])) {
			$info['notes'] = '';
		}

		// For default branch
		if (! isset($info['NewCustomerTaxGroup'])) {
			api_error(200, 'Tax Group is required');
		}
		if (! isset($info['NewCustomerLocation'])) {
			api_error(200, 'Default Location is required');
		}
		if (! isset($info['salesman'])) {
			$info['salesman'] = '1';
		}
		if (! isset($info['area'])) {
			$info['area'] = '1';
		}
		if (! isset($info['ship_via'])) {
			$info['ship_via'] = '1';
		}
		if (! isset($info['phone'])) {
			$info['phone'] = '';
		}
		if (! isset($info['phone2'])) {
			$info['phone2'] = '';
		}
		if (! isset($info['fax'])) {
			$info['fax'] = '';
		}
		if (! isset($info['email'])) {
			$info['email'] = '';
		}

                if(!empty($info['customer_id'])){
                    $selected_id = $info['customer_id'];
                    update_customer($selected_id,$info['name'], $info['debtor_ref'], $info['address'], $info['tax_id'], $info['curr_code'], $info['dimension']['id'], $info['dimension2']['id'], $info['credit_status'], $info['payment_terms']['terms_indicator'], $info['discount'], $info['pymt_discount'], $info['credit_limit'], $info['sales_type']['id'], $info['notes']);
                } else {
                    add_customer($info['name'], $info['debtor_ref'], $info['address'], $info['tax_id'], $info['curr_code'], $info['dimension']['id'], $info['dimension2']['id'], $info['credit_status'], $info['payment_terms']['terms_indicator'], $info['discount'], $info['pymt_discount'], $info['credit_limit'], $info['sales_type']['id'], $info['notes']);

                    $selected_id = db_insert_id();
                    $auto_create_branch = 1;
                    if (isset($auto_create_branch) && $auto_create_branch == 1) {
                            add_branch($selected_id, $info['name'], $info['debtor_ref'], $info['address'], $info['salesman'], $info['area'], $info['NewCustomerTaxGroup'], '1', get_company_pref('default_sales_discount_act'), get_company_pref('debtors_act'), get_company_pref('default_prompt_payment_act'), $info['NewCustomerLocation'], $info['address'], 0, 0, $info['ship_via'], $info['notes']);
                            $selected_branch = db_insert_id();

                            $pers_id = add_crm_person($info['debtor_ref'], $info['name'], '', $info['address'], $info['phone'], $info['phone2'], $info['fax'], $info['email'], '', '');
                            
                            add_crm_contact('cust_branch', 'general', $selected_branch, $pers_id);
                            add_crm_contact('customer', 'general', $selected_id, $pers_id);
                    }
                }
		$cust = get_customer($selected_id);
		if ($cust != null) {
			api_success_response(json_encode($cust));
		} else {
			api_error(200, 'Could Not Save to Database');
		}
	}

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

		$cust = get_customer($id);
		if ($cust == null) {
			api_error(400, 'Invalid Customer ID');
		}

		delete_customer($id);

		$cust = null;
		$cust = get_customer($id);

		if ($cust != null) {
			api_error(500, 'Could Not Delete from Database');
		} else {
			api_success_response("Customer has been deleted");
		}
	}

	public function getBranches($rest, $id) {
		$sql = "SELECT " .
			"b.branch_code, " .
			"b.branch_ref, " .
			"b.br_name, " .
			"b.default_location, " .
			"p.name as contact_name, " .
			"s.salesman_name, " .
			"a.description, " .
			"p.phone, " .
			"p.fax, " .
			"p.email, " .
			"b.tax_group_id, " .
			"t.name AS tax_group_name, " .
			"b.inactive " .
			" FROM " . TB_PREF . "cust_branch b " .
			"LEFT JOIN " . TB_PREF . "crm_contacts c ON c.entity_id=b.branch_code AND c.type='cust_branch' AND c.action='general' " .
			"LEFT JOIN " . TB_PREF . "crm_persons p on c.person_id=p.id," . TB_PREF . "areas a, " . TB_PREF . "salesman s, " . TB_PREF . "tax_groups t
			WHERE b.tax_group_id=t.id
			AND b.area=a.area_code
			AND b.salesman=s.salesman_code
			AND b.debtor_no = " . db_escape($id) . " AND !b.inactive GROUP BY b.branch_code ORDER BY branch_ref";

		$result = db_query($sql, "Cannot Get Customer Branches");

		$info = array();
                $i = 0;
		while ($branch = db_fetch($result)) {
                        $location = get_inventory_location($branch['default_location']);
                        $branch['default_location'] = $location;
			$info[] = $branch;
                        $i++;
		}
		$response['items'] = $info;
                $response['incomplete_results'] = FALSE;
                $response['total_count'] = $i;
                api_success_response(json_encode($response));
	}

	private function customer_all($from = null) {
		if ($from == null)
			$from = 0;
                $length = 1000;
                
                $where = "";
                if(!empty($_GET['dimension'])){
                    $where = " AND dimension_id=".db_escape($_GET['dimension']);
                }
		$sql = "SELECT * FROM " . TB_PREF . "debtors_master WHERE !inactive ".$where." LIMIT " . $from . ", " . $length;

		$query = db_query($sql, "error");

		$info = array();

		while ($data = db_fetch_assoc($query, "error")) {
                    $sales_type = get_sales_type($data['sales_type']);
                    $payment_terms = get_payment_terms($data['payment_terms']);
                    $dimension1 = get_dimension($data['dimension_id'],true);
                    $dimension2 = get_dimension($data['dimension2_id'],true);
                    $data = $this->utf8ize($data);
                    $data["sales_type"] = $sales_type;
                    $data["payment_terms"] = $payment_terms;
                    $data["dimension"] = $dimension1 ? $dimension1 : null;
                    $data["dimension2"] = $dimension2 ? $dimension2 : null;
                    $data["phone"] = "";
                    $data['CustomerBalance'] = "0"; 
                    $info[] = $data;
		}
		
                $response['items'] = $info;
                $response['incomplete_results'] = FALSE;
                $response['total_count'] = $length;
                api_success_response(json_encode($response));
	}
	
	private function utf8ize($d) {
        if (is_array($d)) 
            foreach ($d as $k => $v) 
                $d[$k] = $this->utf8ize($v);
    
         else if(is_object($d))
            foreach ($d as $k => $v) 
                $d->$k = $this->utf8ize($v);
    
         else 
            return utf8_encode($d);
    
        return $d;
    }
}