<?php
/**
 * This report source has a different structure than the other sources. It filters the records before populating the data
 * and uses a temporary table to obtain the balance ids to be displayed after filtering
 * - first a temporary table is created to store the balance ids that will be used when populating the report data
 * - it applies the filters from the interface in the following order:
 *      - the client invoice rows issues are filtered first by using the services idBalance reference from rd_services
 *      - the refunded client inv rows are inserted next (using INSERT IGNORE) by using the idBalanceRefund reference from
 *      rd_services table
 *      - adds the balances that contain only supplier invoices filtered by the balances filters (only if not client related
 *      filter was set)
 *      - if no client related filters were set and at least one supplier related filter was set, the balance (client invoice
 *       only) will not be displayed
 *      - if there are any supplier invoice related filter selected, the balance ids from the temp table which do not fit
 *       the filters selected will be deleted from the temp table
 * - after applying the filters, we obtain a list of balance ids (already) which will be used to populate the client/supplier
 * invoice rows:
 *      - the client invoice rows not refunded are inserted - the ones related to the idBalance reference from rd_services;
 *      to avoid duplicated rows they are filtered by the `refund` column -> refund=0
 *      - the client invoice rows refunded are inserted - the ones related to the idBalanceRefund reference from rd_services;
 *      to avoid duplicated rows they are filtered by the `refund` column -> refund=1
 *      - the supplier invoice rows are inserted next with the related data
 * @author LauraMotoc
 */
$availableTableColumns = array_keys($tableColumns);
// PREPROCESS FILTERS /////////////////////////////////////////////////////////////////////////////
// cleanup dates
$reportFilters['balanceDate']['startDate'] = standard2mysqlDateConversion($reportFilters['balanceDate']['startDate']);
$reportFilters['balanceDate']['endDate'] = standard2mysqlDateConversion($reportFilters['balanceDate']['endDate']);

$reportFilters['orderDate']['startDate'] = standard2mysqlDateConversion($reportFilters['orderDate']['startDate']);
$reportFilters['orderDate']['endDate'] = standard2mysqlDateConversion($reportFilters['orderDate']['endDate']);

if ($reportFilters['offerStartDatetime']['startDate']) {
	$reportFilters['offerStartDatetime']['startDate'] = standard2mysqlDateConversion($reportFilters['offerStartDatetime']['startDate'])." 00:00:00";
}
if ($reportFilters['offerStartDatetime']['endDate']) {
	$reportFilters['offerStartDatetime']['endDate'] = standard2mysqlDateConversion($reportFilters['offerStartDatetime']['endDate'])." 23:59:59";
}

if ($reportFilters['offerEndDatetime']['startDate']) {
	$reportFilters['offerEndDatetime']['startDate'] = standard2mysqlDateConversion($reportFilters['offerEndDatetime']['startDate'])." 00:00:00";
}
if ($reportFilters['offerEndDatetime']['endDate']) {
	$reportFilters['offerEndDatetime']['endDate'] = standard2mysqlDateConversion($reportFilters['offerEndDatetime']['endDate'])." 23:59:59";
}

if ($reportFilters['offerPeriod']['startDate']) {
	$reportFilters['offerPeriod']['startDate'] = standard2mysqlDateConversion($reportFilters['offerPeriod']['startDate'])." 00:00:00";
}
if ($reportFilters['offerPeriod']['endDate']) {
	$reportFilters['offerPeriod']['endDate'] = standard2mysqlDateConversion($reportFilters['offerPeriod']['endDate'])." 23:59:59";
}

$reportFilters['clientInvDate']['startDate'] = standard2mysqlDateConversion($reportFilters['clientInvDate']['startDate']);
$reportFilters['clientInvDate']['endDate'] = standard2mysqlDateConversion($reportFilters['clientInvDate']['endDate']);

$reportFilters['supplierInvDate']['startDate'] = standard2mysqlDateConversion($reportFilters['supplierInvDate']['startDate']);
$reportFilters['supplierInvDate']['endDate'] = standard2mysqlDateConversion($reportFilters['supplierInvDate']['endDate']);


// cleanup responsible user
list($reportFilters['balanceRespOfficeUser']['idOffice'], $reportFilters['balanceRespOfficeUser']['idUser']) = explode("|", $reportFilters['balanceRespOfficeUser']['id']);
list($reportFilters['orderRespOfficeUser']['idOffice'], $reportFilters['orderRespOfficeUser']['idUser']) = explode("|", $reportFilters['orderRespOfficeUser']['id']);

// cleanup invoice clients filters
$reportFilters['idInvoiceCorporate'] = $reportFilters['clientInvCorporate']['id'];
$reportFilters['idInvoiceCustomer'] = $reportFilters['clientInvCustomer']['id'];
$reportFilters['idInvoiceSupplier'] = $reportFilters['supplier']['id'];

$reportFilters['clientInvClientType'] = (array)$reportFilters['clientInvClientType'];
$reportFilters['clientServiceType'] = (array)$reportFilters['clientServiceType'];

// PREPARE EXTRA FILTERS
$reportExtraFilters = [];
if ($reportFilters['idInvoiceCorporate']) {
	$reportExtraFilters['invoiceCorporateIds'] = \Entity\Corporate::select($reportFilters['idInvoiceCorporate'])->fullDuplicatedCorporatesGroup;
}
if ($reportFilters['idInvoiceCustomer']) {
	$reportExtraFilters['invoiceCustomerIds'] = \Entity\Customer::select($reportFilters['idInvoiceCustomer'])->fullDuplicatedCustomersGroup;
}
if ($reportFilters['idInvoiceSupplier']) {
	$reportExtraFilters['invoiceSupplierIds'] = \Entity\Supplier::select($reportFilters['idInvoiceSupplier'])->fullDuplicatedSuppliersGroup;
}

$reportExtraFilters['idInvoiceCorporateTrust'] = $reportFilters['clientInvCorporateTrust']['id'];
$reportExtraFilters['idInvoiceSupplierTrust'] = $reportFilters['supplierTrust']['id'];

try {
	// EXECUTE INITIAL FILTER FOR BALANCES ---------------------------------------------------------
	include(__DIR__."/reportData_initialFilter.php");

	// EXCUTE MAIN SQLs ---------------------------------------------------------------------------
	include(__DIR__."/reportData_executeSQL.php");

	// FILL IN OTHER FIELDS -----------------------------------------------------------------------
	include(__DIR__."/reportData_otherFields.php");

} catch (\DBException $e) {
	killReport("Could not run SQL in report. SQL error: ".$e->getMessage());
} catch (\Exception $e) {
	killReport("Could not process report. Error: ".$e->getMessage());
}
