<?php
class eventclass_customer_payment  extends TableEventsBase {
	
	function init() {
		$this->events = array(
	'BeforeAdd' => true,
	'BeforeEdit' => true,
	'AfterAdd' => true,
	'BeforeDelete' => true,
	'OnPageLoad' => true 
);
		$this->fieldValues = array(
	'filterLimit' => array(
		 
	),
	'mapIcon' => array(
		 
	),
	'viewCustom' => array(
		 
	),
	'lookupWhere' => array(
		 
	),
	'viewFileText' => array(
		 
	),
	'defaultValue' => array(
		'withholding_amount' => array(
			'edit' => true 
		),
		'bank_charge_amount' => array(
			'edit' => true 
		),
		'net_received_amount' => array(
			'edit' => true 
		),
		'applied_amount' => array(
			'edit' => true 
		),
		'unapplied_amount' => array(
			'edit' => true 
		) 
	),
	'autoUpdateValue' => array(
		 
	),
	'uploadFolder' => array(
		 
	),
	'viewPluginInit' => array(
		 
	),
	'editPluginInit' => array(
		 
	) 
);
			}
		function BeforeAdd( &$values, &$sqlValues, &$message, $inline, $pageObject ) {
		// BuildLedger Finance - Customer Payment Before Add

// UUID
if (empty($values["customer_payment_uuid"])) {
    $rs = DB::Query("SELECT UUID() AS uuid");
    $data = $rs->fetchAssoc();
    $values["customer_payment_uuid"] = $data["uuid"];
}

// Company fallback
if (empty($values["company_id"])) {
    if (!empty($_SESSION["company_id"])) {
        $values["company_id"] = (int) $_SESSION["company_id"];
    } else {
        $rs = DB::Query("SELECT id FROM company ORDER BY id LIMIT 1");
        $data = $rs->fetchAssoc();
        if ($data) {
            $values["company_id"] = (int) $data["id"];
        }
    }
}

// Branch fallback
if (empty($values["branch_id"])) {
    if (!empty($_SESSION["branch_id"])) {
        $values["branch_id"] = (int) $_SESSION["branch_id"];
    } else {
        $companyId = (int) $values["company_id"];

        $rs = DB::Query("
            SELECT id
            FROM branch
            WHERE company_id = " . $companyId . "
            ORDER BY is_head_office DESC, id
            LIMIT 1
        ");

        $data = $rs->fetchAssoc();
        if ($data) {
            $values["branch_id"] = (int) $data["id"];
        }
    }
}

// Date
if (empty($values["payment_date"])) {
    $values["payment_date"] = date("Y-m-d");
}

// Currency
if (empty($values["currency_code"])) {
    $values["currency_code"] = "PHP";
}

if (empty($values["exchange_rate"]) || (float) $values["exchange_rate"] <= 0) {
    $values["exchange_rate"] = 1;
}

// Accounting period
if (empty($values["accounting_period_id"])) {
    $companyId = (int) $values["company_id"];
    $paymentDate = db_addslashes($values["payment_date"]);

    $rs = DB::Query("
        SELECT id, period_status
        FROM accounting_period
        WHERE company_id = " . $companyId . "
          AND date_from <= '" . $paymentDate . "'
          AND date_to >= '" . $paymentDate . "'
        ORDER BY date_from DESC
        LIMIT 1
    ");

    $period = $rs->fetchAssoc();

    if (!$period) {
        $message = "No accounting period found for payment date.";
        return false;
    }

    if ($period["period_status"] == "CLOSED") {
        $message = "The accounting period is already closed.";
        return false;
    }

    $values["accounting_period_id"] = (int) $period["id"];
}

// Required customer
if (empty($values["customer_id"])) {
    $message = "Customer is required.";
    return false;
}

// Numeric defaults
$grossAmount = !empty($values["gross_amount"]) ? (float) $values["gross_amount"] : 0;
$withholdingAmount = !empty($values["withholding_amount"]) ? (float) $values["withholding_amount"] : 0;
$bankChargeAmount = !empty($values["bank_charge_amount"]) ? (float) $values["bank_charge_amount"] : 0;

if ($grossAmount <= 0) {
    $message = "Payment amount must be greater than zero.";
    return false;
}

if ($withholdingAmount < 0) {
    $message = "Withholding amount cannot be negative.";
    return false;
}

if ($bankChargeAmount < 0) {
    $message = "Bank charge amount cannot be negative.";
    return false;
}

$netReceivedAmount = round($grossAmount - $withholdingAmount - $bankChargeAmount, 4);

if ($netReceivedAmount < 0) {
    $message = "Net received amount cannot be negative.";
    return false;
}

// Save cleaned amounts
$values["gross_amount"] = $grossAmount;
$values["withholding_amount"] = $withholdingAmount;
$values["bank_charge_amount"] = $bankChargeAmount;
$values["net_received_amount"] = $netReceivedAmount;

// Initial application totals
$values["applied_amount"] = 0;
$values["unapplied_amount"] = $netReceivedAmount;

// Status defaults
if (empty($values["approval_status"])) {
    $values["approval_status"] = "DRAFT";
}

if (empty($values["document_status"])) {
    $values["document_status"] = "DRAFT";
}

if (empty($values["posting_status"])) {
    $values["posting_status"] = "UNPOSTED";
}

// User fallback
if (empty($values["created_by_platform_user_id"])) {
    if (!empty($_SESSION["platform_user_id"])) {
        $values["created_by_platform_user_id"] = (int) $_SESSION["platform_user_id"];
    } else {
        $values["created_by_platform_user_id"] = 0;
    }
}
/* ============================================================
   Period Lock Check - Add
   ============================================================ */

$checkAccountingPeriodId = 0;

if (!empty($values["accounting_period_id"])) {
    $checkAccountingPeriodId = (int)$values["accounting_period_id"];
}

if ($checkAccountingPeriodId > 0) {
    $rsPeriod = DB::Query("
        SELECT period_status
        FROM accounting_period
        WHERE id = " . $checkAccountingPeriodId . "
        LIMIT 1
    ");

    $period = $rsPeriod->fetchAssoc();

    if (!$period) {
        $message = "Accounting period was not found.";
        return false;
    }

    if (strtoupper($period["period_status"]) == "CLOSED") {
        $message = "This accounting period is already closed. You cannot add transactions in this period.";
        return false;
    }
}
return true;
		;
		return true;
	}

	function BeforeEdit( &$values, &$sqlValues, $where, &$oldvalues, &$keys, &$message, $inline, $pageObject ) {
		// BuildLedger Finance - Customer Payment Before Edit

// Posted Customer Payment Lock
if (!empty($oldvalues["posting_status"]) && strtoupper($oldvalues["posting_status"]) == "POSTED") {
    $message = "This customer payment is already posted. You cannot edit it. Use reversal instead.";
    return false;
}

// Period Lock Check - Edit
$checkAccountingPeriodId = 0;

if (!empty($oldvalues["accounting_period_id"])) {
    $checkAccountingPeriodId = (int)$oldvalues["accounting_period_id"];
} elseif (!empty($values["accounting_period_id"])) {
    $checkAccountingPeriodId = (int)$values["accounting_period_id"];
}

if ($checkAccountingPeriodId > 0) {

    $rsPeriod = DB::Query("
        SELECT period_status
        FROM accounting_period
        WHERE id = " . $checkAccountingPeriodId . "
        LIMIT 1
    ");

    $period = $rsPeriod->fetchAssoc();

    if (!$period) {
        $message = "Accounting period was not found.";
        return false;
    }

    if (strtoupper($period["period_status"]) == "CLOSED") {
        $message = "This accounting period is already closed. You cannot edit this customer payment.";
        return false;
    }
}

// Preserve System / Ownership Fields
$values["customer_payment_uuid"] = $oldvalues["customer_payment_uuid"];
$values["company_id"] = $oldvalues["company_id"];

if (!empty($oldvalues["accounting_period_id"])) {
    $values["accounting_period_id"] = $oldvalues["accounting_period_id"];
}

if (!empty($oldvalues["receipt_no"])) {
    $values["receipt_no"] = $oldvalues["receipt_no"];
}

// Required Field Validation
if (empty($values["payment_date"])) {
    $message = "Payment date is required.";
    return false;
}

if (empty($values["customer_id"])) {
    $message = "Customer is required.";
    return false;
}

// Currency Defaults
if (empty($values["currency_code"])) {
    $values["currency_code"] = "PHP";
}

if (empty($values["exchange_rate"]) || (float)$values["exchange_rate"] <= 0) {
    $values["exchange_rate"] = 1;
}

// Numeric Validation and Recalculation
$grossAmount = !empty($values["gross_amount"])
    ? round((float)$values["gross_amount"], 4)
    : 0;

$withholdingAmount = !empty($values["withholding_amount"])
    ? round((float)$values["withholding_amount"], 4)
    : 0;

$bankChargeAmount = !empty($values["bank_charge_amount"])
    ? round((float)$values["bank_charge_amount"], 4)
    : 0;

if ($grossAmount <= 0) {
    $message = "Payment amount must be greater than zero.";
    return false;
}

if ($withholdingAmount < 0) {
    $message = "Withholding amount cannot be negative.";
    return false;
}

if ($bankChargeAmount < 0) {
    $message = "Bank charge amount cannot be negative.";
    return false;
}

$netReceivedAmount = round($grossAmount - $withholdingAmount - $bankChargeAmount, 4);

if ($netReceivedAmount < 0) {
    $message = "Net received amount cannot be negative.";
    return false;
}

// Existing Applied Amount Check
$customerPaymentId = 0;

if (!empty($keys["id"])) {
    $customerPaymentId = (int)$keys["id"];
} elseif (!empty($oldvalues["id"])) {
    $customerPaymentId = (int)$oldvalues["id"];
}

$appliedAmount = 0;

if ($customerPaymentId > 0) {

    $rsApplied = DB::Query("
        SELECT COALESCE(SUM(applied_amount), 0) AS applied_amount
        FROM customer_payment_application
        WHERE customer_payment_id = " . $customerPaymentId
    );

    $applied = $rsApplied->fetchAssoc();

    if ($applied) {
        $appliedAmount = round((float)$applied["applied_amount"], 4);
    }
}

if ($appliedAmount > $netReceivedAmount) {
    $message = "Existing applied amount is greater than the new net received amount.";
    return false;
}

// Save Computed Amounts
$values["gross_amount"] = $grossAmount;
$values["withholding_amount"] = $withholdingAmount;
$values["bank_charge_amount"] = $bankChargeAmount;
$values["net_received_amount"] = $netReceivedAmount;
$values["applied_amount"] = $appliedAmount;
$values["unapplied_amount"] = round($netReceivedAmount - $appliedAmount, 4);

// Preserve Status Fields if Empty
if (empty($values["approval_status"])) {
    $values["approval_status"] = $oldvalues["approval_status"];
}

if (empty($values["document_status"])) {
    $values["document_status"] = $oldvalues["document_status"];
}

if (empty($values["posting_status"])) {
    $values["posting_status"] = $oldvalues["posting_status"];
}

return true;
		;
		return true;
	}

	function AfterAdd( &$values, &$keys, $inline, $pageObject ) {
		// BuildLedger Finance - Customer Payment After Add
// Generate simple receipt number.

$customerPaymentId = 0;

if (!empty($keys["id"])) {
    $customerPaymentId = (int) $keys["id"];
} elseif (!empty($values["id"])) {
    $customerPaymentId = (int) $values["id"];
}

if ($customerPaymentId > 0) {

    $prefix = "OR-" . date("Ym") . "-";
    $receiptNo = $prefix . str_pad($customerPaymentId, 6, "0", STR_PAD_LEFT);

    DB::Exec("
        UPDATE customer_payment
        SET receipt_no = '" . db_addslashes($receiptNo) . "'
        WHERE id = " . $customerPaymentId . "
          AND (receipt_no IS NULL OR receipt_no = '')
        LIMIT 1
    ");
}
if (!$inline && !empty($keys["id"])) {
    header("Location: customer_payment_edit.php?editid1=" . $keys["id"]);
    exit();
}
		;
		
	}

	function BeforeDelete( $where, &$deleted_values, &$message, $pageObject ) {
		/* ============================================================
   BuildLedger Finance - Customer Payment Before Delete
   Prevent delete if posted or period is closed
   ============================================================ */

$customerPaymentId = 0;

if (!empty($deleted_values["id"])) {
    $customerPaymentId = (int)$deleted_values["id"];
}

if ($customerPaymentId <= 0) {
    $message = "Customer payment ID is missing.";
    return false;
}

/* ============================================================
   Check customer payment header
   ============================================================ */

$rsPayment = DB::Query("
    SELECT
        id,
        accounting_period_id,
        posting_status
    FROM customer_payment
    WHERE id = " . $customerPaymentId . "
    LIMIT 1
");

$payment = $rsPayment->fetchAssoc();

if (!$payment) {
    $message = "Customer payment was not found.";
    return false;
}

/* ============================================================
   Block deleting posted customer payment
   ============================================================ */

if (strtoupper($payment["posting_status"]) == "POSTED") {
    $message = "This customer payment is already posted. You cannot delete it. Use reversal instead.";
    return false;
}

/* ============================================================
   Block deleting customer payment in closed period
   ============================================================ */

$accountingPeriodId = (int)$payment["accounting_period_id"];

if ($accountingPeriodId > 0) {

    $rsPeriod = DB::Query("
        SELECT period_status
        FROM accounting_period
        WHERE id = " . $accountingPeriodId . "
        LIMIT 1
    ");

    $period = $rsPeriod->fetchAssoc();

    if (!$period) {
        $message = "Accounting period was not found.";
        return false;
    }

    if (strtoupper($period["period_status"]) == "CLOSED") {
        $message = "This accounting period is already closed. You cannot delete this customer payment.";
        return false;
    }
}

return true;
		;
		return true;
	}
	public function default_withholding_amount_efedit(  ) {
	$defaultValue = 0;
return $defaultValue;
}

public function default_bank_charge_amount_efedit(  ) {
	$defaultValue = 0;
return $defaultValue;
}

public function default_net_received_amount_efedit(  ) {
	$defaultValue = 0;
return $defaultValue;
}

public function default_applied_amount_efedit(  ) {
	$defaultValue = 0;
return $defaultValue;
}

public function default_unapplied_amount_efedit(  ) {
	$defaultValue = 0;
return $defaultValue;
}	

}


?>