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

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

$para    = isset($_GET['para']) && $_GET['para'] == 'C' ? 'C' : 'B';
$grpcode = $para == 'C' ? '002' : '001';
$formname = $para == 'C' ? 'Cash Book' : 'Bank Book';
$mainfile = 'bankbook.php?para=' . $para;

// ── Account list for this group ──────────────────────────────────────────────
$acclist = [];
$ares = mysqli_query($conn, "SELECT `accode`,`name`,`openbal`,`dc`,`currency` FROM `accmast` WHERE `grpcode`='$grpcode' ORDER BY `name` ASC") or die(mysqli_error($conn));
while ($r = mysqli_fetch_assoc($ares)) { $acclist[] = $r; }

// ── Filters ───────────────────────────────────────────────────────────────
$accode = isset($_GET['accode']) ? (int)$_GET['accode'] : (count($acclist) ? (int)$acclist[0]['accode'] : 0);
$from   = isset($_GET['from'])   ? trim($_GET['from'])   : '';
$to     = isset($_GET['to'])     ? trim($_GET['to'])     : '';

function d2sql($d) {
    if ($d != '' && preg_match('/^(\d{2})-(\d{2})-(\d{4})$/', $d, $m)) {
        return $m[3] . '-' . $m[2] . '-' . $m[1];
    }
    return '';
}
$fromsql = d2sql($from);
$tosql   = d2sql($to);

// ── Account info (opening balance) ────────────────────────────────────────────
$accinfo = ['name'=>'', 'openbal'=>0, 'dc'=>'D', 'currency'=>'INR'];
foreach ($acclist as $a) {
    if ((int)$a['accode'] == $accode) {
        $accinfo = $a;
        break;
    }
}
// signedOpenBal: negative = Dr, positive = Cr (matches actran amount convention)
$signedOpenBal = ($accinfo['dc'] == 'D') ? -1 * (float)$accinfo['openbal'] : (float)$accinfo['openbal'];

// ── Opening balance as of "from" date: openbal + all postings before from date ──
$openingBal = $signedOpenBal;
if ($accode > 0 && $fromsql != '') {
    $oqRes = mysqli_query($conn, "SELECT SUM(`amount`) AS s FROM `actran` WHERE `accode`='$accode' AND `vouchdt` < '" . mysqli_real_escape_string($conn, $fromsql) . "'") or die(mysqli_error($conn));
    $oqRow = mysqli_fetch_assoc($oqRes);
    $openingBal += (float)($oqRow['s'] ?? 0);
}

// ── Transactions in range ──────────────────────────────────────────────────────
$where = ["`accode`='$accode'"];
if ($fromsql != '') $where[] = "`vouchdt` >= '" . mysqli_real_escape_string($conn, $fromsql) . "'";
if ($tosql   != '') $where[] = "`vouchdt` <= '" . mysqli_real_escape_string($conn, $tosql)   . "'";
$whereSql = "WHERE " . implode(' AND ', $where);

$rows = [];
if ($accode > 0) {
    $sql = "SELECT * FROM `actran` $whereSql ORDER BY `vouchdt` ASC, `srl` ASC";
    $result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
    while ($r = mysqli_fetch_assoc($result)) { $rows[] = $r; }
}

// ── Source label / voucher file mapping ────────────────────────────────────────
$sourceMap = [
    'BR' => ['label' => 'Bank Receipt', 'file' => 'bankrecp.php'],
    'BP' => ['label' => 'Bank Payment', 'file' => 'bankpay.php'],
    'CR' => ['label' => 'Cash Receipt', 'file' => 'cashrecp.php'],
    'CP' => ['label' => 'Cash Payment', 'file' => 'cashpay.php'],
];

function pf($v) {
    $v = (float)$v;
    return $v == 0 ? '' : number_format($v, 2);
}
function balstr($v) {
    $v = (float)$v;
    if (abs($v) < 0.005) return '0.00';
    return number_format(abs($v), 2) . ' ' . ($v < 0 ? 'Dr' : 'Cr');
}

// ── Build running balance rows ──────────────────────────────────────────────────
$running = $openingBal;
$totDr = 0; $totCr = 0;
$displayRows = [];
foreach ($rows as $r) {
    $amt = (float)$r['amount'];
    $dr = $amt < 0 ? abs($amt) : 0;
    $cr = $amt > 0 ? $amt : 0;
    $totDr += $dr;
    $totCr += $cr;
    $running += $amt;
    $displayRows[] = [
        'vouchdt' => $r['vouchdt'],
        'vouchno' => $r['vouchno'],
        'source'  => $r['source'],
        'narr'    => $r['narr'],
        'dr'      => $dr,
        'cr'      => $cr,
        'balance' => $running,
    ];
}

// ── CSV Export ───────────────────────────────────────────────────────────
if (isset($_GET['export']) && $_GET['export'] == 'csv') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . ($para == 'C' ? 'cash_book' : 'bank_book') . '.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Date','Voucher No','Type','Narration','Debit','Credit','Balance']);
    fputcsv($out, ['','','','Opening Balance','','', balstr($openingBal)]);
    foreach ($displayRows as $r) {
        fputcsv($out, [
            $r['vouchdt'] != '0000-00-00' ? date('d-m-Y', strtotime($r['vouchdt'])) : '',
            $r['vouchno'],
            $sourceMap[$r['source']]['label'] ?? $r['source'],
            $r['narr'],
            number_format($r['dr'], 2, '.', ''),
            number_format($r['cr'], 2, '.', ''),
            balstr($r['balance']),
        ]);
    }
    fputcsv($out, ['','','','Total', number_format($totDr,2,'.',''), number_format($totCr,2,'.',''), balstr($running)]);
    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-body { padding:18px 20px; }

    .filter-bar {
        display:flex; flex-wrap:wrap; gap:10px; align-items:end;
        padding:14px; background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; margin-bottom:16px;
    }
    .filter-bar .fg { display:flex; flex-direction:column; gap:4px; }
    .filter-bar .fg.fg-wide { flex:1; min-width:220px; }
    .filter-bar label { font-size:10.5px; font-weight:700; text-transform:uppercase; letter-spacing:.05em; color:#94a3b8; }
    .filter-bar input, .filter-bar select {
        padding:7px 10px; border:1px solid #e2e8f0; border-radius:6px; font-size:12.5px;
        background:#fff; outline:none; min-width:120px;
    }
    .filter-bar input:focus, .filter-bar select:focus { border-color:#3b82f6; }

    .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-primary { background:#2563eb; color:#fff; }
    .btn-primary:hover { background:#1d4ed8; }
    .btn-export { background:#16a34a; color:#fff; }
    .btn-export:hover { background:#15803d; }

    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:9px 10px;
        border-bottom:2px solid #e2e8f0; text-align:left; white-space:nowrap;
    }
    table.reg th.num { text-align:right; }
    table.reg td { padding:7px 10px; border-bottom:1px solid #f1f5f9; white-space:nowrap; }
    table.reg td.num { text-align:right; }
    .num { text-align:right; }
    table.reg tbody tr.clickable { cursor:pointer; }
    table.reg tbody tr.clickable:hover { background:#eff6ff; }
    table.reg tfoot td { font-weight:700; background:#f8fafc; border-top:2px solid #e2e8f0; }
    table.reg tr.openrow td { background:#fef9c3; font-weight:600; }
    table.reg tr.closerow td { background:#dbeafe; font-weight:700; border-top:2px solid #e2e8f0; }

    .reg-wrap { overflow:auto; border:1px solid #e2e8f0; border-radius:8px; }
    .badge-cur { font-size:10.5px; background:#f1f5f9; color:#64748b; border-radius:20px; padding:3px 10px; font-weight:600; margin-left:8px; }
</style>

<body>
<div class="sim-card">
    <div class="sim-card-header">
        <h2>
            <i class="fa fa-<?php echo $para=='C' ? 'coins' : 'landmark'; ?>" style="color:#3b82f6;margin-right:8px;font-size:14px;"></i><?php echo $formname; ?>
            <?php if ($accinfo['currency']): ?><span class="badge-cur"><?php echo htmlspecialchars($accinfo['currency']); ?></span><?php endif; ?>
        </h2>
        <a href="?<?php echo $_SERVER['QUERY_STRING'] ? $_SERVER['QUERY_STRING'] . '&' : ''; ?>export=csv" class="btn btn-export">
            <i class="fa fa-file-csv"></i> Export CSV
        </a>
    </div>

    <div class="sim-body">

        <form method="GET" class="filter-bar">
            <input type="hidden" name="para" value="<?php echo htmlspecialchars($para); ?>">
            <div class="fg fg-wide">
                <label><?php echo $para=='C' ? 'Cash Account' : 'Bank Account'; ?></label>
                <select name="accode" class="select2" style="width:100%;" onchange="this.form.submit()">
                    <?php if (count($acclist) == 0): ?>
                    <option value="0">-- No Accounts Found --</option>
                    <?php else: foreach ($acclist as $a): ?>
                    <option value="<?php echo (int)$a['accode']; ?>" <?php echo ($a['accode']==$accode)?'selected':''; ?>>
                        <?php echo htmlspecialchars($a['name']); ?> (<?php echo htmlspecialchars($a['currency']); ?>)
                    </option>
                    <?php endforeach; endif; ?>
                </select>
            </div>
            <div class="fg">
                <label>From Date</label>
                <input type="text" name="from" class="datepick" placeholder="dd-mm-yyyy" value="<?php echo htmlspecialchars($from); ?>">
            </div>
            <div class="fg">
                <label>To Date</label>
                <input type="text" name="to" class="datepick" placeholder="dd-mm-yyyy" value="<?php echo htmlspecialchars($to); ?>">
            </div>
            <div class="fg">
                <label>&nbsp;</label>
                <button type="submit" class="btn btn-primary"><i class="fa fa-filter"></i> Filter</button>
            </div>
            <?php if ($from || $to): ?>
            <div class="fg">
                <label>&nbsp;</label>
                <a href="<?php echo $mainfile . '&accode=' . $accode; ?>" class="btn" style="background:#e2e8f0;color:#64748b;"><i class="fa fa-times"></i> Clear</a>
            </div>
            <?php endif; ?>
        </form>

        <div class="reg-wrap">
        <table class="reg">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Voucher No</th>
                    <th>Type</th>
                    <th>Narration</th>
                    <th class="num">Debit</th>
                    <th class="num">Credit</th>
                    <th class="num">Balance</th>
                </tr>
            </thead>
            <tbody>
                <tr class="openrow">
                    <td colspan="4" style="text-align:right;">Opening Balance</td>
                    <td></td>
                    <td></td>
                    <td class="num"><?php echo balstr($openingBal); ?></td>
                </tr>
                <?php if (count($displayRows) == 0): ?>
                <tr><td colspan="7" style="text-align:center;padding:24px;color:#94a3b8;">No transactions found.</td></tr>
                <?php else: foreach ($displayRows as $r):
                    $src = $sourceMap[$r['source']] ?? ['label'=>$r['source'],'file'=>''];
                ?>
                <tr class="<?php echo $src['file'] ? 'clickable' : ''; ?>"
                    <?php if ($src['file']): ?>onclick="window.open('<?php echo $src['file']; ?>?mode=edit&vouchno=<?php echo $r['vouchno']; ?>','_blank')"<?php endif; ?>>
                    <td><?php echo $r['vouchdt'] != '0000-00-00' ? date('d-m-Y', strtotime($r['vouchdt'])) : ''; ?></td>
                    <td style="font-weight:600;color:#2563eb;"><?php echo $r['vouchno']; ?></td>
                    <td><?php echo htmlspecialchars($src['label']); ?></td>
                    <td><?php echo htmlspecialchars($r['narr']); ?></td>
                    <td class="num"><?php echo pf($r['dr']); ?></td>
                    <td class="num"><?php echo pf($r['cr']); ?></td>
                    <td class="num"><?php echo balstr($r['balance']); ?></td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
            <?php if (count($displayRows) > 0): ?>
            <tfoot>
                <tr>
                    <td colspan="4" style="text-align:right;">Total (<?php echo count($displayRows); ?> entries)</td>
                    <td class="num"><?php echo pf($totDr); ?></td>
                    <td class="num"><?php echo pf($totCr); ?></td>
                    <td></td>
                </tr>
                <tr class="closerow">
                    <td colspan="6" style="text-align:right;">Closing Balance</td>
                    <td class="num"><?php echo balstr($running); ?></td>
                </tr>
            </tfoot>
            <?php endif; ?>
        </table>
        </div>

    </div>
</div>

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