<?php
/*
 * Jetpack CRM
 * https://jetpackcrm.com
 * V3.0
 *
 * Copyright 2020 Automattic
 *
 * Date: 04/06/2019
 */

/*
======================================================
	Breaking Checks ( stops direct access )
	====================================================== */
if ( ! defined( 'ZEROBSCRM_PATH' ) ) {
	exit( 0 );
}
/*
======================================================
	/ Breaking Checks
	====================================================== */

// Check the method
// Ultimately this should be switched to GET, but the docs have it as POST, so best to wait for a rewrite
// Also seems to mostly be a duplicate of customer_search, other than not being able to search by email...

// phpcs:disabled WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase

global $zbs;

$json_params     = file_get_contents( 'php://input' );
$customer_params = json_decode( $json_params, true );

$perPage = 10;
if ( isset( $customer_params['perpage'] ) ) {
	$perPage = sanitize_text_field( $customer_params['perpage'] );
}
$page = 0;
if ( isset( $customer_params['page'] ) ) {
	$page = sanitize_text_field( $customer_params['page'] );
}
$withInvoices = false;
if ( isset( $customer_params['invoices'] ) ) {
	$withInvoices = filter_var( $customer_params['invoices'], FILTER_VALIDATE_BOOLEAN );
}
$withQuotes = false;
if ( isset( $customer_params['quotes'] ) ) {
	$withQuotes = filter_var( $customer_params['quotes'], FILTER_VALIDATE_BOOLEAN );
}
$searchPhrase = '';
if ( isset( $customer_params['search'] ) ) {
	$searchPhrase = sanitize_text_field( $customer_params['search'] );
}
$withTransactions = false;
if ( isset( $customer_params['transactions'] ) ) {
	$withTransactions = filter_var( $customer_params['transactions'], FILTER_VALIDATE_BOOLEAN );
}
$isOwned = -1;
if ( isset( $customer_params['owned'] ) ) {
	$isOwned = (int) $customer_params['owned'];
}

$companyID = -1;
if ( isset( $customer_params['company'] ) ) {
	$companyID = (int) $customer_params['company'];
}

$withTags = false;
if ( isset( $customer_params['tags'] ) ) {
	$withTags = filter_var( $customer_params['tags'], FILTER_VALIDATE_BOOLEAN );
}

$args = array(
	// Search/Filtering (leave as false to ignore)
	'searchPhrase'     => $searchPhrase,
	'inCompany'        => $companyID,
	'ownedBy'          => $isOwned,
	'withCustomFields' => true,
	'withQuotes'       => $withQuotes,
	'withInvoices'     => $withInvoices,
	'withTransactions' => $withTransactions,
	'withTags'         => $withTags,
	'page'             => $page,
	'perPage'          => $perPage,
	'ignoreowner'      => zeroBSCRM_DAL2_ignoreOwnership( ZBS_TYPE_CONTACT ),
);

$customers = $zbs->DAL->contacts->getContacts( $args );

wp_send_json( $customers, 200, JSON_UNESCAPED_SLASHES );

// phpcs:enabled WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase


