<?php
include_once('../header.php');
if (!check_login()) {
  header("Location: " . WEB_URL . "logout.php");
  die();
}

if ($_SERVER["REQUEST_METHOD"] !== "POST" || !isset($_POST["tenant_id"])) {
  header("Location: " . WEB_URL . "tenant/tenantlist.php");
  exit;
}

/* ------- Fetch tenant -------- */
$tenantId = (int)($_POST["tenant_id"] ?? 0);
$tq = mysqli_query($link, "SELECT * FROM tenants WHERE tid = $tenantId LIMIT 1");
if (!$tq || mysqli_num_rows($tq) === 0) {
  header("Location: " . WEB_URL . "tenant/tenantlist.php");
  exit;
}
$tenant = mysqli_fetch_assoc($tq);

/* ------- Fetch transactions -------- */
$rows = [];
$tx = mysqli_query($link, "SELECT * FROM tenant_accounts WHERE tid = $tenantId ORDER BY created_at ASC");
while ($r = mysqli_fetch_assoc($tx)) { $rows[] = $r; }

/* ------- Running totals (keep original DR/CR mapping) --------
   Original logic in your code:
   - If trans_type == "credit" -> show under "Debit" and add to $tDebit
   - If trans_type == "debit"  -> show under "Credit" and add to $tCredit
   - Balance = tDebit - tCredit
--------------------------------------------------------------*/
$tDebit = 0.0;   // shows in "Debit" column when trans_type == "credit"
$tCredit = 0.0;  // shows in "Credit" column when trans_type == "debit"
$balance = 0.0;

$CURRENCY = isset($global_currency) && $global_currency !== '' ? $global_currency : '$';
?>
<!-- Page header -->
<section class="content-header">
  <h1 style="font-weight:800;margin-bottom:8px;">
    <i class="fa fa-file-text-o"></i> Tenant Account Statement
  </h1>
  <ol class="breadcrumb">
    <li><a href="<?= WEB_URL?>dashboard.php"><i class="fa fa-dashboard"></i> <?= $_data['home_breadcam']; ?></a></li>
    <li class="active">Tenant Account Statement</li>
  </ol>
</section>

<!-- Friendly styles -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
<style>
  :root{
    --ink-1:#0f172a; --ink-2:#334155; --muted:#64748b;
    --soft:#f8fafc; --line:#e2e8f0; --brand:#2563eb;
    --ok:#16a34a; --warn:#d97706; --danger:#dc2626;
    --chip:#f1f5f9;
  }
  .content-wrapper, .box, .table, .btn, label { font-family: 'Inter', system-ui, Segoe UI, Roboto, Helvetica, Arial; }
  .box.box-success{
    border:0; border-radius:16px; overflow:hidden;
    box-shadow:0 14px 36px rgba(2,6,23,.12);
  }
  .box.box-success .box-header{
    background: linear-gradient(135deg, #eaf2ff, #f8fafc);
    border-bottom:1px solid var(--line);
  }
  .box-title{ font-weight:800; color:var(--ink-1); letter-spacing:.2px; }

  /* Tenant header */
  .tenant-card{
    display:flex; align-items:center; gap:16px; padding:12px 4px 4px;
  }
  .tenant-avatar{
    width:56px; height:56px; border-radius:12px; object-fit:cover;
    box-shadow:0 8px 24px rgba(2,6,23,.15);
  }
  .tenant-name{ font-weight:800; color:var(--ink-1); font-size:18px; line-height:1.2; }
  .tenant-contact{ color:var(--muted); font-size:12px; }

  /* Table */
  .ledger-table{
    border:1px solid var(--line);
    border-radius:12px; overflow:hidden;
  }
  .ledger-table thead th{
    background:#f1f5f9; color:#0f172a; font-weight:700;
    border-bottom:1px solid var(--line);
  }
  .ledger-table tbody td{
    vertical-align: middle;
  }
  .ledger-table tfoot th{
    background:#f8fafc; border-top:2px solid var(--line);
    font-weight:800; color:#0f172a;
  }
  .desc-chip{
    display:inline-flex; align-items:center; gap:8px;
    background:var(--chip); border:1px solid var(--line);
    padding:6px 10px; border-radius:999px; font-weight:600; font-size:12px;
  }
  .desc-chip i{ color:#475569; }
  .amount{
    font-weight:700;
  }
  .amount.debit{ color:#0f172a; }
  .amount.credit{ color:#0f172a; }
  .balance-pos{ color:var(--ok); font-weight:800; }
  .balance-neg{ color:var(--danger); font-weight:800; }

  .pill{
    display:inline-block; padding:2px 8px; border-radius:999px; font-size:11px; font-weight:700;
    border: 1px solid var(--line); background:#fff;
  }
  .pill.credit{ background:#e2fbe8; color:#065f46; border-color:#bbf7d0; }
  .pill.debit{ background:#fee2e2; color:#991b1b; border-color:#fecaca; }
</style>

<section class="content">
  <div class="row">
    <div class="col-xs-12">

      <div class="box box-success">
        <div class="box-header">
          <div class="tenant-card">
            <?php
              $img = WEB_URL . 'img/no_image.jpg';
              if (!empty($tenant['image']) && file_exists(ROOT_PATH . '/img/upload/' . $tenant['image'])) {
                $img = WEB_URL . 'img/upload/' . $tenant['image'];
              }
            ?>
            <img class="tenant-avatar" src="<?= $img; ?>" alt="Tenant photo">
            <div>
              <div class="tenant-name"><?= htmlspecialchars($tenant["r_name"]); ?></div>
              <div class="tenant-contact">
                <i class="fa fa-envelope-o"></i> <?= htmlspecialchars($tenant["r_email"]); ?>
                &nbsp;&middot;&nbsp;
                <i class="fa fa-phone"></i> <?= htmlspecialchars($tenant["r_contact"]); ?>
              </div>
            </div>
          </div>
          <h3 class="box-title" style="margin-top:8px;">Account Statement</h3>
        </div>

        <div class="box-body">
          <div class="table-responsive ledger-table">
            <table class="table table-bordered table-striped dt-responsive">
              <thead>
                <tr>
                  <th style="min-width:130px;">Date</th>
                  <th>Description</th>
                  <th style="width:150px; text-align:right;">Debit </th>
                  <th style="width:150px; text-align:right;">Credit </th>
                  <th style="width:160px; text-align:right;">Balance </th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($rows)): ?>
                  <tr>
                    <td colspan="5" class="text-center text-muted">No transactions yet.</td>
                  </tr>
                <?php else: ?>
                  <?php foreach ($rows as $row): ?>
                    <?php
                      // Pretty date
                      $d = !empty($row['created_at']) ? date('jS M, Y', strtotime($row['created_at'])) : '';

                      // Display chips in description
                      $type = strtolower(trim($row['trans_type'] ?? ''));
                      $isCredit = ($type === 'credit'); // maps to Debit column per original logic
                      $isDebit  = ($type === 'debit');  // maps to Credit column per original logic

                      $debitAmt  = $isCredit ? (float)$row["transaction_amt"] : 0.0; // show under Debit
                      $creditAmt = $isDebit  ? (float)$row["transaction_amt"] : 0.0; // show under Credit

                      $tDebit  += $debitAmt;
                      $tCredit += $creditAmt;
                      $balance  = $tDebit - $tCredit;
                    ?>
                    <tr>
                      <td><?= htmlspecialchars($d); ?></td>
                      <td>
                        <span class="desc-chip" title="Transaction type">
                          <i class="fa <?= $isCredit ? 'fa-plus-circle' : 'fa-minus-circle'; ?>"></i>
                          <?= htmlspecialchars($row['description']); ?>
                          <span class="pill <?= $isCredit ? 'credit' : 'debit' ?>"><?= strtoupper($type ?: '-') ?></span>
                        </span>
                      </td>
                      <td style="text-align:right;">
                        <?= $debitAmt ? '<span class="amount debit">'.number_format($debitAmt, 2).'</span>' : '<span class="text-muted">—</span>'; ?>
                      </td>
                      <td style="text-align:right;">
                        <?= $creditAmt ? '<span class="amount credit">'.number_format($creditAmt, 2).'</span>' : '<span class="text-muted">—</span>'; ?>
                      </td>
                      <td style="text-align:right;">
                        <span class="<?= ($balance >= 0 ? 'balance-pos' : 'balance-neg'); ?>">
                          <?= number_format($balance, 2); ?>
                        </span>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
              <tfoot>
                <tr>
                  <th></th>
                  <th style="text-align:right;">Totals</th>
                  <th style="text-align:right;"><?= number_format($tDebit, 2); ?></th>
                  <th style="text-align:right;"><?= number_format($tCredit, 2); ?></th>
                  <th style="text-align:right;">
                    <span class="<?= ($balance >= 0 ? 'balance-pos' : 'balance-neg'); ?>">
                      <?= number_format($balance, 2); ?>
                    </span>
                  </th>
                </tr>
              </tfoot>
            </table>
          </div>

          <!-- Optional quick actions -->
          <div class="text-right" style="margin-top:10px;">
            <a href="<?= WEB_URL; ?>tenant/tenantlist.php" class="btn btn-default" style="border-radius:10px;">
              <i class="fa fa-reply"></i> Back to Tenants
            </a>
            <button class="btn btn-primary" style="border-radius:10px;" onclick="window.print();">
              <i class="fa fa-print"></i> Print
            </button>
          </div>
        </div>
      </div>

    </div>
  </div>
</section>

<script>
  // fade alerts if any exist on page
  $(function(){
    setTimeout(function(){ $("#me, #you").fadeOut(300); }, 3000);
  });
</script>

<?php include_once('../footer.php'); ?>
