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

$formname = 'Cash Register';

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

// ── Inputs from filter form ──────────────────────────────────────────────
$cashac = isset($_POST['cashac']) ? (int)$_POST['cashac'] : 0;
$party  = isset($_POST['party'])  ? (int)$_POST['party']  : 0;
$vtype  = isset($_POST['vtype'])  ? trim($_POST['vtype']) : '';
$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=cashreg.php");
    exit;
}
if ($mtodate == '') {
    browse("To Date Cannot Be Empty");
    header("refresh:1; url=cashreg.php");
    exit;
}

$cashcond  = ($cashac > 0) ? " AND `cashac`='$cashac' " : '';
$partycond = ($party > 0)  ? " AND `accode`='$party' "  : '';

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

// ── Build unified rows from cashrecp (CR) and cashpay (CP) ───────────────────
$rows = [];
if ($vtype == '' || $vtype == 'CR') {
    $r = mysqli_query($conn, "SELECT 'CR' AS vtype, `vouchno`,`vouchdt`,`accode`,`cashac`,`currency`,`amount`,`narr`
                               FROM `cashrecp` WHERE `vouchdt` >= '$mfrmdate' AND `vouchdt` <= '$mtodate' $cashcond $partycond") or die(mysqli_error($conn));
    while ($row = mysqli_fetch_assoc($r)) { $rows[] = $row; }
}
if ($vtype == '' || $vtype == 'CP') {
    $r = mysqli_query($conn, "SELECT 'CP' AS vtype, `vouchno`,`vouchdt`,`accode`,`cashac`,`currency`,`amount`,`narr`
                               FROM `cashpay` WHERE `vouchdt` >= '$mfrmdate' AND `vouchdt` <= '$mtodate' $cashcond $partycond") or die(mysqli_error($conn));
    while ($row = mysqli_fetch_assoc($r)) { $rows[] = $row; }
}
usort($rows, function($a, $b) {
    $c = strcmp($a['vouchdt'], $b['vouchdt']);
    return $c !== 0 ? $c : ($a['vouchno'] - $b['vouchno']);
});

// ── Resolve account names ────────────────────────────────────────────────
$accNames = [];
function accname($conn, &$cache, $accode) {
    $accode = (int)$accode;
    if ($accode <= 0) return '';
    if (isset($cache[$accode])) return $cache[$accode];
    $r = mysqli_query($conn, "SELECT `name` FROM `accmast` WHERE `accode`='$accode'");
    $row = $r ? mysqli_fetch_assoc($r) : null;
    return $cache[$accode] = $row ? $row['name'] : '';
}

$vtypeLabel = ['CR' => 'Receipt', 'CP' => 'Payment'];

$totRecp = 0; $totPay = 0;
foreach ($rows as &$row) {
    $row['cashname']  = accname($conn, $accNames, $row['cashac']);
    $row['partyname'] = accname($conn, $accNames, $row['accode']);
    $row['mydt'] = $row['vouchdt'] != '0000-00-00' ? date('d-m-Y', strtotime($row['vouchdt'])) : '';
    if ($row['vtype'] == 'CR') $totRecp += (float)$row['amount'];
    else $totPay += (float)$row['amount'];
}
unset($row);

$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="Cash_Register_' . $suffix . '_' . date('d-m-Y') . '.csv"');
    $out = fopen('php://output', 'w');
    if ($dtype == '2') {
        fputcsv($out, ['Sr','Type','Voucher No','Date','Cash A/c','Party','Currency','Amount','Narration']);
    } else {
        fputcsv($out, ['Sr','Type','Voucher No','Date','Cash A/c','Party','Amount']);
    }
    $ctr = 0;
    foreach ($rows as $row) {
        $ctr++;
        if ($dtype == '2') {
            fputcsv($out, [$ctr, $vtypeLabel[$row['vtype']], $row['vouchno'], $row['mydt'], $row['cashname'], $row['partyname'], $row['currency'], number_format((float)$row['amount'],2,'.',''), $row['narr']]);
        } else {
            fputcsv($out, [$ctr, $vtypeLabel[$row['vtype']], $row['vouchno'], $row['mydt'], $row['cashname'], $row['partyname'], number_format((float)$row['amount'],2,'.','')]);
        }
    }
    fputcsv($out, []);
    fputcsv($out, ['', '', '', '', '', 'Total Receipt', number_format($totRecp,2,'.','')]);
    fputcsv($out, ['', '', '', '', '', 'Total Payment', number_format($totPay,2,'.','')]);
    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:#3a4547; }

    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 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; }
    .pill { font-size:10.5px; font-weight:700; border-radius:20px; padding:2px 9px; color:#fff; display:inline-block; }
    .pill-recp { background:#16a34a; }
    .pill-pay  { background:#dc2626; }
    .reg-wrap { overflow:auto; }

    @media print {
        .no-print { display:none !important; }
        body { padding:0; }
        table.reg tbody tr.clickable:hover { background:none; }
    }
</style>

<body>
<div class="sim-card">
    <div class="sim-card-header">
        <div>
            <h2><i class="fa fa-coins" 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">
    <div class="reg-wrap">
    <table class="reg">
        <thead>
            <tr>
                <th>Sr</th>
                <th>Type</th>
                <th>Voucher No</th>
                <th>Date</th>
                <th>Cash A/c</th>
                <th>Party</th>
                <?php if ($dtype == '2'): ?>
                <th>Narration</th>
                <?php endif; ?>
                <th class="num">Amount</th>
            </tr>
        </thead>
        <tbody>
            <?php if (count($rows) == 0): ?>
            <tr><td colspan="<?php echo $dtype=='2' ? 8 : 7; ?>" style="text-align:center;padding:24px;color:#94a3b8;">No records found.</td></tr>
            <?php else: $ctr = 0; foreach ($rows as $row): $ctr++;
                $file = $row['vtype'] == 'CR' ? 'cashrecp.php' : 'cashpay.php';
                $pillcls = $row['vtype'] == 'CR' ? 'pill-recp' : 'pill-pay';
            ?>
            <tr class="clickable" onclick="window.open('<?php echo $file; ?>?mode=edit&vouchno=<?php echo $row['vouchno']; ?>','_blank')">
                <td style="text-align:center;"><?php echo $ctr; ?></td>
                <td style="text-align:center;"><span class="pill <?php echo $pillcls; ?>"><?php echo $vtypeLabel[$row['vtype']]; ?></span></td>
                <td style="color:#2563eb;font-weight:600;"><?php echo $row['vouchno']; ?></td>
                <td><?php echo $row['mydt']; ?></td>
                <td><?php echo htmlspecialchars($row['cashname']); ?></td>
                <td><?php echo htmlspecialchars($row['partyname']); ?></td>
                <?php if ($dtype == '2'): ?>
                <td><?php echo htmlspecialchars($row['narr']); ?></td>
                <?php endif; ?>
                <td class="num"><?php echo pf($row['amount']); ?></td>
            </tr>
            <?php endforeach; endif; ?>
        </tbody>
        <?php if (count($rows) > 0): ?>
        <tfoot>
            <tr>
                <td colspan="<?php echo $dtype=='2' ? 6 : 5; ?>" style="text-align:right;">Total Receipt</td>
                <td></td>
                <td class="num"><?php echo pf($totRecp); ?></td>
            </tr>
            <tr>
                <td colspan="<?php echo $dtype=='2' ? 6 : 5; ?>" style="text-align:right;">Total Payment</td>
                <td></td>
                <td class="num"><?php echo pf($totPay); ?></td>
            </tr>
        </tfoot>
        <?php endif; ?>
    </table>
    </div>
    </div>
</div>

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