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

$formname = 'Stock Register';

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

// ── Inputs from filter form ──────────────────────────────────────────────
$godown = isset($_POST['godown']) ? (int)$_POST['godown'] : 0;
$search = isset($_POST['search']) ? trim($_POST['search']) : '';
$source = isset($_POST['source']) ? trim($_POST['source']) : '';
$dtype  = isset($_POST['dtype'])  ? trim($_POST['dtype'])  : '1';   // 1=Summary, 2=Detail

function d2sql($d) {
    if ($d != '' && preg_match('/^(\d{2})-(\d{2})-(\d{4})$/', $d, $m)) {
        return $m[3] . '-' . $m[2] . '-' . $m[1];
    }
    return '';
}
$mfrmdate = d2sql(isset($_POST['fdate']) ? trim($_POST['fdate']) : '');
$mtodate  = d2sql(isset($_POST['tdate']) ? trim($_POST['tdate']) : '');

if ($mfrmdate == '') {
    browse("From Date Cannot Be Empty");
    header("refresh:1; url=stock.php");
    exit;
}
if ($mtodate == '') {
    browse("To Date Cannot Be Empty");
    header("refresh:1; url=stock.php");
    exit;
}

$godowncond = ($godown > 0) ? " AND sl.`godown`='$godown' " : '';
$sourcecond = ($source != '') ? " AND sl.`source`='" . mysqli_real_escape_string($conn, $source) . "' " : '';
$searchcond = '';
if ($search != '') {
    $s = mysqli_real_escape_string($conn, $search);
    $searchcond = " AND (sl.`description` LIKE '%$s%' OR sl.`modelno` LIKE '%$s%' OR sl.`marka` LIKE '%$s%') ";
}

function pf($v) {
    $v = (float)$v;
    return $v == 0 ? '' : number_format($v, 2);
}

$sourceLabel = ['PUR' => 'Purchase', 'DSP' => 'Despatch'];

if ($dtype == '1') {
    // ── SUMMARY: one row per Godown+Description+Model+Marka, opening/in/out/closing ──
    // Opening always reflects true historical balance (not source-filtered).
    // In/Out within range respect the Source filter if one is selected.
    $inSourceCond  = ($source != '' && $source != 'PUR') ? "AND sl.`source`='PUR'" : '';
    $outSourceCond = ($source != '' && $source != 'DSP') ? "AND sl.`source`='DSP'" : '';
    if ($source == 'PUR') $outSourceCond = "AND 1=0";   // suppress Out entirely
    if ($source == 'DSP') $inSourceCond  = "AND 1=0";   // suppress In entirely

    $sql = "SELECT sl.`godown`, g.`name` AS godownname,
                   sl.`customer`, sl.`supplier`, sl.`description`, sl.`modelno`, sl.`marka`,
                   c.`name` AS customername, s.`name` AS suppliername,
                   SUM(CASE WHEN sl.`vouchdt` < '$mfrmdate' THEN sl.`ctn` ELSE 0 END) AS opening,
                   SUM(CASE WHEN sl.`vouchdt` >= '$mfrmdate' AND sl.`vouchdt` <= '$mtodate' AND sl.`ctn` > 0 $inSourceCond THEN sl.`ctn` ELSE 0 END) AS totin,
                   SUM(CASE WHEN sl.`vouchdt` >= '$mfrmdate' AND sl.`vouchdt` <= '$mtodate' AND sl.`ctn` < 0 $outSourceCond THEN -sl.`ctn` ELSE 0 END) AS totout,
                   SUM(CASE WHEN sl.`vouchdt` <= '$mtodate' THEN sl.`ctn` ELSE 0 END) AS closing,
                   SUM(CASE WHEN sl.`vouchdt` >= '$mfrmdate' AND sl.`vouchdt` <= '$mtodate' AND sl.`ctn` > 0 THEN sl.`tcbm`    ELSE 0 END) AS tottcbm,
                   SUM(CASE WHEN sl.`vouchdt` >= '$mfrmdate' AND sl.`vouchdt` <= '$mtodate' AND sl.`ctn` > 0 THEN sl.`tweight` ELSE 0 END) AS tottweight
            FROM `stockledger` sl
            LEFT JOIN `godown` g ON g.code = sl.godown
            LEFT JOIN `accmast` c ON c.accode = sl.customer
            LEFT JOIN `accmast` s ON s.accode = sl.supplier
            WHERE 1=1 $godowncond $searchcond
            GROUP BY sl.`godown`, sl.`customer`, sl.`supplier`, sl.`description`, sl.`modelno`, sl.`marka`
            HAVING totin > 0 OR totout > 0 OR ABS(opening) > 0.005 OR ABS(closing) > 0.005
            ORDER BY g.`name` ASC, sl.`description` ASC";
    // Note: sourcecond intentionally not applied to summary totals (in/out already split by sign, source filter only meaningful in detail)
    $res = mysqli_query($conn, $sql) or die(mysqli_error($conn));
    $rows = [];
    while ($r = mysqli_fetch_assoc($res)) { $rows[] = $r; }
} else {
    // ── DETAIL: every movement row, with running balance per item ────────────
    $sql = "SELECT sl.*, g.`name` AS godownname,
                   c.`name` AS customername, s.`name` AS suppliername
            FROM `stockledger` sl
            LEFT JOIN `godown` g ON g.code = sl.godown
            LEFT JOIN `accmast` c ON c.accode = sl.customer
            LEFT JOIN `accmast` s ON s.accode = sl.supplier
            WHERE sl.`vouchdt` >= '$mfrmdate' AND sl.`vouchdt` <= '$mtodate' $godowncond $sourcecond $searchcond
            ORDER BY sl.`godown` ASC, sl.`customer` ASC, sl.`supplier` ASC, sl.`description` ASC, sl.`vouchdt` ASC, sl.`srl` ASC";
    $res = mysqli_query($conn, $sql) or die(mysqli_error($conn));
    $detailRows = [];
    while ($r = mysqli_fetch_assoc($res)) { $detailRows[] = $r; }

    // Group into item blocks, computing opening balance (before From date) and running balance
    $itemGroups = [];
    foreach ($detailRows as $r) {
        $key = $r['godown'] . '|' . $r['customer'] . '|' . $r['supplier'] . '|' . $r['description'] . '|' . $r['modelno'] . '|' . $r['marka'];
        if (!isset($itemGroups[$key])) {
            $opRes = mysqli_query($conn, "SELECT SUM(`ctn`) AS s FROM `stockledger`
                                           WHERE `godown`='{$r['godown']}' AND `customer`='{$r['customer']}' AND `supplier`='{$r['supplier']}'
                                           AND `description`='" . mysqli_real_escape_string($conn, $r['description']) . "'
                                           AND `modelno`='" . mysqli_real_escape_string($conn, $r['modelno']) . "'
                                           AND `marka`='" . mysqli_real_escape_string($conn, $r['marka']) . "'
                                           AND `vouchdt` < '$mfrmdate'") or die(mysqli_error($conn));
            $opRow = mysqli_fetch_assoc($opRes);
            $opening = (float)($opRow['s'] ?? 0);
            $itemGroups[$key] = [
                'godownname'   => $r['godownname'],
                'customername' => $r['customername'] ?? '',
                'suppliername' => $r['suppliername'] ?? '',
                'description'  => $r['description'],
                'modelno'      => $r['modelno'],
                'marka'        => $r['marka'],
                'opening'      => $opening,
                'rows'         => [],
                'totin'        => 0,
                'totout'       => 0,
            ];
        }
        $itemGroups[$key]['rows'][] = $r;
    }
    foreach ($itemGroups as $key => &$grp) {
        $running = $grp['opening'];
        foreach ($grp['rows'] as &$rr) {
            $running += (float)$rr['ctn'];
            $rr['running'] = $running;
            if ($rr['ctn'] > 0) $grp['totin']  += (float)$rr['ctn'];
            else                 $grp['totout'] += -(float)$rr['ctn'];
        }
        unset($rr);
        $grp['closing'] = $running;
    }
    unset($grp);
}

$mfdt = date('d-m-Y', strtotime($mfrmdate));
$mtdt = date('d-m-Y', strtotime($mtodate));

// ── CSV Export ───────────────────────────────────────────────────────────
if (isset($_POST['excel'])) {
    header('Content-Type: text/csv; charset=utf-8');
    $suffix = ($dtype == '2') ? 'Detail' : 'Summary';
    header('Content-Disposition: attachment; filename="Stock_Register_' . $suffix . '_' . date('d-m-Y') . '.csv"');
    $out = fopen('php://output', 'w');
    if ($dtype == '1') {
        fputcsv($out, ['Godown', 'Customer', 'Supplier', 'Description', 'Model No.', 'Marka', 'Opening CTN', 'In CTN', 'Out CTN', 'Balance CTN', 'T.CBM', 'T.Weight']);
        foreach ($rows as $r) {
            fputcsv($out, [
                $r['godownname'], $r['customername'] ?? '', $r['suppliername'] ?? '',
                $r['description'], $r['modelno'], $r['marka'],
                number_format((float)$r['opening'],2,'.',''), number_format((float)$r['totin'],2,'.',''),
                number_format((float)$r['totout'],2,'.',''), number_format((float)$r['closing'],2,'.',''),
                number_format((float)$r['tottcbm'],4,'.',''),
                number_format((float)$r['tottweight'],2,'.',''),
            ]);
        }
    } else {
        fputcsv($out, ['Godown', 'Customer', 'Supplier', 'Description', 'Model No.', 'Marka', 'Date', 'Voucher No', 'Type', 'In', 'Out', 'Balance']);
        foreach ($itemGroups as $grp) {
            fputcsv($out, [$grp['godownname'], $grp['customername'] ?? '', $grp['suppliername'] ?? '', $grp['description'], $grp['modelno'], $grp['marka'], '', '', 'Opening', '', '', number_format($grp['opening'],2,'.','')]);
            foreach ($grp['rows'] as $r) {
                $in = $r['ctn'] > 0 ? $r['ctn'] : '';
                $out2 = $r['ctn'] < 0 ? -$r['ctn'] : '';
                fputcsv($out, [
                    '', '', '', '', '', '',
                    date('d-m-Y', strtotime($r['vouchdt'])), $r['vouchno'], $sourceLabel[$r['source']] ?? $r['source'],
                    $in !== '' ? number_format($in,2,'.','') : '', $out2 !== '' ? number_format($out2,2,'.','') : '',
                    number_format($r['running'],2,'.',''),
                ]);
            }
            fputcsv($out, ['', '', '', '', '', '', '', '', 'Closing', number_format($grp['totin'],2,'.',''), number_format($grp['totout'],2,'.',''), number_format($grp['closing'],2,'.','')]);
            fputcsv($out, []);
        }
    }
    fclose($out);
    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;
    }
    .sim-card-header h2 { font-size:15px; font-weight:700; color:#1e293b; margin:0; }
    .sim-card-header .sub { font-size:11.5px; color:#94a3b8; margin-top:2px; }

    .sim-body { padding:18px 20px; }

    .btn { padding:8px 16px; border:none; border-radius:6px; font-size:12.5px; font-weight:600; cursor:pointer; display:inline-flex; align-items:center; gap:6px; text-decoration:none; }
    .btn-export { background:#16a34a; color:#fff; }
    .btn-export:hover { background:#15803d; }
    .btn-print { background:#4a5759; color:#fff; }
    .btn-print:hover { background:#374043; }

    table.reg { width:100%; border-collapse:collapse; font-size:12px; }
    table.reg th {
        background:#f8fafc; color:#374151; font-weight:700; font-size:11px;
        text-transform:uppercase; letter-spacing:.04em; padding:8px 10px;
        border-bottom:2px solid #e2e8f0; text-align:left; white-space:nowrap;
    }
    table.reg th.num { text-align:right; }
    table.reg td { padding:6px 10px; border-bottom:1px solid #f1f5f9; white-space:nowrap; }
    table.reg td.num { text-align:right; }
    .num { text-align:right; }
    table.reg tfoot td { font-weight:700; background:#f8fafc; border-top:2px solid #e2e8f0; }
    .bal-zero { color:#94a3b8; }
    .bal-low  { color:#dc2626; font-weight:700; }
    .bal-ok   { color:#16a34a; font-weight:700; }

    .acc-block { border:1px solid #e2e8f0; border-radius:8px; margin-bottom:18px; overflow:hidden; }
    .acc-head {
        background:#eff6ff; padding:9px 14px; display:flex; justify-content:space-between; align-items:center;
        border-bottom:1px solid #e2e8f0;
    }
    .acc-head .acc-name { font-size:13px; font-weight:700; color:#1e293b; }
    .acc-head .acc-meta { font-size:11px; color:#64748b; margin-left:8px; }
    tr.openrow td { background:#fef9c3; font-weight:600; }
    tr.closerow td { background:#dbeafe; font-weight:700; border-top:2px solid #e2e8f0; }

    .pill { font-size:10.5px; font-weight:700; border-radius:20px; padding:2px 9px; color:#fff; display:inline-block; }
    .pill-in  { background:#16a34a; }
    .pill-out { background:#dc2626; }

    .reg-wrap { overflow:auto; }

    @media print {
        body { background:#fff; padding:0; }
        .no-print { display:none !important; }
        .sim-card { box-shadow:none; border-radius:0; }
    }
</style>

<body>
<div class="sim-card">
    <div class="sim-card-header">
        <div>
            <h2><i class="fa fa-warehouse" style="color:#3b82f6;margin-right:8px;font-size:14px;"></i><?php echo $formname; ?> (<?php echo $dtype=='2' ? 'Detail' : 'Summary'; ?>)</h2>
            <div class="sub"><?php echo $mfdt; ?> to <?php echo $mtdt; ?></div>
        </div>
        <div class="no-print" style="display:flex;gap:8px;">
            <button type="button" class="btn btn-print" onclick="window.print()"><i class="fa fa-print"></i> Print</button>
    <button onclick="if(window.parent&&window.parent!==window){window.parent.document.getElementById('rptframe').src='about:blank';}else{window.close();}" style="padding:8px 22px;background:#f1f5f9;color:#374151;border:none;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;margin-left:8px;"><i class="fa fa-arrow-left"></i> Go Back</button>
            <form method="POST" style="margin:0;">
                <?php foreach ($_POST as $k => $v) { if ($k != 'view') echo '<input type="hidden" name="' . htmlspecialchars($k) . '" value="' . htmlspecialchars($v) . '">'; } ?>
                <button type="submit" name="excel" value="1" class="btn btn-export"><i class="fa fa-file-csv"></i> Export CSV</button>
            </form>
        </div>
    </div>

    <div class="sim-body">

        <?php if ($dtype == '1'): ?>
        <!-- ── SUMMARY VIEW ─────────────────────────────────────────────── -->
        <?php if (count($rows) == 0): ?>
        <div style="text-align:center;padding:40px;color:#94a3b8;">No stock records found for the selected filters.</div>
        <?php else: ?>
        <div class="reg-wrap">
        <table class="reg">
            <thead>
                <tr>
                    <th>Godown</th>
                    <th>Customer</th>
                    <th>Supplier</th>
                    <th>Description</th>
                    <th>Model No.</th>
                    <th>Marka</th>
                    <th class="num">Opening CTN</th>
                    <th class="num">In CTN</th>
                    <th class="num">Out CTN</th>
                    <th class="num">Balance CTN</th>
                    <th class="num">T.CBM</th>
                    <th class="num">T.Weight</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $gtOpen = $gtIn = $gtOut = $gtClose = $gtCbm = $gtWt = 0;
                foreach ($rows as $r):
                    $closing = (float)$r['closing'];
                    $balcls = abs($closing) < 0.005 ? 'bal-zero' : ($closing < 0 ? 'bal-low' : 'bal-ok');
                    $gtOpen += (float)$r['opening']; $gtIn += (float)$r['totin']; $gtOut += (float)$r['totout']; $gtClose += $closing;
                    $gtCbm += (float)$r['tottcbm']; $gtWt += (float)$r['tottweight'];
                ?>
                <tr>
                    <td><?php echo htmlspecialchars($r['godownname'] ?? ''); ?></td>
                    <td><?php echo htmlspecialchars($r['customername'] ?? ''); ?></td>
                    <td><?php echo htmlspecialchars($r['suppliername'] ?? ''); ?></td>
                    <td><?php echo htmlspecialchars($r['description']); ?></td>
                    <td><?php echo htmlspecialchars($r['modelno']); ?></td>
                    <td><?php echo htmlspecialchars($r['marka']); ?></td>
                    <td class="num"><?php echo number_format((float)$r['opening'], 2); ?></td>
                    <td class="num"><?php echo pf($r['totin']); ?></td>
                    <td class="num"><?php echo pf($r['totout']); ?></td>
                    <td class="num <?php echo $balcls; ?>"><?php echo number_format($closing, 2); ?></td>
                    <td class="num"><?php echo number_format((float)$r['tottcbm'], 4); ?></td>
                    <td class="num"><?php echo pf($r['tottweight']); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="6" style="text-align:right;">Total (<?php echo count($rows); ?> items)</td>
                    <td class="num"><?php echo number_format($gtOpen, 2); ?></td>
                    <td class="num"><?php echo pf($gtIn); ?></td>
                    <td class="num"><?php echo pf($gtOut); ?></td>
                    <td class="num"><?php echo number_format($gtClose, 2); ?></td>
                    <td class="num"><?php echo number_format($gtCbm, 4); ?></td>
                    <td class="num"><?php echo pf($gtWt); ?></td>
                </tr>
            </tfoot>
        </table>
        </div>
        <?php endif; ?>

        <?php else: ?>
        <!-- ── DETAIL VIEW ──────────────────────────────────────────────── -->
        <?php if (count($itemGroups) == 0): ?>
        <div style="text-align:center;padding:40px;color:#94a3b8;">No stock movements found for the selected filters.</div>
        <?php else: ?>
        <?php
        $gtIn = $gtOut = $gtCtn = $gtCbm = $gtWt = 0;
        foreach ($itemGroups as $grp):
            $gtIn += $grp['totin']; $gtOut += $grp['totout'];
            foreach ($grp['rows'] as $rr) {
                if ($rr['ctn'] > 0) {
                    $gtCtn += (float)($rr['ctn'] ?? 0);
                    $gtCbm += (float)($rr['tcbm'] ?? 0);
                    $gtWt  += (float)($rr['tweight'] ?? 0);
                }
            }
        ?>
        <div class="acc-block">
            <div class="acc-head">
                <div>
                    <span class="acc-name"><?php echo htmlspecialchars($grp['description']); ?></span>
                    <span class="acc-meta">
                        <?php echo htmlspecialchars($grp['godownname'] ?? ''); ?>
                        <?php echo $grp['modelno'] ? ' · ' . htmlspecialchars($grp['modelno']) : ''; ?>
                        <?php echo $grp['marka']   ? ' · Marka: ' . htmlspecialchars($grp['marka']) : ''; ?>
                        <?php echo !empty($grp['customername']) ? ' · Customer: ' . htmlspecialchars($grp['customername']) : ''; ?>
                        <?php echo !empty($grp['suppliername']) ? ' · Supplier: ' . htmlspecialchars($grp['suppliername']) : ''; ?>
                    </span>
                </div>
            </div>
            <div class="reg-wrap">
            <table class="reg">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Voucher No</th>
                        <th>Type</th>
                        <th class="num">In</th>
                        <th class="num">Out</th>
                        <th class="num">Balance</th>
                    </tr>
                </thead>
                <tbody>
                    <tr class="openrow">
                        <td colspan="3" style="text-align:right;">Opening Balance</td>
                        <td></td><td></td>
                        <td class="num"><?php echo number_format($grp['opening'], 2); ?></td>
                    </tr>
                    <?php foreach ($grp['rows'] as $r):
                        $isIn = $r['ctn'] > 0;
                        $file = $isIn ? 'purchase.php' : 'despatch.php';
                    ?>
                    <tr style="cursor:pointer;" onclick="window.open('<?php echo $file; ?>?mode=edit&vouchno=<?php echo $r['vouchno']; ?>','_blank')">
                        <td><?php echo date('d-m-Y', strtotime($r['vouchdt'])); ?></td>
                        <td style="font-weight:600;color:#2563eb;"><?php echo $r['vouchno']; ?></td>
                        <td><span class="pill <?php echo $isIn ? 'pill-in' : 'pill-out'; ?>"><?php echo $sourceLabel[$r['source']] ?? $r['source']; ?></span></td>
                        <td class="num"><?php echo $isIn ? number_format($r['ctn'], 2) : ''; ?></td>
                        <td class="num"><?php echo !$isIn ? number_format(-$r['ctn'], 2) : ''; ?></td>
                        <td class="num"><?php echo number_format($r['running'], 2); ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <tr class="closerow">
                        <td colspan="3" style="text-align:right;">Closing Balance</td>
                        <td class="num"><?php echo number_format($grp['totin'], 2); ?></td>
                        <td class="num"><?php echo number_format($grp['totout'], 2); ?></td>
                        <td class="num"><?php echo number_format($grp['closing'], 2); ?></td>
                    </tr>
                </tbody>
            </table>
            </div>
        </div>
        <?php endforeach; ?>
        <div style="margin-top:8px;padding:12px 16px;background:#1e293b;color:#fff;border-radius:8px;display:flex;justify-content:flex-end;gap:24px;font-size:12.5px;font-weight:600;flex-wrap:wrap;">
            <span><span style="color:#94a3b8;margin-right:6px;font-weight:500;">Total In</span><?php echo number_format($gtIn, 2); ?></span>
            <span><span style="color:#94a3b8;margin-right:6px;font-weight:500;">Total Out</span><?php echo number_format($gtOut, 2); ?></span>
            <span><span style="color:#94a3b8;margin-right:6px;font-weight:500;">CTN</span><?php echo pf($gtCtn); ?></span>
            <span><span style="color:#94a3b8;margin-right:6px;font-weight:500;">T.CBM</span><?php echo number_format($gtCbm, 4); ?></span>
            <span><span style="color:#94a3b8;margin-right:6px;font-weight:500;">T.Weight</span><?php echo pf($gtWt); ?></span>
        </div>
        <?php endif; ?>
        <?php endif; ?>

    </div>
</div>

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