<?php
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include('includes/function.php');

$maindb = 'openbal';
$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);

$dcode = mysqli_real_escape_string($conn, $_GET["code"]);

if (!empty($dcode) || $dcode != '') {
    $result = mysqli_query($conn, "SELECT * FROM `accmast` WHERE `grpcode`='$dcode' ORDER BY name") or die(mysqli_error($conn));
} else {
    $result = mysqli_query($conn, "SELECT * FROM `accmast` WHERE grpcode != '011' and grpcode != '012' ORDER BY name") or die(mysqli_error($conn));
}

$ctr = 0;
$rowsHtml = '';
while ($row = mysqli_fetch_array($result)) {
    $dc = $row['dc'];
    // Match original: whichever side (Debit/Credit) the saved `dc` flag points
    // to gets pre-filled with the saved openbal, the other starts blank —
    // but BOTH stay editable at initial render. The mutual-exclusivity
    // (typing in one side locks the other) is applied client-side only,
    // same as before this restyle.
    $debitVal  = ($dc == 'D') ? htmlspecialchars($row['openbal']) : '';
    $creditVal = ($dc != 'D') ? htmlspecialchars($row['openbal']) : '';

    $rowsHtml .= '<tr>'
        . '<td><input type="hidden" name="accode_' . $ctr . '" value="' . htmlspecialchars($row['accode']) . '">'
        . '<input type="text" name="acname_' . $ctr . '" value="' . htmlspecialchars($row['name']) . '" readonly></td>'
        . '<td><input type="text" name="init_' . $ctr . '" value="' . htmlspecialchars($row['init']) . '" readonly></td>'
        . '<td><input type="text" name="bankinit_' . $ctr . '" value="' . htmlspecialchars($row['bankinit']) . '" readonly></td>'
        . '<td><input type="number" step="any" name="debit_' . $ctr . '" value="' . $debitVal . '" class="cal numfld"></td>'
        . '<td><input type="number" step="any" name="credit_' . $ctr . '" value="' . $creditVal . '" class="cal2 numfld"></td>'
        . '</tr>';
    $ctr++;
}

if ($ctr == 0) {
    echo '<div class="grid-empty">No accounts found for this group.</div>';
} else {
    echo '<table class="dgrid">'
        . '<thead><tr>'
        . '<th style="width:34%;text-align:left;">Name</th>'
        . '<th style="width:14%;">Init</th>'
        . '<th style="width:14%;">Bank Init</th>'
        . '<th class="num" style="width:19%;">Debit</th>'
        . '<th class="num" style="width:19%;">Credit</th>'
        . '</tr></thead>'
        . '<tbody>' . $rowsHtml . '</tbody>'
        . '</table>';
}

echo "<input type='hidden' name='count' value='$ctr'>";
