<?php
ob_start();
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
require("includes/config.php");
require("includes/function.php");
require("includes/check_permission.php");

$formname = 'Opening Balance';
$maindb   = 'accmast';
$file     = 'openbal.php';

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

$addflag = (isset($_GET["mode"]) && $_GET["mode"] == "true") ? 1 : 0;

// ── POST: bulk-save opening balances for every account row currently
//    rendered by opnbalsrch.php (same logic as before this restyle — only
//    the surrounding page markup changed). ─────────────────────────────────
if (isset($_POST['submit'])) {
    $count = $_POST["count"];

    for ($i = 0; $i < $count; $i++) {
        $accode = $_POST['accode_' . $i];
        $debit  = $_POST['debit_' . $i];
        $credit = $_POST['credit_' . $i];

        if ($debit > 0) {
            $mopenbal = $debit;
            $mdc      = "D";
        } else {
            if ($credit > 0) {
                $mopenbal = $credit;
                $mdc      = "C";
            } else {
                $mopenbal = 0.00;
                $mdc      = "";
            }
        }

        mysqli_query($conn, "UPDATE `$maindb` SET openbal='$mopenbal', `dc`='$mdc' WHERE accode='$accode' ") or die(mysqli_error($conn));
    }
    updmess();
    header("refresh:1; url=$file");
    exit;
}

include("includes/linkshead.php");
?>
<style>
    body { background:#f0f2f5; margin:0; padding:10px 14px; }

    .sim-card { background:#fff; border-radius:10px; box-shadow:0 1px 3px rgba(0,0,0,.08), 0 4px 16px rgba(0,0,0,.06); overflow:hidden; }
    .sim-card-header { background:#fff; border-bottom:2px solid #f1f5f9; padding:12px 20px; display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:8px; }
    .sim-card-header h2 { font-size:15px; font-weight:700; color:#1e293b; margin:0; letter-spacing:.01em; }
    .sim-body { padding:16px 20px; }

    .fr-grid { display:flex; flex-wrap:wrap; gap:0 20px; }
    .fl { flex:1; min-width:220px; display:flex; flex-direction:column; margin-bottom:11px; max-width:360px; }
    .lbl { font-size:13px; font-weight:600; color:#374151; margin-bottom:4px; }
    .finp { padding:8px 12px; background:#f8fafc; border:1px solid #e2e8f0; border-radius:6px; font-size:13.5px; color:#1e293b; outline:none; width:100%; box-sizing:border-box; font-family:inherit; }
    .finp:focus { background:#fff; border-color:#3b82f6; box-shadow:0 0 0 3px rgba(59,130,246,.12); }
    .fl .select2-container { flex:1; }
    .fl .select2-container .select2-selection--single { height:36px; border:1px solid #e2e8f0; border-radius:6px; background:#f8fafc; display:flex; align-items:center; }
    .fl .select2-container--default .select2-selection--single .select2-selection__rendered { line-height:normal; font-size:13.5px; color:#1e293b; padding-left:12px; }
    .fl .select2-container--default .select2-selection--single .select2-selection__arrow { height:34px; right:6px; }
    .fl .select2-container--default.select2-container--focus .select2-selection--single { border-color:#3b82f6; box-shadow:0 0 0 3px rgba(59,130,246,.12); }

    .sum-strip { margin:4px 0 14px; padding:14px 16px; background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; display:flex; align-items:center; justify-content:flex-end; gap:16px; flex-wrap:wrap; }
    .sum-fld label { font-size:11px; font-weight:600; color:#64748b; display:block; margin-bottom:3px; }
    .sum-fld input { width:150px; box-sizing:border-box; padding:6px 8px; font-size:13px; font-weight:700; background:#fff; border:1px solid #e2e8f0; border-radius:6px; text-align:right; font-family:inherit; }
    .sum-fld input.debit-tot  { color:#16a34a; }
    .sum-fld input.credit-tot { color:#dc2626; }

    .grid-wrap { border:1px solid #e2e8f0; border-radius:8px; overflow:auto; margin-top:4px; max-height:420px; }
    table.dgrid { width:100%; border-collapse:collapse; font-size:12.5px; table-layout:fixed; min-width:680px; }
    table.dgrid thead th { position:sticky; top:0; background:#1e293b; color:#e2e8f0; font-weight:700; font-size:10.5px; text-transform:uppercase; letter-spacing:.04em; padding:9px 6px; border-bottom:2px solid #334155; text-align:center; white-space:nowrap; overflow:hidden; z-index:1; }
    table.dgrid th.num { text-align:right; }
    table.dgrid td { padding:4px 4px; border-bottom:1px solid #f1f5f9; overflow:hidden; }
    table.dgrid tbody tr:hover { background:#f8faff; }
    table.dgrid input { width:100%; padding:5px 5px; font-size:12px; border:1px solid #e2e8f0; border-radius:4px; background:#fff; font-family:inherit; box-sizing:border-box; color:#1e293b; }
    table.dgrid input:focus { border-color:#3b82f6; background:#f0f7ff; outline:none; }
    table.dgrid input[readonly] { background:#f8fafc; color:#64748b; border-color:#f1f5f9; }
    table.dgrid input.numfld { text-align:right; }
    .grid-empty { text-align:center; padding:40px 20px; color:#94a3b8; font-size:12.5px; }

    .btn-bar { display:flex; justify-content:center; align-items:center; gap:8px; padding:16px 20px; border-top:1px solid #f1f5f9; background:#fafafa; }
    .abtn { width:46px; height:46px; border-radius:10px; border:none; cursor:pointer; font-size:15px; color:#fff; display:inline-flex; align-items:center; justify-content:center; text-decoration:none; transition:transform .12s,box-shadow .12s; position:relative; }
    .abtn:hover { transform:translateY(-2px); box-shadow:0 5px 14px rgba(0,0,0,.22); }
    .abtn-exit { background:#e2e8f0; color:#64748b; }
    .abtn::after { content:attr(data-tip); position:absolute; bottom:calc(100% + 6px); left:50%; transform:translateX(-50%); background:#1e293b; color:#fff; font-size:10px; font-weight:600; padding:3px 8px; border-radius:4px; white-space:nowrap; opacity:0; pointer-events:none; transition:opacity .15s; }
    .abtn:hover::after { opacity:1; }
    .abtn-save { width:auto; padding:0 18px; background:#16a34a; gap:6px; font-size:12.5px; font-weight:600; }
</style>
</head>
<body>
<form name="" class="validation" id="form" action="" method="post">
<div class="sim-card">

    <div class="sim-card-header">
        <h2><i class="fa fa-scale-balanced" style="color:#f59e0b;margin-right:8px;font-size:14px;"></i><?php echo $formname; ?></h2>
    </div>

    <div class="sim-body">

        <div class="fr-grid">
            <div class="fl">
                <span class="lbl">A/C Group</span>
                <select id="cmbgrp" name="cmbgrp" class="finp select2" style="width:100%;">
                    <option value=""></option>
                    <option value="">All</option>
                    <?php
                    $mown = mysqli_query($conn, "SELECT grpcode, `name` FROM `grpmast` WHERE grpcode IN (001,002,010,009,012,030,040,044) ") or die(mysqli_error($conn));
                    while ($trow = mysqli_fetch_array($mown)) {
                        echo "<option value=\"" . htmlspecialchars($trow['grpcode']) . "\">" . htmlspecialchars($trow['name']) . "</option>";
                    }
                    ?>
                </select>
            </div>
        </div>

        <div class="sum-strip">
            <div class="sum-fld">
                <label>Total Debit</label>
                <input type="text" id="totdebit" name="totdebit" class="debit-tot" readonly tabindex="-1">
            </div>
            <div class="sum-fld">
                <label>Total Credit</label>
                <input type="text" id="totcredit" name="totcredit" class="credit-tot" readonly tabindex="-1">
            </div>
        </div>

        <div class="grid-wrap">
            <div id="data"><div class="grid-empty">Select an A/C Group above to load accounts.</div></div>
        </div>

    </div>

    <div class="btn-bar">
        <button id="submit" type="submit" name="submit" class="abtn abtn-save buttonform" data-tip="Save">
            <i class="fa fa-check"></i> Save
        </button>
        <button id="hexit" type="button" class="abtn abtn-exit buttonform" data-tip="Exit" onclick="window.location.href='default.php'">
            <i class="fa fa-power-off"></i>
        </button>
    </div>

</div>
</form>

<?php include("includes/linksfoot.php"); ?>

<script>
    $(document).ready(function () {
        $("#cmbgrp").on('change', function () {
            $.ajax({
                type: "GET",
                url: "opnbalsrch.php",
                data: { code: $('#cmbgrp').val() },
                success: function (result) {
                    $("#data").html(result);
                }
            });
        });

        $('#data').on('blur change', '.cal, .cal2', calculateSum);

        function calculateSum() {
            var dsum = 0;
            $(".cal").each(function () {
                if (!isNaN(this.value) && this.value.length != 0) {
                    dsum += parseFloat(this.value);
                }
            });
            $("#totdebit").val(dsum.toFixed(2));

            var csum = 0;
            $(".cal2").each(function () {
                if (!isNaN(this.value) && this.value.length != 0) {
                    csum += parseFloat(this.value);
                }
            });
            $("#totcredit").val(csum.toFixed(2));
        }

        $('#data').on('blur change', '.cal, .cal2', function () {
            var $row = $(this).closest("tr");
            var mname = $row.find('.cal').val();
            var mname2 = $row.find('.cal2').val();

            if (mname != "" || mname != 0) {
                $($row.find('.cal2')).attr("readonly", true);
            } else {
                $($row.find('.cal2')).removeAttr("readonly");
            }

            if (mname2 != "" || mname2 != 0) {
                $($row.find('.cal')).attr("readonly", true);
            } else {
                $($row.find('.cal')).removeAttr("readonly");
            }
        });

        $('#submit').click(function () {
            $('#form').submit();
        });
    });

    $(document).keydown(function (event) {
        if (!(String.fromCharCode(event.which).toLowerCase() == 's' && event.ctrlKey) && !(event.which == 19))
            return true;
        $("#submit").click();
        event.preventDefault();
        return false;
    });
</script>

</body>
</html>
