<?php
require_once '../includes/auth.php';
require_once '../db.php';
require_once '../includes/company.php';

$vendor_id = intval($_GET['vendor_id'] ?? 0);
$fco       = intval($_GET['co'] ?? 0);
$from_date = $_GET['from_date'] ?? '';
$to_date   = $_GET['to_date'] ?? '';
$format    = ($_GET['format'] ?? 'a4') === 'thermal' ? 'thermal' : 'a4';

if (!$vendor_id) die('Invalid vendor.');

$vendor = $conn->query("SELECT id, name, phone FROM vendors WHERE id = $vendor_id LIMIT 1")->fetch_assoc();
if (!$vendor) die('Vendor not found.');

$company = getCompany($conn, $fco > 0 ? $fco : null);

$df = $from_date !== '' ? $conn->real_escape_string($from_date) : '';
$dt = $to_date   !== '' ? $conn->real_escape_string($to_date)   : '';

$coWhere   = $fco > 0 ? "AND company_id = $fco"        : "";
$coWherePP = $fco > 0 ? "AND po2.company_id = $fco"    : "";

$poDate = ($df ? "AND po.purchase_date >= '$df'" : '') . ($dt ? " AND po.purchase_date <= '$dt'" : '');
$prDate = ($df ? "AND pr.return_date   >= '$df'" : '') . ($dt ? " AND pr.return_date   <= '$dt'" : '');
$vpDate = ($df ? "AND vp.payment_date  >= '$df'" : '') . ($dt ? " AND vp.payment_date  <= '$dt'" : '');
$ppDate = ($df ? "AND pp.payment_date  >= '$df'" : '') . ($dt ? " AND pp.payment_date  <= '$dt'" : '');

// 3-branch UNION
$result = $conn->query("
    SELECT po.purchase_date AS txn_date, 'Purchase' AS txn_type,
           po.net_amount AS debit, 0 AS credit, po.po_no AS ref_no,
           po.id AS ref_id, 'po' AS src, po.created_at AS created_at
    FROM purchase_orders po
    WHERE po.vendor_id = $vendor_id AND po.status = 'final' $coWhere $poDate

    UNION ALL

    SELECT pr.return_date AS txn_date, 'Return' AS txn_type,
           0 AS debit, pr.net_amount AS credit, pr.return_no AS ref_no,
           pr.id AS ref_id, 'pr' AS src, pr.created_at AS created_at
    FROM purchase_returns pr
    WHERE pr.vendor_id = $vendor_id AND pr.status = 'final' $coWhere $prDate

    UNION ALL

    SELECT vp.payment_date AS txn_date, 'Payment' AS txn_type,
           0 AS debit, vp.amount AS credit,
           COALESCE(NULLIF(vp.reference_no,''), vp.payment_mode) AS ref_no,
           vp.id AS ref_id, 'vp' AS src, vp.created_at AS created_at
    FROM vendor_payments vp
    WHERE vp.vendor_id = $vendor_id $coWhere $vpDate

    ORDER BY txn_date ASC, created_at ASC, src ASC
");

$totalPurchased = 0; $totalReturns = 0; $totalPaid = 0;
$transactions   = [];
while ($row = $result->fetch_assoc()) {
    if ($row['txn_type'] === 'Purchase') $totalPurchased += $row['debit'];
    if ($row['txn_type'] === 'Return')   $totalReturns   += $row['credit'];
    if ($row['txn_type'] === 'Payment')  $totalPaid      += $row['credit'];
    $transactions[] = $row;
}

// purchase_payments separate query (avoids UNION collation conflict)
try {
    $ppRes = $conn->query("
        SELECT pp.payment_date AS txn_date, 'Payment' AS txn_type,
               0 AS debit, pp.amount AS credit,
               CONCAT(po2.po_no, ' (', pp.payment_mode, ')') AS ref_no,
               pp.id AS ref_id, 'pp' AS src, pp.created_at AS created_at
        FROM purchase_payments pp
        JOIN purchase_orders po2 ON po2.id = pp.purchase_order_id
        WHERE po2.vendor_id = $vendor_id $coWherePP $ppDate
    ");
    while ($row = $ppRes->fetch_assoc()) { $totalPaid += $row['credit']; $transactions[] = $row; }
} catch (mysqli_sql_exception $e) {}

usort($transactions, function($a, $b) {
    $c = strcmp($a['txn_date'], $b['txn_date']);
    if ($c !== 0) return $c;
    $c2 = strcmp($a['created_at'] ?? '', $b['created_at'] ?? '');
    return $c2 !== 0 ? $c2 : strcmp($a['src'], $b['src']);
});

$runBal = 0;
foreach ($transactions as &$txn) {
    $runBal += $txn['debit'] - $txn['credit'];
    $txn['running_balance'] = $runBal;
}
unset($txn);

$closingBalance = $totalPurchased - $totalReturns - $totalPaid;

$dateLabel = 'All Transactions';
if ($from_date && $to_date) $dateLabel = date('d-m-Y', strtotime($from_date)) . ' to ' . date('d-m-Y', strtotime($to_date));
elseif ($from_date)         $dateLabel = 'From ' . date('d-m-Y', strtotime($from_date));
elseif ($to_date)           $dateLabel = 'Till ' . date('d-m-Y', strtotime($to_date));

$printDate = date('d-m-Y h:i A');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vendor Ledger — <?= htmlspecialchars($vendor['name']) ?></title>
<?php if ($format === 'a4'): ?>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
@page { size: A4; margin: 12mm 14mm; }
body { font-family: Arial, sans-serif; font-size: 11px; color: #1a1a1a; background: #fff; }
.no-print { display: none; }

.header { display: flex; justify-content: space-between; align-items: flex-start; border-bottom: 2px solid #1a1a1a; padding-bottom: 8px; margin-bottom: 10px; }
.company-name { font-size: 16px; font-weight: 700; margin-bottom: 3px; }
.company-sub  { font-size: 10px; color: #444; line-height: 1.6; }
.report-title { text-align: right; }
.report-title h2 { font-size: 14px; font-weight: 700; color: #1a56db; margin-bottom: 4px; }
.report-title p  { font-size: 10px; color: #555; line-height: 1.6; }

.info-bar { display: flex; justify-content: space-between; background: #f3f4f6; border-radius: 4px; padding: 7px 12px; margin-bottom: 10px; font-size: 10.5px; }
.info-bar .lbl { font-weight: 700; color: #555; margin-right: 4px; }

.summary { display: flex; gap: 8px; margin-bottom: 12px; }
.sum-box { flex: 1; border: 1px solid #e5e7eb; border-radius: 5px; padding: 7px 10px; }
.sum-box .s-label { font-size: 9px; font-weight: 700; text-transform: uppercase; letter-spacing: .4px; color: #666; margin-bottom: 3px; }
.sum-box .s-val   { font-size: 13px; font-weight: 700; }
.sum-box.pur  { border-left: 3px solid #f59e0b; } .sum-box.pur  .s-val { color: #b45309; }
.sum-box.ret  { border-left: 3px solid #10b981; } .sum-box.ret  .s-val { color: #065f46; }
.sum-box.paid { border-left: 3px solid #3b82f6; } .sum-box.paid .s-val { color: #1d4ed8; }
.sum-box.bal  { border-left: 3px solid #ef4444; } .sum-box.bal  .s-val { color: #b91c1c; }
.sum-box.bal.settled { border-left-color: #10b981; } .sum-box.bal.settled .s-val { color: #065f46; }

table { width: 100%; border-collapse: collapse; font-size: 10.5px; margin-bottom: 16px; }
thead tr { background: #1e3a5f; color: #fff; }
thead th { padding: 6px 8px; text-align: left; font-size: 9.5px; font-weight: 600; text-transform: uppercase; letter-spacing: .4px; }
thead th.r { text-align: right; }
tbody tr { border-bottom: 1px solid #e5e7eb; }
tbody tr:nth-child(even) { background: #f9fafb; }
tbody td { padding: 5px 8px; vertical-align: middle; }
tbody td.r { text-align: right; }
.type-purchase { color: #92400e; background: #fef3c7; padding: 1px 5px; border-radius: 3px; font-size: 9px; font-weight: 700; }
.type-return   { color: #065f46; background: #d1fae5; padding: 1px 5px; border-radius: 3px; font-size: 9px; font-weight: 700; }
.type-payment  { color: #1e40af; background: #dbeafe; padding: 1px 5px; border-radius: 3px; font-size: 9px; font-weight: 700; }
.debit   { color: #b91c1c; }
.credit  { color: #065f46; }
.bal-pos { color: #b91c1c; font-weight: 700; }
.bal-neg { color: #065f46; font-weight: 700; }

.footer { border-top: 1px solid #d1d5db; padding-top: 10px; display: flex; justify-content: space-between; align-items: flex-end; margin-top: 4px; }
.sig-line { border-top: 1px solid #374151; width: 140px; text-align: center; padding-top: 4px; font-size: 9.5px; color: #555; }
.closing-stmt { font-size: 11px; font-weight: 700; }
.closing-stmt span { color: <?= $closingBalance > 0 ? '#b91c1c' : '#065f46' ?>; font-size: 13px; }
</style>
<?php else: /* thermal */ ?>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
@page { size: 80mm auto; margin: 4mm 3mm; }
body { font-family: 'Courier New', monospace; font-size: 12px; font-weight: 600; color: #000; width: 74mm; background: #fff; }
.no-print { display: none; }
.center { text-align: center; }
.bold   { font-weight: 700; }
.line   { border-top: 1px dashed #000; margin: 5px 0; }
.dline  { border-top: 2px solid #000; margin: 5px 0; }
.co-name { font-size: 16px; font-weight: 700; text-align: center; }
.title   { font-size: 13px; font-weight: 700; text-align: center; margin: 3px 0; }
.row     { display: flex; justify-content: space-between; margin: 2px 0; font-size: 11px; }
.row .l  { flex: 1; }
.row .r  { text-align: right; white-space: nowrap; padding-left: 4px; }
table    { width: 100%; border-collapse: collapse; font-size: 11px; }
th       { padding: 3px 2px; text-align: left; font-weight: 700; font-size: 11px; }
td       { padding: 3px 2px; text-align: left; font-weight: 600; }
td.r, th.r { text-align: right; }
thead tr { border-bottom: 2px solid #000; }
tbody tr { border-bottom: 1px solid #888; }
.sum-row { display: flex; justify-content: space-between; font-size: 11px; margin: 2px 0; }
.sum-row.total { font-weight: 700; font-size: 13px; margin-top: 3px; }
</style>
<?php endif; ?>
</head>
<body>

<?php if ($format === 'a4'): ?>

<!-- ══ A4 LAYOUT ══ -->
<div class="header">
    <div>
        <div class="company-name"><?= htmlspecialchars($company['company_name'] ?? 'Company') ?></div>
        <div class="company-sub">
            <?= htmlspecialchars($company['address'] ?? '') ?><br>
            <?php if (!empty($company['gst_no'])): ?>GSTIN: <?= htmlspecialchars($company['gst_no']) ?> &nbsp;|&nbsp; <?php endif; ?>
            Ph: <?= htmlspecialchars($company['phone'] ?? '') ?>
        </div>
    </div>
    <div class="report-title">
        <h2>VENDOR ACCOUNT STATEMENT</h2>
        <p>Period: <?= htmlspecialchars($dateLabel) ?><br>Printed: <?= $printDate ?></p>
    </div>
</div>

<div class="info-bar">
    <div><span class="lbl">Vendor:</span><?= htmlspecialchars($vendor['name']) ?></div>
    <div><span class="lbl">Phone:</span><?= htmlspecialchars($vendor['phone'] ?: '—') ?></div>
    <div><span class="lbl">Total Transactions:</span><?= count($transactions) ?></div>
</div>

<div class="summary">
    <div class="sum-box pur">
        <div class="s-label">Total Purchased</div>
        <div class="s-val">&#8377;<?= number_format($totalPurchased, 2) ?></div>
    </div>
    <div class="sum-box ret">
        <div class="s-label">Total Returns</div>
        <div class="s-val">&#8377;<?= number_format($totalReturns, 2) ?></div>
    </div>
    <div class="sum-box paid">
        <div class="s-label">Total Paid</div>
        <div class="s-val">&#8377;<?= number_format($totalPaid, 2) ?></div>
    </div>
    <div class="sum-box bal<?= $closingBalance <= 0 ? ' settled' : '' ?>">
        <div class="s-label">Closing Balance</div>
        <div class="s-val">&#8377;<?= number_format(abs($closingBalance), 2) ?></div>
    </div>
</div>

<table>
    <thead>
        <tr>
            <th>#</th>
            <th>Date</th>
            <th>Type</th>
            <th>Reference</th>
            <th class="r">Debit (You Owe)</th>
            <th class="r">Credit (Paid/Ret.)</th>
            <th class="r">Balance</th>
        </tr>
    </thead>
    <tbody>
    <?php if (empty($transactions)): ?>
        <tr><td colspan="7" style="text-align:center;padding:16px;color:#888;">No transactions found.</td></tr>
    <?php else: $i = 1; foreach ($transactions as $txn): ?>
        <tr>
            <td style="color:#888;"><?= $i++ ?></td>
            <td><?= date('d-m-Y', strtotime($txn['txn_date'])) ?></td>
            <td>
                <?php if ($txn['txn_type'] === 'Purchase'): ?>
                    <span class="type-purchase">Purchase</span>
                <?php elseif ($txn['txn_type'] === 'Return'): ?>
                    <span class="type-return">Return</span>
                <?php else: ?>
                    <span class="type-payment">Payment</span>
                <?php endif; ?>
            </td>
            <td><?= htmlspecialchars($txn['ref_no'] ?: '—') ?></td>
            <td class="r debit"><?= $txn['debit'] > 0 ? '&#8377;'.number_format($txn['debit'], 2) : '—' ?></td>
            <td class="r credit"><?= $txn['credit'] > 0 ? '&#8377;'.number_format($txn['credit'], 2) : '—' ?></td>
            <td class="r <?= $txn['running_balance'] > 0 ? 'bal-pos' : 'bal-neg' ?>">&#8377;<?= number_format(abs($txn['running_balance']), 2) ?> <?= $txn['running_balance'] > 0 ? 'Dr' : 'Cr' ?></td>
        </tr>
    <?php endforeach; endif; ?>
    </tbody>
</table>

<div class="footer">
    <div>
        <div class="closing-stmt">
            Closing Balance: <span>&#8377;<?= number_format(abs($closingBalance), 2) ?></span>
            <?php if ($closingBalance > 0): ?>(You Owe Vendor)<?php elseif ($closingBalance < 0): ?>(Credit Balance)<?php else: ?>(Settled)<?php endif; ?>
        </div>
        <div style="font-size:9.5px;color:#777;margin-top:3px;">This is a computer generated statement.</div>
    </div>
    <div style="text-align:right;">
        <div class="sig-line">Authorised Signatory</div>
    </div>
</div>

<?php else: /* ══ THERMAL LAYOUT ══ */ ?>

<div class="co-name"><?= htmlspecialchars($company['company_name'] ?? 'Company') ?></div>
<?php if (!empty($company['phone'])): ?>
<div class="center" style="font-size:9px;">Ph: <?= htmlspecialchars($company['phone']) ?></div>
<?php endif; ?>
<div class="dline"></div>
<div class="title">VENDOR STATEMENT</div>
<div class="line"></div>

<div class="row"><span class="l bold">Vendor</span><span class="r"><?= htmlspecialchars($vendor['name']) ?></span></div>
<?php if ($vendor['phone']): ?><div class="row"><span class="l">Phone</span><span class="r"><?= htmlspecialchars($vendor['phone']) ?></span></div><?php endif; ?>
<div class="row"><span class="l">Period</span><span class="r"><?= htmlspecialchars($dateLabel) ?></span></div>
<div class="row"><span class="l">Printed</span><span class="r"><?= $printDate ?></span></div>
<div class="line"></div>

<table>
    <thead>
        <tr>
            <th>Date</th>
            <th>Type</th>
            <th>Ref</th>
            <th class="r">Dr</th>
            <th class="r">Cr</th>
            <th class="r">Bal</th>
        </tr>
    </thead>
    <tbody>
    <?php if (empty($transactions)): ?>
        <tr><td colspan="6" style="text-align:center;padding:4px;">No records.</td></tr>
    <?php else: foreach ($transactions as $txn): ?>
        <tr>
            <td><?= date('d/m/y', strtotime($txn['txn_date'])) ?></td>
            <td><?= substr($txn['txn_type'], 0, 3) ?></td>
            <td style="max-width:14mm;overflow:hidden;"><?= htmlspecialchars(substr($txn['ref_no'] ?: '—', 0, 10)) ?></td>
            <td class="r"><?= $txn['debit'] > 0 ? number_format($txn['debit'], 0) : '—' ?></td>
            <td class="r"><?= $txn['credit'] > 0 ? number_format($txn['credit'], 0) : '—' ?></td>
            <td class="r" style="font-weight:<?= $txn['running_balance'] > 0 ? '700' : '400' ?>;"><?= number_format(abs($txn['running_balance']), 0) ?><?= $txn['running_balance'] > 0 ? 'D' : 'C' ?></td>
        </tr>
    <?php endforeach; endif; ?>
    </tbody>
</table>
<div class="dline"></div>

<div class="sum-row"><span>Total Purchased</span><span>&#8377;<?= number_format($totalPurchased, 2) ?></span></div>
<div class="sum-row"><span>Total Returns</span><span>&#8377;<?= number_format($totalReturns, 2) ?></span></div>
<div class="sum-row"><span>Total Paid</span><span>&#8377;<?= number_format($totalPaid, 2) ?></span></div>
<div class="line"></div>
<div class="sum-row total">
    <span>BALANCE DUE</span>
    <span>&#8377;<?= number_format(abs($closingBalance), 2) ?> <?= $closingBalance > 0 ? 'Dr' : ($closingBalance < 0 ? 'Cr' : '') ?></span>
</div>
<div class="dline"></div>
<div class="center" style="font-size:9px;margin-top:4px;">Thank you for your business</div>

<?php endif; ?>

</body>
</html>
