<?php
class eventclass_supplier_bill  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(
		'document_type' => array(
			'edit' => true 
		),
		'subtotal_amount' => array(
			'edit' => true 
		),
		'discount_amount' => array(
			'edit' => true 
		),
		'input_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 - Supplier Bill Before Add

// UUID
if (empty($values["supplier_bill_uuid"])) {
    $rs = DB::Query("SELECT UUID() AS uuid");
    $data = $rs->fetchAssoc();
    $values["supplier_bill_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"];
        }
    }
}

// Document type
if (empty($values["document_type"])) {
    $values["document_type"] = "SUPPLIER_BILL";
}

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

if (empty($values["due_date"])) {
    $values["due_date"] = $values["bill_date"];
}

// Supplier snapshot
if (!empty($values["supplier_id"])) {
    $supplierId = (int) $values["supplier_id"];

    $rsSupplier = DB::Query("
        SELECT
            registered_name,
            tin,
            bir_branch_code
        FROM supplier
        WHERE id = " . $supplierId . "
        LIMIT 1
    ");

    $supplier = $rsSupplier->fetchAssoc();

    if ($supplier) {
        if (empty($values["supplier_name_snapshot"])) {
            $values["supplier_name_snapshot"] = $supplier["registered_name"];
        }

        if (empty($values["supplier_tin_snapshot"])) {
            $values["supplier_tin_snapshot"] = $supplier["tin"];
        }
    }
}

// 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"];
    $billDate = db_addslashes($values["bill_date"]);

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

    $period = $rs->fetchAssoc();

    if (!$period) {
        $message = "No accounting period found for bill 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";
}

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

// Safe initial totals
$totalFields = array(
    "subtotal_amount",
    "discount_amount",
    "input_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;
    }
}
return true;
		;
		return true;
	}

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

/* ============================================================
   Posted Supplier Bill Lock
   ============================================================ */

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

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

$values["supplier_bill_uuid"] = $oldvalues["supplier_bill_uuid"];
$values["company_id"] = $oldvalues["company_id"];

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

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

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

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

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

if (empty($values["due_date"])) {
    $values["due_date"] = $values["bill_date"];
}

/* ============================================================
   Supplier Snapshot
   ============================================================ */

if (!empty($values["supplier_id"])) {

    $supplierId = (int)$values["supplier_id"];

    $rsSupplier = DB::Query("
        SELECT
            registered_name,
            tin,
            bir_branch_code
        FROM supplier
        WHERE id = " . $supplierId . "
        LIMIT 1
    ");

    $supplier = $rsSupplier->fetchAssoc();

    if ($supplier) {
        $values["supplier_name_snapshot"] = $supplier["registered_name"];
        $values["supplier_tin_snapshot"] = $supplier["tin"];
    }
}

/* ============================================================
   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 Supplier Bill Totals
   Do not let the Supplier Bill Edit form overwrite totals
   computed from supplier_bill_detail.
   Safe even if some fields are not present.
   ============================================================ */

unset($values["subtotal_amount"]);
unset($values["discount_amount"]);
unset($values["vatable_amount"]);
unset($values["vat_exempt_amount"]);
unset($values["zero_rated_amount"]);
unset($values["vat_amount"]);
unset($values["input_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 - Supplier Bill After Add
// Generate simple Supplier Bill number.

$supplierBillId = 0;

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

if ($supplierBillId > 0) {

    $prefix = "AP-" . date("Ym") . "-";
    $billNo = $prefix . str_pad($supplierBillId, 6, "0", STR_PAD_LEFT);

    DB::Exec("
        UPDATE supplier_bill
        SET bill_no = '" . db_addslashes($billNo) . "'
        WHERE id = " . $supplierBillId . "
          AND (bill_no IS NULL OR bill_no = '')
        LIMIT 1
    ");
}
if (!$inline && !empty($keys["id"])) {
    header("Location: supplier_bill_edit.php?editid1=" . $keys["id"]);
    exit();
}
		;
		
	}

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

$supplierBillId = 0;

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

if ($supplierBillId <= 0) {
    $message = "Supplier bill ID is missing.";
    return false;
}

/* ============================================================
   Check supplier bill header
   ============================================================ */

$rsBill = DB::Query("
    SELECT
        id,
        accounting_period_id,
        posting_status
    FROM supplier_bill
    WHERE id = " . $supplierBillId . "
    LIMIT 1
");

$bill = $rsBill->fetchAssoc();

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

/* ============================================================
   Block deleting posted supplier bill
   ============================================================ */

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

/* ============================================================
   Block deleting supplier bill in closed period
   ============================================================ */

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

return true;
		;
		return true;
	}
	public function default_document_type_efedit(  ) {
	$defaultValue = SUPPLIER_BILL;
return $defaultValue;
}

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

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

public function default_input_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;
}	

}


?>