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

$formname = "Profit Sharing";
$file     = "profshar.php";

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

$profres = mysqli_query($conn, "SELECT * FROM `profit` ") or die(mysqli_error($conn));
$getprof = mysqli_fetch_object($profres);
$actprof = $getprof->amount ?? 0;
if (empty($actprof)) {
    $actprof = 0.00;
}

$result = mysqli_query($conn, "SELECT * FROM `accmast` WHERE `grpcode`='050' ORDER BY name") or die(mysqli_error($conn));

if (isset($_POST["submit"])) {
    $a = 1;
    $count   = (int) $_POST["items"];
    $totperc = (float) $_POST["totperc"];

    if (round($totperc, 2) != 100) {
        browse("Percentage Total Should Be 100");
        $a = 0;
    }

    if ($a == 1) {
        for ($i = 0; $i < $count; $i++) {
            $maccode = $_POST["accode_$i"];
            $percent = $_POST["percent_$i"];
            $prolos  = $_POST["prolos_$i"];
            $pdc     = ($prolos > 0) ? 'C' : 'D';

            mysqli_query($conn, "UPDATE `accmast` SET `percent`='" . mysqli_real_escape_string($conn, $percent) . "',
                `currbal` = '" . mysqli_real_escape_string($conn, $prolos) . "',
                `currdc` = '$pdc'  WHERE `accode`= '" . mysqli_real_escape_string($conn, $maccode) . "' ") or die(mysqli_error($conn));
        }
        updmess($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; }

    .sum-strip { margin:0 0 14px; padding:14px 16px; background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px;
        display:flex; align-items:center; justify-content:flex-end; gap:10px; }
    .sum-strip .lbl2 { font-size:13px; font-weight:600; color:#64748b; }
    .sum-strip .val2 { font-size:16px; font-weight:700; color:#1e293b; }

    .grid-wrap { border:1px solid #e2e8f0; border-radius:8px; overflow:auto; margin-top:4px; }
    table.dgrid { width:100%; border-collapse:collapse; font-size:12.5px; }
    table.dgrid thead th { background:#1e293b; color:#e2e8f0; font-weight:700; font-size:10.5px; text-transform:uppercase;
        letter-spacing:.04em; padding:9px 10px; border-bottom:2px solid #334155; text-align:left; white-space:nowrap; }
    table.dgrid th.num { text-align:right; }
    table.dgrid td { padding:6px 8px; border-bottom:1px solid #f1f5f9; }
    table.dgrid tbody tr:hover { background:#f8faff; }
    table.dgrid input { width:100%; padding:6px 8px; font-size:12.5px; border:1px solid #e2e8f0; border-radius:5px;
        background:#f8fafc; font-family:inherit; box-sizing:border-box; color:#1e293b; }
    table.dgrid input:focus { border-color:#3b82f6; background:#fff; outline:none; }
    table.dgrid input[readonly] { background:#f1f5f9; color:#475569; }
    table.dgrid input.numfld { text-align:right; }

    .tot-row { display:flex; justify-content:flex-end; gap:20px; margin-top:12px; padding:12px 16px;
        background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; flex-wrap:wrap; }
    .tot-fld label { font-size:11px; font-weight:600; color:#64748b; display:block; margin-bottom:3px; }
    .tot-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; color:#1e293b; }

    .btn-bar { display:flex; justify-content:center; align-items:center; gap:8px; padding:16px 20px; border-top:1px solid #f1f5f9; background:#fafafa; }
    .abtn { width:auto; padding:0 22px; height:42px; border-radius:8px; border:none; cursor:pointer; font-size:12.5px;
        font-weight:600; color:#fff; display:inline-flex; align-items:center; gap:6px; text-decoration:none;
        transition:transform .12s,box-shadow .12s,filter .12s; }
    .abtn:hover { transform:translateY(-2px); box-shadow:0 5px 14px rgba(0,0,0,.22); filter:brightness(1.06); }
    .abtn-save { background:#16a34a; }
    .abtn-exit { background:#64748b; }
</style>

<script>
    $(document).ready(function () {
        $("body").on("focus keyup blur change", '.perc,.amt,.pro,.totperc,.totamt', calperc);
        function calperc() {
            var tr = $(this).closest("tr"),
                    iperc = tr.find(".perc").val(),
                    iamt = $('.amt').val();

            var actamt = (iperc * iamt) / 100;

            tr.find(".pro").val(actamt.toFixed(2));

            var valperc = 0;
            $(".perc").each(function () {
                if (!isNaN(this.value) && this.value.length !== 0) {
                    valperc += parseFloat(this.value);
                }
            });
            $(".totperc").val(valperc.toFixed(2));

            var valtot = 0;
            $(".pro").each(function () {
                if (!isNaN(this.value) && this.value.length !== 0) {
                    valtot += parseFloat(this.value);
                }
            });
            $(".totamt").val(valtot.toFixed(2));
        }
        // populate totals on load from whatever the server rendered
        $('.perc').first().trigger('change');
    });
</script>
</head>
<body>
    <form name="" id="form" method="post" action="">
    <div class="sim-card">

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

        <div class="sim-body">

            <div class="sum-strip">
                <span class="lbl2">Profit / Loss :</span>
                <span class="val2"><?php echo number_format($actprof, 2); ?></span>
                <input type="hidden" class="amt" value="<?php echo $actprof; ?>">
            </div>

            <div class="grid-wrap">
                <table class="dgrid">
                    <thead>
                        <tr>
                            <th style="width:45%;">Account Name</th>
                            <th style="width:15%;">Init</th>
                            <th class="num" style="width:15%;">Share %</th>
                            <th class="num" style="width:25%;">Profit / Loss</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $ctr = 0;
                        while ($row = mysqli_fetch_array($result)) {
                            $mperc  = $row['percent'];
                            $prolos = $actprof * ($mperc / 100);
                            ?>
                            <tr>
                                <input type="hidden" name="accode_<?php echo $ctr; ?>" value="<?php echo htmlspecialchars($row['accode']); ?>">
                                <td><input type="text" name="acname_<?php echo $ctr; ?>" value="<?php echo htmlspecialchars($row['name']); ?>" readonly></td>
                                <td><input type="text" name="init_<?php echo $ctr; ?>" value="<?php echo htmlspecialchars($row['init']); ?>" readonly></td>
                                <td><input type="text" name="percent_<?php echo $ctr; ?>" value="<?php echo htmlspecialchars($mperc); ?>" class="numfld perc"></td>
                                <td><input type="number" step="any" name="prolos_<?php echo $ctr; ?>" value="<?php echo number_format((float) $prolos, 2, '.', ''); ?>" class="numfld pro" readonly></td>
                            </tr>
                            <?php
                            $ctr++;
                        }
                        ?>
                    </tbody>
                </table>
            </div>

            <div class="tot-row">
                <div class="tot-fld">
                    <label>Total Share % (should be 100)</label>
                    <input type="text" name="totperc" class="totperc" readonly>
                </div>
                <div class="tot-fld">
                    <label>Total Profit / Loss</label>
                    <input type="text" name="totamt" class="totamt" readonly>
                </div>
            </div>

            <input type="hidden" id="items" name="items" value="<?php echo $ctr; ?>">
        </div>

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

    </div>
    </form>

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