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

$formname = 'Contra Register';

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

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

$acccond = ($acc > 0) ? " AND (`fromac`='$acc' OR `toac`='$acc') " : '';

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

$getmain = mysqli_query($conn, "SELECT m.*, a.`name` AS fromname, b.`name` AS toname,
                                        DATE_FORMAT(m.`vouchdt`,'%d-%m-%Y') AS mydt
                                 FROM `contra` m
                                 LEFT JOIN `accmast` a ON a.`accode` = m.`fromac`
                                 LEFT JOIN `accmast` b ON b.`accode` = m.`toac`
                                 WHERE m.`vouchdt` >= '$mfrmdate' AND m.`vouchdt` <= '$mtodate'
                                 $acccond
                                 ORDER BY m.`vouchdt` ASC, m.`vouchno` ASC") or die(mysqli_error($conn));

$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="Contra_Register_' . $suffix . '_' . date('d-m-Y') . '.csv"');
    $out = fopen('php://output', 'w');
    if ($dtype == '2') {
        fputcsv($out, ['Sr','Voucher No','Date','From','To','Cheque No','Cheque Date','Amount','Narration']);
    } else {
        fputcsv($out, ['Sr','Voucher No','Date','From','To','Amount']);
    }
    $ctr = 0; $ttotamt = 0;
    while ($row = mysqli_fetch_array($getmain)) {
        $ctr++;
        $chqdt = (!empty($row['chqdt']) && $row['chqdt'] != '0000-00-00') ? date('d-m-Y', strtotime($row['chqdt'])) : '';
        if ($dtype == '2') {
            fputcsv($out, [$ctr, $row['vouchno'], $row['mydt'], $row['fromname'], $row['toname'], $row['chqno'], $chqdt, number_format((float)$row['amount'],2,'.',''), $row['narr']]);
        } else {
            fputcsv($out, [$ctr, $row['vouchno'], $row['mydt'], $row['fromname'], $row['toname'], number_format((float)$row['amount'],2,'.','')]);
        }
        $ttotamt += (float)$row['amount'];
    }
    fputcsv($out, []);
    fputcsv($out, ['', '', '', '', 'Grand Total', number_format($ttotamt,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:#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; }
    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; }
    .reg-wrap { overflow:auto; }

    @media print {
        body { background:#fff; padding:0; }
        .no-print { display:none !important; }
        .sim-card { box-shadow:none; border-radius:0; }
        table.reg tbody tr.clickable:hover { background:none; }
    }
</style>
</head>
<body>
<div class="sim-card">
    <div class="sim-card-header">
        <div>
            <h2><i class="fa fa-right-left" style="color:#7c3aed;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>Voucher No</th>
                <th>Date</th>
                <th>From</th>
                <th>To</th>
                <?php if ($dtype == '2'): ?>
                <th>Cheque No</th>
                <th>Cheque Date</th>
                <th>Narration</th>
                <?php endif; ?>
                <th class="num">Amount</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $ctr = 0;
            $ttotamt = 0;
            $anyRows = false;
            while ($row = mysqli_fetch_array($getmain)) {
                $anyRows = true;
                $ctr++;
                $chqdt = (!empty($row['chqdt']) && $row['chqdt'] != '0000-00-00') ? date('d-m-Y', strtotime($row['chqdt'])) : '';
                echo "<tr class='clickable' onclick=\"window.open('contra.php?mode=edit&vouchno={$row['vouchno']}','_blank')\">";
                echo "<td style='text-align:center;'>$ctr</td>";
                echo "<td style='color:#2563eb;font-weight:600;'>CTR#{$row['vouchno']}</td>";
                echo "<td>{$row['mydt']}</td>";
                echo "<td>" . htmlspecialchars($row['fromname'] ?? '') . "</td>";
                echo "<td>" . htmlspecialchars($row['toname'] ?? '') . "</td>";
                if ($dtype == '2') {
                    echo "<td>" . htmlspecialchars($row['chqno'] ?? '') . "</td>";
                    echo "<td>" . htmlspecialchars($chqdt) . "</td>";
                    echo "<td>" . htmlspecialchars($row['narr'] ?? '') . "</td>";
                }
                echo "<td class='num'>" . pf($row['amount']) . "</td>";
                echo "</tr>";

                $ttotamt += (float)$row['amount'];
            }
            if (!$anyRows) {
                $cols = $dtype == '2' ? 8 : 6;
                echo "<tr><td colspan='$cols' style='text-align:center;padding:24px;color:#94a3b8;'>No records found.</td></tr>";
            }
            ?>
        </tbody>
        <?php if ($anyRows): ?>
        <tfoot>
            <tr>
                <td colspan="<?php echo $dtype=='2' ? 7 : 5; ?>" style="text-align:right;">Grand Total (<?php echo $ctr; ?> vouchers)</td>
                <td class="num"><?php echo pf($ttotamt); ?></td>
            </tr>
        </tfoot>
        <?php endif; ?>
    </table>
    </div>
    </div>
</div>

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