<?php
class eventclass_sales  extends TableEventsBase {
	
	function init() {
		$this->events = array(
	'BeforeAdd' => true,
	'BeforeEdit' => true,
	'AfterAdd' => true,
	'BeforeDelete' => true,
	'OnPageLoad' => true,
	'AfterEdit' => true 
);
		$this->fieldValues = array(
	'filterLimit' => array(
		 
	),
	'mapIcon' => array(
		 
	),
	'viewCustom' => array(
		 
	),
	'lookupWhere' => array(
		 
	),
	'viewFileText' => array(
		 
	),
	'defaultValue' => array(
		'transaction_type' => array(
			'edit' => true 
		),
		'commercial_discount_amount' => array(
			'edit' => true 
		),
		'statutory_discount_amount' => array(
			'edit' => true 
		),
		'vat_amount' => array(
			'edit' => true 
		),
		'withholding_amount' => array(
			'edit' => true 
		),
		'grand_total_amount' => array(
			'edit' => true 
		) 
	),
	'autoUpdateValue' => array(
		 
	),
	'uploadFolder' => array(
		 
	),
	'viewPluginInit' => array(
		 
	),
	'editPluginInit' => array(
		 
	) 
);
			}
		function BeforeAdd( &$values, &$sqlValues, &$message, $inline, $pageObject ) {
		// BuildLedger Finance - Sales Before Add

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

// Company fallback.
// Later this should strictly come from the selected tenant/company session.
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"];
        }
    }
}

// Transaction type
if (empty($values["transaction_type"])) {
    $values["transaction_type"] = "SALES_INVOICE";
}

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

if (empty($values["due_date"])) {
    $terms = !empty($values["payment_terms_days"])
        ? (int) $values["payment_terms_days"]
        : 0;

    $values["due_date"] = date(
        "Y-m-d",
        strtotime($values["transaction_date"] . " +" . $terms . " days")
    );
}

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

if (empty($values["base_currency_code"])) {
    $values["base_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"];
    $txnDate = db_addslashes($values["transaction_date"]);

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

    $period = $rs->fetchAssoc();

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

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

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

// 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";
}

if (empty($values["eis_status"])) {
    $values["eis_status"] = "NOT_REQUIRED";
}

// User
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;
    }
}

// Safe initial totals
$totalFields = array(
    "subtotal_amount",
    "commercial_discount_amount",
    "statutory_discount_amount",
    "vatable_amount",
    "vat_exempt_amount",
    "zero_rated_amount",
    "vat_amount",
    "withholding_amount",
    "grand_total_amount",
    "base_grand_total_amount"
);

foreach ($totalFields as $field) {
    if (!isset($values[$field]) || $values[$field] === "" || $values[$field] === null) {
        $values[$field] = 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;
    }
}

/* ============================================================
   Protect Auto-Computed Sales Totals on Add
   Detail lines should control the invoice totals.
   ============================================================ */

unset($values["subtotal_amount"]);
unset($values["commercial_discount_amount"]);
unset($values["statutory_discount_amount"]);
unset($values["vatable_amount"]);
unset($values["vat_exempt_amount"]);
unset($values["zero_rated_amount"]);
unset($values["vat_amount"]);
unset($values["withholding_amount"]);
unset($values["grand_total_amount"]);
unset($values["base_grand_total_amount"]);

return true;
		;
		return true;
	}

	function BeforeEdit( &$values, &$sqlValues, $where, &$oldvalues, &$keys, &$message, $inline, $pageObject ) {
		/* ============================================================
   BuildLedger Finance - Sales Before Edit
   Prevent editing posted sales invoices or closed-period sales
   ============================================================ */

/* ============================================================
   Posted Sales Invoice Lock
   ============================================================ */

if (!empty($oldvalues["posting_status"]) && strtoupper($oldvalues["posting_status"]) == "POSTED") {
    $message = "This sales invoice 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 sales invoice.";
        return false;
    }
}

/* ============================================================
   Preserve System / Ownership Fields
   ============================================================ */

$values["sales_uuid"] = $oldvalues["sales_uuid"];
$values["company_id"] = $oldvalues["company_id"];
$values["accounting_period_id"] = $oldvalues["accounting_period_id"];

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

/* ============================================================
   Required Date Validation
   ============================================================ */

if (empty($values["transaction_date"])) {
    $message = "Transaction date is required.";
    return false;
}

/* ============================================================
   Auto Due Date
   ============================================================ */

if (empty($values["due_date"])) {

    $terms = !empty($values["payment_terms_days"])
        ? (int)$values["payment_terms_days"]
        : 0;

    $values["due_date"] = date(
        "Y-m-d",
        strtotime($values["transaction_date"] . " +" . $terms . " days")
    );
}

/* ============================================================
   Currency Defaults
   ============================================================ */

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

if (empty($values["base_currency_code"])) {
    $values["base_currency_code"] = "PHP";
}

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

/* ============================================================
   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"];
}

/* ============================================================
   Protect Auto-Computed Sales Totals
   Do not let the Sales Edit form overwrite totals computed
   from sales_detail.
   ============================================================ */

unset($values["subtotal_amount"]);
unset($values["commercial_discount_amount"]);
unset($values["statutory_discount_amount"]);
unset($values["vatable_amount"]);
unset($values["vat_exempt_amount"]);
unset($values["zero_rated_amount"]);
unset($values["vat_amount"]);
unset($values["withholding_amount"]);
unset($values["grand_total_amount"]);
unset($values["base_grand_total_amount"]);

return true;
		;
		return true;
	}

	function AfterAdd( &$values, &$keys, $inline, $pageObject ) {
		// BuildLedger Finance - Sales After Add
// Generate simple Sales Invoice document number after record is created.

$salesId = 0;

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

if ($salesId > 0) {

    $prefix = "SI-" . date("Ym") . "-";
    $documentNo = $prefix . str_pad($salesId, 6, "0", STR_PAD_LEFT);

    DB::Exec("
        UPDATE sales
        SET document_no = '" . db_addslashes($documentNo) . "',
            updated_at = CURRENT_TIMESTAMP(6)
        WHERE id = " . $salesId . "
          AND (document_no IS NULL OR document_no = '')
        LIMIT 1
    ");
}
if (!$inline && !empty($keys["id"])) {
    header("Location: sales_edit.php?editid1=" . $keys["id"]);
    exit();
}

header("Location: sales_edit.php?editid1=" . $keys["id"]);
exit();
		;
		
	}

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

$salesId = 0;

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

if ($salesId <= 0) {
    $message = "Sales invoice ID is missing.";
    return false;
}

/* ============================================================
   Check sales invoice header
   ============================================================ */

$rsSales = DB::Query("
    SELECT
        id,
        accounting_period_id,
        posting_status
    FROM sales
    WHERE id = " . $salesId . "
    LIMIT 1
");

$sales = $rsSales->fetchAssoc();

if (!$sales) {
    $message = "Sales invoice was not found.";
    return false;
}

/* ============================================================
   Block deleting posted sales invoice
   ============================================================ */

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

/* ============================================================
   Block deleting sales invoice in closed period
   ============================================================ */

$accountingPeriodId = (int)$sales["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 sales invoice.";
        return false;
    }
}

return true;
		;
		return true;
	}

	function AfterEdit( &$values, $where, &$oldvalues, &$keys, $inline, $pageObject ) {
		/* ============================================================
   Recalculate Sales Totals After Header Save
   This fixes stale invoice summary after saving the Sales header.
   ============================================================ */

$salesId = 0;

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

if ($salesId > 0) {
    DB::Exec("CALL sp_recalc_sales_totals(" . $salesId . ")");
}


		;
		
	}
	public function default_transaction_type_efedit(  ) {
	$defaultValue = SALES_INVOICE;
return $defaultValue;
}

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

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

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

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

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

}


?>