<?php
$searchdisabled = '';
$adddisabled    = '';
$editdisabled   = '';
$savedisabled   = 'none';
$deletedisabled = '';
$exitdisabled   = '';
$printdisabled  = '';
$canceldisabled = 'none';
$pdisabled      = '';
$ndisabled      = '';
$pdisabled1     = '';
$ndisabled1     = '';
$prevvouch      = 0;
$nextvouch      = 0;
$qvouch         = 0;
$flag           = '';

if (isset($_GET["mode"])) {
    $mode = $_GET["mode"];

    if ($mode == "true") {
        $addflag = 1;
        // Use the global MAX (no $keycond) — `accode`/`vouchno` is one shared
        // sequence across all groups/types, so the next number must not
        // collide with rows belonging to other groups (e.g. fixed accmast accounts).
        $gen1    = mysqli_query($conn, "SELECT MAX(`$keyfld`) AS maxcode FROM `$maindb` LIMIT 1") or die(mysqli_error($conn));
        $vvouch  = mysqli_fetch_assoc($gen1);
        $qvouch  = ($vvouch["maxcode"] > 0) ? $vvouch["maxcode"] + 1 : 1;

        // accmast codes 1-50 are reserved for fixed/system accounts.
        // Any new master created through the software must start above 50.
        if ($maindb == "accmast" && $qvouch <= 50) {
            $qvouch = 51;
        }

        $flag    = "Add";

        $searchdisabled = 'none';
        $adddisabled    = 'none';
        $editdisabled   = 'none';
        $deletedisabled = 'none';
        $exitdisabled   = 'none';
        $printdisabled  = 'none';
        $pdisabled      = 'none';
        $ndisabled      = 'none';
        $savedisabled   = '';
        $canceldisabled = '';

    } elseif ($mode == "last") {
        $addflag     = 2;
        $mgetlastrec = mysqli_query($conn, "SELECT * FROM `$maindb` WHERE `$keyfld` != '' $keycond ORDER BY `$keyfld` DESC LIMIT 1") or die(mysqli_error($conn));
        $mgetvouchno = mysqli_fetch_array($mgetlastrec);
        $qvouch      = isset($mgetvouchno[$keyfld]) ? $mgetvouchno[$keyfld] : 0;

        $savedisabled   = 'none';
        $canceldisabled = 'none';

    } elseif ($mode == "edit") {
        $addflag = 0;
        $qvouch  = isset($_GET[$keyfld]) ? (int)$_GET[$keyfld] : 0;
        $flag    = "Edit";

        $savedisabled   = 'none';
        $canceldisabled = 'none';
    }
}

if (isset($_GET["delete"])) {
    $qvouch = isset($_GET[$keyfld]) ? (int)$_GET[$keyfld] : 0;
}

// ── Role-based UI restrictions ────────────────────────────────────────────
// Admin (1): full access. Manager (2): can edit, cannot delete.
// Staff/Salesman (3): cannot edit or delete.
$_ut = isset($_SESSION["usertype_".$dbname]) ? (int)$_SESSION["usertype_".$dbname] : 0;
if ($_ut === 3) {
    $deletedisabled = 'none';
    $editdisabled   = 'none';
} elseif ($_ut === 2) {
    $deletedisabled = 'none';
}
// ── Expose agentcode for salesman filtering ───────────────────────────────
$agentcode = (int)($_SESSION["agentcode_".$dbname] ?? 0);
