<?php
// ── Per-module access control for Staff (usertype=3) accounts ─────────────
// The permission checkboxes on profile.php save a Y/N flag per module onto
// `passmain`. This is the enforcement side: any Staff (salesman) account
// gets blocked from a module page unless their flag for it is 'Y'.
// Admins (usertype=1) and Supervisors (usertype=2) are never restricted here.
$_ut = (int)($_SESSION["usertype_" . $dbname] ?? 0);

if ($_ut === 3) {
    // Must match the permission column keys used in profile.php's $permGroups.
    $_permCols = [
        'customer','supplier','agent','shipper','cha','godown','brand','product','expense',
        'purchexpense','bank','cash',
        'saleorder','dispatchalert','sale','salegst','salereturn',
        'purchentry','purchreturn','purchaseexport','inward','outward','damage','transfer','stockprod',
        'bankrecp','bankpay','cashrecp','cashpay','discountgiven','discounttaken','contra','jv',
        'ledger','payablerep','receivable','openbal',
        'salereg','salereturnreg','salegstreg','saleorderreg',
        'purreg','purchreturnreg','purchaseimportreg',
        'inwreg','otwreg','dmgreg','transferreg','bankreg','cashreg','contrareg','jvbook',
        'salesmanperf','custleading','custaging',
    ];
    $_permCol = basename($_SERVER['SCRIPT_NAME'], '.php');

    if (in_array($_permCol, $_permCols, true)) {
        mysqli_select_db($conn, $dbname);

        // Defensive: guarantee the column exists even if profile.php has
        // never been opened yet on this install (same self-healing pattern
        // used throughout this app), so a missing column never gets
        // misread as "no access".
        $_chk = mysqli_query($conn, "SHOW COLUMNS FROM `passmain` LIKE '$_permCol'");
        if ($_chk && mysqli_num_rows($_chk) == 0) {
            mysqli_query($conn, "ALTER TABLE `passmain` ADD COLUMN `$_permCol` VARCHAR(1) NOT NULL DEFAULT ''");
        }

        $_loguser = $_SESSION["username_" . $dbname] ?? '';
        $_prow = mysqli_fetch_assoc(mysqli_query($conn,
            "SELECT `$_permCol` AS perm FROM `passmain` WHERE `user`='" . mysqli_real_escape_string($conn, $_loguser) . "'"));

        if (!$_prow || $_prow['perm'] !== 'Y') {
            require(__DIR__ . "/access_denied.php");
            exit;
        }
    }
}
