function save_bal()
{
    # Get Owners Equity Sub Headings
    $oesubRslt = undget("core", "*", "bal_sheet", "type", "OESUB' AND div = '11111111");
    $sheet = "<center>\n\t<h3> Balance sheet for period : " . PRD_NAME . "<br><br>Date: " . date("d M Y") . " </h3>\n\t<table cellpadding='3' cellspacing='0' border=1 bordercolor='#000000' width=750>\n\t<tr><th colspan=3>Owners Equity</th></tr>";
    # get accounts
    $oebal = 0;
    // OE Balance
    while ($oesub = pg_fetch_array($oesubRslt)) {
        $sheet .= "<tr><td colspan=3><b>{$oesub['value']}<b></td></tr>";
        $sql = "SELECT * FROM bal_sheet WHERE type ='OEACC' AND ref = {$oesub['ref']} AND div = 11111111";
        $accRslt = db_exec($sql) or errDie("Unable to retrieve balance sheet settings from the Database.", SELF);
        # get account BAlances
        while ($acc = pg_fetch_array($accRslt)) {
            list($topacc, $accnum) = explode("/", $acc['value']);
            # Get balance
            $query = "SELECT sum(credit) as credit,sum(debit) as debit FROM trial_bal WHERE topacc = '{$topacc}' AND accnum = '{$accnum}'";
            $balRslt = db_exec($query) or errDie("Unable to retrieve Account Balances from the Database.", SELF);
            $accbal = pg_fetch_array($balRslt);
            $balance = $accbal['credit'] - $accbal['debit'];
            $oebal += $balance;
            $balacc = getaccnum($acc['value']);
            $sheet .= "<tr><td><blockquote><li>{$balacc['accname']}</td><td>" . CUR . " {$balance}</td><td><br></td></tr>";
        }
    }
    $oebal = sprint($oebal);
    # print Net Income and OE Balance on last column
    $netincome = getNetIncome();
    $oebal += $netincome;
    $sheet .= "<tr><td>&nbsp<b>Net Income</b></td><td>" . CUR . " {$netincome}</td><td><br></td></tr>";
    $sheet .= "<tr><td colspan=2><b>Total</b></td><td><b>" . CUR . " {$oebal}</b></td></tr>";
    # Get Assets Sub Headings
    $abal = 0;
    // Assets Balance
    $asssubRslt = undget("core", "*", "bal_sheet", "type", "ASSSUB' AND div = '11111111");
    $sheet .= "<tr><th colspan=3>Assets</th></tr>";
    # get accounts
    while ($asssub = pg_fetch_array($asssubRslt)) {
        $sheet .= "<tr><td colspan=3><b>{$asssub['value']}<b></td></tr>";
        $sql = "SELECT * FROM bal_sheet WHERE type ='ASSACC' AND ref = {$asssub['ref']} AND div = 11111111";
        $accRslt = db_exec($sql) or errDie("Unable to retrieve balance sheet settings from the Database.", SELF);
        # get account BAlances
        while ($acc = pg_fetch_array($accRslt)) {
            list($topacc, $accnum) = explode("/", $acc['value']);
            # Get Balance
            $query = "SELECT sum(credit) as credit,sum(debit) as debit FROM trial_bal WHERE topacc = '{$topacc}' AND accnum = '{$accnum}'";
            $balRslt = db_exec($query) or errDie("Unable to retrieve Account Balances from the Database.", SELF);
            $accbal = pg_fetch_array($balRslt);
            $balance = $accbal['debit'] - $accbal['credit'];
            // calc Balance
            $abal += $balance;
            $balacc = getaccnum($acc['value']);
            $sheet .= "<tr><td><blockquote><li>{$acc['value']} - {$balacc['accname']}</td><td>" . CUR . " {$balance}</td><td><br></td></tr>";
        }
    }
    $abal = sprint($abal);
    # print assets balance on last column
    $sheet .= "<tr><td colspan=2><b>Total</b></td><td><b>" . CUR . " {$abal}</b></td></tr>\n\t</table><br>";
    $output = base64_encode($sheet);
    core_connect();
    $sql = "INSERT INTO save_bal_sheet(gendate, output, div) VALUES('" . date("Y-m-d") . "', '{$output}', '" . USER_DIV . "')";
    $Rs = db_exec($sql) or errdie("Unable to save the Balance Sheet.");
    $sheet .= "\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=25%>\n\t<tr><th>Quick Links</th></tr>\n\t<tr class=datacell><td align=center><a target=_blank href='../core/acc-new2.php'>Add account (New Window)</a></td></tr>\n\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $sheet;
}
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # Validate input
    require_lib("validate");
    $v = new validate();
    # Validate array input
    foreach ($oesub as $key => $sub) {
        $v->isOk($sub, "string", 0, 255, "Invalid Owners Equity Sub Heading number {$key}.");
    }
    if (isset($asssub)) {
        foreach ($asssub as $key => $sub) {
            $v->isOk($sub, "string", 0, 255, "Invalid Assets Sub Heading number {$key}.");
        }
    }
    foreach ($accno as $key => $accn) {
        list($topacc, $accnum) = explode("/", $accn);
        $v->isOk($topacc, "num", 3, 3, "Invalid account number.");
        $v->isOk($accnum, "num", 3, 3, "Invalid account number.");
    }
    foreach ($heads as $key => $head) {
        $v->isOk($head, "string", 1, 10, "Invalid Sub Heading Selection.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>" . $e["msg"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # First Empty the Table (Warning Was Given)
    core_connect();
    $sql = "DELETE FROM bal_sheet WHERE div = '" . USER_DIV . "'";
    $emptyRslt = db_exec($sql) or errDie("Unable to clean the balance sheet settings table before writing.", SELF);
    // Shooo !!!! Its hot in here, deal with them b***hies
    # Write Owner's Equity sub headigns and their accounts
    foreach ($oesub as $oref => $sub) {
        $query = "INSERT INTO bal_sheet(type, ref, value, div) VALUES('OESUB', '{$oref}', '{$sub}', '" . USER_DIV . "')";
        $bsRslt = db_exec($query) or errDie("Unable to insert Balance Sheet settings to database", SELF);
        $subaccs = getaccs($oref, $heads, 'o', $accno);
        foreach ($subaccs as $kkey => $subacc) {
            $acc = getaccnum($subacc);
            $query = "INSERT INTO bal_sheet(type, ref, value, div) VALUES('OEACC','{$oref}','{$acc['accid']}', '" . USER_DIV . "')";
            $accRslt = db_exec($query) or errDie("Unable to insert Balance sheet settings to Cubit.", SELF);
        }
    }
    if (isset($asssub)) {
        # Write Assets sub headings and their Accounts
        foreach ($asssub as $aref => $sub) {
            $query = "INSERT INTO bal_sheet(type, ref, value, div) VALUES('ASSSUB', '{$aref}', '{$sub}', '" . USER_DIV . "')";
            $bsRslt = db_exec($query) or errDie("Unable to insert Balance Sheet settings to database", SELF);
            $subaccs = getaccs($aref, $heads, 'a', $accno);
            foreach ($subaccs as $kkey => $subacc) {
                $acc = getaccnum($subacc);
                $query = "INSERT INTO bal_sheet(type, ref, value, div) VALUES('ASSACC','{$aref}','{$acc['accid']}', '" . USER_DIV . "')";
                $accRslt = db_exec($query) or errDie("Unable to insert Balance sheet settings to Cubit.", SELF);
            }
        }
    }
    // Status Report
    $write = "\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='50%'>\n\t\t<tr><th>Balance Sheet Settings</th></tr>\n\t\t<tr class=datacell><td>The Selected Balance Sheet Settings were successfully added to Cubit.</td></tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=25%>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function confirm($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # Validate input
    require_lib("validate");
    $v = new validate();
    if (!isset($asssub) || !isset($oesub)) {
        $v->isOk("##", "num", 0, 0, "Error : Please set at least one Owners Equity and one Assets Sub Heading.");
    } else {
        # Validate array input
        foreach ($oesub as $key => $sub) {
            $v->isOk($sub, "string", 0, 255, "Invalid Owners Equity Sub Heading number {$key}.");
        }
        foreach ($asssub as $key => $sub) {
            $v->isOk($sub, "string", 0, 255, "Invalid Assets Sub Heading number {$key}.");
        }
        foreach ($accno as $key => $accn) {
            list($topacc, $accnum) = explode("/", $accn);
            $v->isOk($topacc, "num", 3, 3, "Invalid account number.");
            $v->isOk($accnum, "num", 3, 3, "Invalid account number.");
        }
        foreach ($heads as $key => $head) {
            $v->isOk($head, "string", 1, 10, "Invalid Sub Heading Selection.");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>" . $e["msg"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # hide subs
    $hide = "";
    foreach ($oesub as $key => $sub) {
        $hide .= "<input type=hidden name=oesub[] value='{$sub}'>";
    }
    if (isset($asssub)) {
        foreach ($asssub as $key => $sub) {
            $hide .= "<input type=hidden name=asssub[] value='{$sub}'>";
        }
    }
    # hide account numbers
    foreach ($accno as $key => $accn) {
        $hide .= "<input type=hidden name=accno[] value='{$accn}'>";
    }
    # hide account headings
    foreach ($heads as $key => $head) {
        $hide .= "<input type=hidden name=heads[] value='{$head}'>";
    }
    # Display oe subs
    $oesubdsp = "<tr><th colspan=2>Equity</th></tr>";
    foreach ($oesub as $ksub => $sub) {
        $oesubdsp .= "<tr class='bg-even'><td colspan=2><b>{$sub}</b></td></tr>";
        $subaccs = getaccs($ksub, $heads, 'o', $accno);
        foreach ($subaccs as $kkey => $subacc) {
            $acc = getaccnum($subacc);
            $oesubdsp .= "<tr class='bg-odd'><td>{$subacc}</td><td>{$acc['accname']}</td></tr>";
        }
    }
    # Display ass subs
    $asssubdsp = "<tr><th colspan=2>Assets</th></tr>";
    if (isset($asssub)) {
        foreach ($asssub as $ksub => $sub) {
            $asssubdsp .= "<tr class='bg-even'><td colspan=2><b>{$sub}</b></td></tr>";
            $subaccs = getaccs($ksub, $heads, 'a', $accno);
            foreach ($subaccs as $kkey => $subacc) {
                $acc = getaccnum($subacc);
                $asssubdsp .= "<tr class='bg-odd'><td>{$subacc}</td><td>{$acc['accname']}</td></tr>";
            }
        }
    }
    # Set up table to display in
    $OUTPUT = "<center>\n\t<h3>Configure Balance Sheet</h3>\n\t<h4>Confirm</h4>\n\t<form action='" . SELF . "' method=post name=form>\n\t<input type=hidden name=key value=write>{$hide}\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=60%>\n\t\t{$oesubdsp}\n\t\t<tr><td><br></td></tr>\n\t\t{$asssubdsp}\n\t\t<tr><td><br></td></tr>\n\t\t<tr><td> </td><td align=center><input type=submit value='Confirm &raquo'></td></tr>\n\t<table>\n\t</form>\n\t<p>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=25%>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<tr class=datacell><td align=center><a target=_blank href='../core/acc-new2.php'>Add account (New Window)</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $OUTPUT;
}