<?php
$page_title = 'Payment Ledger';
require_once __DIR__ . '/header.php';

$ledgers = $db->query("SELECT * FROM dealer_ledgers WHERE dealer_id={$dealer['id']} ORDER BY date DESC, id DESC")->fetchAll();
?>

<div class="card" style="display:flex;justify-content:space-between;align-items:center;background:linear-gradient(135deg, #0f172a, #1e293b);color:#fff;">
  <div>
    <h3 style="margin:0 0 8px;font-family:'Outfit';color:#e2e8f0;">Outstanding Balance</h3>
    <div style="font-size:2rem;font-weight:700;color:<?= $dealer['outstanding_balance'] > 0 ? '#fca5a5' : '#86efac' ?>">
      ₹<?= number_format($dealer['outstanding_balance'], 2) ?>
    </div>
  </div>
  <div style="text-align:right;">
    <p style="margin:0 0 8px;color:#94a3b8;font-size:.9rem;">Credit Limit</p>
    <div style="font-size:1.2rem;font-weight:600;">₹<?= number_format($dealer['credit_limit'], 2) ?></div>
  </div>
</div>

<div class="card">
  <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
    <h3 style="margin:0;color:#0f172a;">Ledger Transactions</h3>
    <button onclick="window.print()" class="btn-primary" style="background:#e2e8f0;color:#0f172a;padding:6px 12px;font-size:.85rem;"><i class="fas fa-print"></i> Print Statement</button>
  </div>
  
  <div class="table-wrap" style="margin-top:0;">
    <table>
      <thead>
        <tr>
          <th>Date</th>
          <th>Description</th>
          <th>Ref ID</th>
          <th style="text-align:right;">Debit (Dr)</th>
          <th style="text-align:right;">Credit (Cr)</th>
          <th style="text-align:right;">Balance</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($ledgers as $l): ?>
        <tr>
          <td><?= date('d M Y', strtotime($l['date'])) ?></td>
          <td><?= h($l['description']) ?></td>
          <td style="color:#64748b;font-size:.85rem;"><?= $l['reference_id'] ? '#'.$l['reference_id'] : '-' ?></td>
          <td style="text-align:right;color:#dc2626;font-weight:600;">
            <?= $l['type']==='debit' ? '₹'.number_format($l['amount'],2) : '-' ?>
          </td>
          <td style="text-align:right;color:#059669;font-weight:600;">
            <?= $l['type']==='credit' ? '₹'.number_format($l['amount'],2) : '-' ?>
          </td>
          <td style="text-align:right;font-weight:700;color:#0f172a;">
            ₹<?= number_format($l['balance'], 2) ?>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if(!$ledgers): ?>
        <tr><td colspan="6" style="text-align:center;padding:30px;color:#64748b;">No transactions found in your ledger.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<style>
  @media print {
    body * { visibility: hidden; }
    .card, .card * { visibility: visible; }
    .card { position: absolute; left: 0; top: 0; width: 100%; box-shadow:none;border:none;}
    button { display: none !important; }
  }
</style>

<?php require_once __DIR__ . '/footer.php'; ?>
