<?php
class eventclass_accounting_period  extends TableEventsBase {
	
	function init() {
		$this->events = array(
	'BeforeEdit' => true,
	'BeforeDelete' => true 
);
		$this->fieldValues = array(
	'filterLimit' => array(
		 
	),
	'mapIcon' => array(
		 
	),
	'viewCustom' => array(
		 
	),
	'lookupWhere' => array(
		 
	),
	'viewFileText' => array(
		 
	),
	'defaultValue' => array(
		 
	),
	'autoUpdateValue' => array(
		 
	),
	'uploadFolder' => array(
		 
	),
	'viewPluginInit' => array(
		 
	),
	'editPluginInit' => array(
		 
	) 
);
			}
		function BeforeEdit( &$values, &$sqlValues, $where, &$oldvalues, &$keys, &$message, $inline, $pageObject ) {
		// BuildLedger Finance - Accounting Period Before Edit

$periodId = 0;

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

if ($periodId <= 0) {
    $message = "Accounting period ID is missing.";
    return false;
}

// Do not allow direct editing of closed periods.
// Use Reopen Period button first.
if (!empty($oldvalues["period_status"]) && strtoupper($oldvalues["period_status"]) == "CLOSED") {
    $message = "This accounting period is already closed. Reopen the closed. Re period first before editing.";
    return false;
}

// Required fields
if (empty($values["fiscal_year_id"])) {
    $message = "Fiscal year is required.";
    return false;
}

if (empty($values["period_no"])) {
    $message = "Period number is required.";
    return false;
}

if (empty($values["period_name"])) {
    $message = "Period name is required.";
    return false;
}

if (empty($values["date_from"])) {
    $message = "Date From is required.";
    return false;
}

if (empty($values["date_to"])) {
    $message = "Date To is required.";
    return false;
}

// Date validation
$dateFrom = strtotime($values["date_from"]);
$dateTo = strtotime($values["date_to"]);

if ($dateFrom === false || $dateTo === false) {
    $message = "Invalid accounting period date.";
    return false;
}

if ($dateFrom > $dateTo) {
    $message = "Date From cannot be later than Date To.";
    return false;
}

// Do not allow manual status closing/reopening from Edit page.
// Closing/Reopening should only be done using the buttons.
$values["period_status"] = $oldvalues["period_status"];

// Preserve close/reopen audit fields from manual editing
$values["closed_at"] = $oldvalues["closed_at"];
$values["closed_by_platform_user_id"] = $oldvalues["closed_by_platform_user_id"];
$values["soft_closed_at"] = $oldvalues["soft_closed_at"];
$values["reopened_until"] = $oldvalues["reopened_until"];
$values["reopen_reason"] = $oldvalues["reopen_reason"];

// Optional: prevent changing dates if transactions already exist in this period
$dateChanged =
    $values["date_from"] != $oldvalues["date_from"] ||
    $values["date_to"] != $oldvalues["date_to"];

if ($dateChanged) {

    $transactionCount = 0;

    $tables = array(
        "sales",
        "supplier_bill",
        "customer_payment",
        "supplier_payment",
        "journal_entry"
    );

    foreach ($tables as $tableName) {

        $rsCount = DB::Query("
            SELECT COUNT(*) AS cnt
            FROM " . $tableName . "
            WHERE accounting_period_id = " . $periodId
        );

        $countData = $rsCount->fetchAssoc();

        if ($countData) {
            $transactionCount += (int)$countData["cnt"];
        }
    }

    if ($transactionCount > 0) {
        $message = "This accounting period already has transactions. You cannot change its date range.";
        return false;
    }
}

return true;
		;
		return true;
	}

	function BeforeDelete( $where, &$deleted_values, &$message, $pageObject ) {
		// BuildLedger Finance - Accounting Period Before Delete

$periodId = 0;

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

if ($periodId <= 0) {
    $message = "Accounting period ID is missing.";
    return false;
}

// Load period
$rsPeriod = DB::Query("
    SELECT
        id,
        period_name,
        period_status
    FROM accounting_period
    WHERE id = " . $periodId . "
    LIMIT 1
");

$period = $rsPeriod->fetchAssoc();

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

// Do not delete closed periods
if (strtoupper($period["period_status"]) == "CLOSED") {
    $message = "This accounting period is already closed. You cannot delete it.";
    return false;
}

// Check if transactions exist under this period
$usedList = array();

$rsSales = DB::Query("
    SELECT COUNT(*) AS cnt
    FROM sales
    WHERE accounting_period_id = " . $periodId
);
$sales = $rsSales->fetchAssoc();

if ($sales && (int)$sales["cnt"] > 0) {
    $usedList[] = "Sales Invoice: " . (int)$sales["cnt"];
}

$rsSupplierBill = DB::Query("
    SELECT COUNT(*) AS cnt
    FROM supplier_bill
    WHERE accounting_period_id = " . $periodId
);
$supplierBill = $rsSupplierBill->fetchAssoc();

if ($supplierBill && (int)$supplierBill["cnt"] > 0) {
    $usedList[] = "Supplier Bill: " . (int)$supplierBill["cnt"];
}

$rsCustomerPayment = DB::Query("
    SELECT COUNT(*) AS cnt
    FROM customer_payment
    WHERE accounting_period_id = " . $periodId
);
$customerPayment = $rsCustomerPayment->fetchAssoc();

if ($customerPayment && (int)$customerPayment["cnt"] > 0) {
    $usedList[] = "Customer Payment: " . (int)$customerPayment["cnt"];
}

$rsSupplierPayment = DB::Query("
    SELECT COUNT(*) AS cnt
    FROM supplier_payment
    WHERE accounting_period_id = " . $periodId
);
$supplierPayment = $rsSupplierPayment->fetchAssoc();

if ($supplierPayment && (int)$supplierPayment["cnt"] > 0) {
    $usedList[] = "Supplier Payment: " . (int)$supplierPayment["cnt"];
}

$rsJournal = DB::Query("
    SELECT COUNT(*) AS cnt
    FROM journal_entry
    WHERE accounting_period_id = " . $periodId
);
$journal = $rsJournal->fetchAssoc();

if ($journal && (int)$journal["cnt"] > 0) {
    $usedList[] = "Journal Entry: " . (int)$journal["cnt"];
}

if (count($usedList) > 0) {
    $message =
        "You cannot delete this accounting period because transactions already exist under it:\n\n" .
        implode("\n", $usedList);

    return false;
}

return true;
		;
		return true;
	}
		

}


?>