<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
set_error_handler(function($s,$m,$f,$l){ throw new ErrorException($m,0,$s,$f,$l); });

require_once __DIR__.'/../includes/db.php';
require_once __DIR__.'/../includes/auth.php';
require_once __DIR__.'/../includes/helpers.php';
require_once __DIR__.'/../includes/config.php';

require_login();

if (session_status() !== PHP_SESSION_ACTIVE) session_start();
$page_title = "Dashboard";

// flash message
$flash = $_SESSION['flash_success'] ?? '';
unset($_SESSION['flash_success']);

// Load current user
$st = $pdo->prepare("SELECT fullname, email, account_number, balance_cents FROM users WHERE id = :id");
$st->execute([':id' => $_SESSION['uid']]);
$user = $st->fetch();
if (!$user) { header('Location: ' . url('login.php')); exit; }

// Keep handy for sidebar
$_SESSION['fullname'] = $user['fullname'];
$_SESSION['email']    = $user['email'];

// CSRF token
if (empty($_SESSION['csrf'])) {
  $_SESSION['csrf'] = bin2hex(random_bytes(16));
}

// Ensure + fetch virtual card row
$cardStmt = $pdo->prepare("SELECT * FROM cards WHERE user_id=:id LIMIT 1");
$cardStmt->execute([':id'=>$_SESSION['uid']]);
$card = $cardStmt->fetch();

if (!$card) {
  $ins = $pdo->prepare("INSERT INTO cards (user_id, card_number, cvv, exp_month, exp_year, status)
                        VALUES (:uid, :num, :cvv, :m, :y, 'inactive')");
  $ins->execute([
    ':uid'=>$_SESSION['uid'],
    ':num'=>gen_card_number(),
    ':cvv'=>gen_cvv(),
    ':m'=>gen_expiry_month(),
    ':y'=>gen_expiry_year(),
  ]);
  $cardStmt->execute([':id'=>$_SESSION['uid']]);
  $card = $cardStmt->fetch();
}

// Quick stats
$txCountStmt = $pdo->prepare("SELECT COUNT(*) FROM transactions WHERE user_id = :id");
$txCountStmt->execute([':id'=>$_SESSION['uid']]);
$txCount = (int)$txCountStmt->fetchColumn();

$lastTxStmt = $pdo->prepare("SELECT kind, amount_cents, created_at FROM transactions WHERE user_id=:id ORDER BY id DESC LIMIT 1");
$lastTxStmt->execute([':id'=>$_SESSION['uid']]);
$lastTx = $lastTxStmt->fetch();

$recentStmt = $pdo->prepare("
  SELECT kind, amount_cents, balance_after_cents, reference, note, counterparty_acct, created_at
  FROM transactions
  WHERE user_id=:id
  ORDER BY id DESC
  LIMIT 5
");
$recentStmt->execute([':id'=>$_SESSION['uid']]);
$recent = $recentStmt->fetchAll();

include __DIR__.'/../includes/header.php';
?>
<head>
    <!-- Bootstrap CSS (Latest 5.x version) -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-..." crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">

</head>
<style>
/* === PIN MODAL FIXED CENTER OVERLAY === */
.pin-modal {
  display: none;
  position: fixed;
  inset: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.55);
  backdrop-filter: blur(4px);
  z-index: 9999;
  align-items: center;
  justify-content: center;
  transition: opacity 0.3s ease;
}

.pin-modal.show {
  display: flex !important;
  animation: fadeInScale 0.35s ease forwards;
}

@keyframes fadeInScale {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

/* Optional: Button hover polish */
.pin-modal button {
  transition: all 0.2s ease;
}

.pin-modal button:hover {
  transform: scale(1.05);
  opacity: 0.9;
}

#verifyPinBtn { background:#111;color:#fff; }
#cancelPinBtn { background:#ccc;color:#000; }



.mobile-bottom-nav {
    position: fixed;
    bottom: 25px;
    left: 0;
    width: 100%;
    background: #ffffff;
    border-top: 1px solid #ddd;
    display: flex;
    justify-content: space-around;
    padding: 10px 0 8px; 
    z-index: 9999;

    /* 🔥 fixes disappearing labels */
    height: 65px;
    overflow: visible;
}
.mobile-bottom-nav .nav-item span {
    display: block;
    font-size: 12px;
    line-height: 14px;  /* 🔥 prevents text cut-off */
}


.mobile-bottom-nav .nav-item {
    text-align: center;
    color: #555;
    font-size: 12px;
    text-decoration: none;
}

.mobile-bottom-nav .nav-item i {
    display: block;
    font-size: 20px;
    margin-bottom: 2px;
}

.mobile-bottom-nav .nav-item.active,
.mobile-bottom-nav .nav-item:hover {
    color: #0d6efd; /* Bootstrap blue */
}
body {
    padding-bottom: 80px; /* enough space for the bottom menu */
}


</style>




<?php if ($flash): ?>
  <div style="margin:10px 0;padding:10px;border-radius:10px;background:#0f3a16;color:#cafecf;border:1px solid #1c5a27;">
    <?= htmlspecialchars($flash, ENT_QUOTES) ?>
  </div>
<?php endif; ?>

<div class="row g-4">
  <div class="col-md-9">

    <!-- Summary cards -->
    <div class="row g-3 mb-3">

      <!-- Balance Card with Add Money -->
      <div class="col-md-4">
        <div class="card shadow-sm h-100">
          <div class="card-body d-flex flex-column justify-content-between">
            <div class="d-flex justify-content-between align-items-start">
              <div>
                <div class="text-muted small">Balance</div>
                <div class="h4 mb-1">₦<?= number_format($user['balance_cents']/100,2) ?></div>
                <div class="small text-muted">Acct: <?= sanitize($user['account_number']) ?></div>
              </div>
              <!-- Add Money Button --><br>
              <div>
                <a href="#" class="btn btn-sm btn-primary rounded-circle" title="Add Money">
                  <i class="bi bi-plus">Add money</i>
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Last Transaction Card -->
      <div class="col-md-4">
        <div class="card shadow-sm h-100">
          <div class="card-body">
            <div class="text-muted small">Last Transaction</div>
            <?php if ($lastTx): ?>
              <div class="h6 mb-1">
                <?= $lastTx['kind']==='credit' 
                    ? '<span class="badge text-bg-success">credit</span>' 
                    : '<span class="badge text-bg-danger">debit</span>' ?>
                ₦<?= number_format($lastTx['amount_cents']/100,2) ?>
              </div>
              <div class="small text-muted"><?= sanitize($lastTx['created_at']) ?></div>
            <?php else: ?>
              <div class="text-muted">No transactions yet</div>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <!-- Total Transactions Card -->
      <div class="col-md-4">
        <div class="card shadow-sm h-100">
          <div class="card-body">
            <div class="text-muted small">Total Transactions</div>
            <div class="h4 mb-0"><?= number_format($txCount) ?></div>
            <div class="small text-muted">last 200 shown on listing</div>
          </div>
        </div>
      </div>

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


    <!-- Virtual Card -->
    <div class="card shadow-sm mb-3">
      <div class="card-body">
        <?php
          $badge = ['inactive'=>'secondary','pending'=>'warning','active'=>'success'][$card['status']] ?? 'secondary';
          $num_active  = sanitize($card['card_number']);
          $num_masked  = preg_replace('/\d(?!\d{0,3}$)/', '•', $num_active);
          $exp_active  = str_pad((string)$card['exp_month'],2,'0',STR_PAD_LEFT) . '/' . $card['exp_year'];
          $exp_masked  = '**/**';
          $cvv_active  = sanitize($card['cvv']);
          $cvv_masked  = '***';
          $is_active   = ($card['status']==='active');
          $is_pending  = ($card['status']==='pending');
        ?>
        <div class="d-flex justify-content-between align-items-center mb-2">
          <h5 class="card-title mb-0">Virtual Card</h5>
          <span class="badge text-bg-<?= $badge ?> text-uppercase"><?= sanitize($card['status']) ?></span>
        </div>
        <div class="virtual-card-wrap">
          <div class="bank-card <?= $is_active ? 'is-active' : ($is_pending ? 'is-pending' : 'is-inactive') ?>">
            <div class="brand">
              <span class="dot"></span>
              <span class="word">SurexGate</span>
            </div>
            <div class="row-top">
              <div class="chip"></div>
              <svg class="wave" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 12c4-6 14-6 18 0M6 12c3-4 9-4 12 0M9 12c1.5-2 4.5-2 6 0" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>
            </div>
            <div class="number"><?= $is_active ? $num_active : $num_masked ?></div>
            <div class="meta">
              <div class="meta-box">
                <div class="label">Expiry</div>
                <div class="value"><?= $is_active ? $exp_active : $exp_masked ?></div>
              </div>
              <div class="meta-box">
                <div class="label">CVV</div>
                <div class="value"><?= $is_active ? $cvv_active : $cvv_masked ?></div>
              </div>
              <div class="meta-box holder">
                <div class="label">Cardholder</div>
                <div class="value"><?= sanitize($user['fullname']) ?></div>
              </div>
            </div>
          </div>
        </div>
        <?php if (!$is_active): ?>
          <p class="text-muted mt-2 mb-2">
            <?= $is_pending ? 'Activation requested. Waiting for admin approval.' : 'Your card is inactive. Activate to reveal details.' ?>
          </p>
          <?php if (!$is_pending): ?>
            <form method="post" action="request_card_activation.php">
              <input type="hidden" name="csrf" value="<?= $_SESSION['csrf'] ?>">
              <button class="btn btn-sm btn-dark">Activate card</button>
            </form>
          <?php endif; ?>
        <?php endif; ?>
      </div>
    </div>

    <!-- Transfer Form -->
    <form id="transferForm" method="POST" action="/public/transfer.php">
      <input type="hidden" name="csrf" value="<?= htmlspecialchars($_SESSION['csrf']) ?>">
      <div class="mb-3">
        <label class="form-label">Recipient Account Number</label>
        <input type="text" name="to_account" class="form-control" required pattern="\d{10}">
      </div>
      <div class="mb-3">
        <label class="form-label">Amount (₦)</label>
        <input type="number" step="0.01" name="amount" class="form-control" required>
      </div>
      <div class="mb-3">
        <label class="form-label">Note</label>
        <input type="text" name="note" class="form-control" maxlength="255">
      </div>
      <button type="button" class="btn btn-primary w-100" id="openPinModalBtn">Send Money</button>
    </form>

    <!-- Blocking PIN Modal -->
 <!-- Full-screen blocking PIN popup -->
<div class="pin-modal" id="pinModal">
  <div class="pin-modal-content">
    <h3>Enter Transaction PIN</h3>
<input 
  type="password" 
  id="transactionPin" 
  name="transactionPin" 
  inputmode="numeric" 
  pattern="[0-9]*" 
  maxlength="6" 
  autocomplete="off" 
  placeholder="••••••" 
  required 
/>
    <div class="pin-modal-buttons">
      <button id="cancelPinBtn">Cancel</button>
      <button id="verifyPinBtn">Verify</button>
    </div>
    <p id="pinMsg"></p>
  </div>
</div>



   <!-- Recent Activity -->
<div class="card shadow-sm mt-4">
  <div class="card-body">
    <h5 class="card-title mb-3">Recent activity</h5>
    <?php
      // Fetch extended data to include validation details
      $recentStmt = $pdo->prepare("
        SELECT id, kind, amount_cents, balance_after_cents, reference, note, validation_status, created_at
        FROM transactions
        WHERE user_id=:id
        ORDER BY id DESC
        LIMIT 5
      ");
      $recentStmt->execute([':id'=>$_SESSION['uid']]);
      $recent = $recentStmt->fetchAll();
    ?>

    <?php if (!$recent): ?>
      <div class="text-muted">No recent transactions yet.</div>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table align-middle mb-0">
          <thead class="table-light">
            <tr>
              <th>Date</th>
              <th>Type</th>
              <th>Amount</th>
              <th>Note</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($recent as $r): ?>
              <tr>
                <td class="text-nowrap small"><?= sanitize($r['created_at']) ?></td>
                <td>
                  <?= $r['kind']==='credit'
                    ? '<span class="badge text-bg-success">credit</span>'
                    : '<span class="badge text-bg-danger">debit</span>' ?>
                </td>
                <td class="<?= $r['kind']==='credit' ? 'text-success' : 'text-danger' ?>">
                  ₦<?= number_format($r['amount_cents']/100,2) ?>
                </td>
                <td class="small"><?= sanitize($r['note']) ?></td>
              </tr>

              <?php if ($r['kind'] === 'credit' && ($r['validation_status'] ?? '') === 'pending'): ?>
                <tr>
                  <td colspan="4" class="bg-light text-center">
                    <form action="validate_payment.php" method="POST" class="d-inline-flex gap-2 align-items-center mt-1">
                      <input type="hidden" name="transaction_id" value="<?= (int)$r['id'] ?>">
                      <input type="text" name="validation_code" placeholder="Enter code" required class="form-control form-control-sm" style="width:120px;">
                      <button type="submit" name="action" value="validate" class="btn btn-success btn-sm">Validate</button>
                      <button type="submit" name="action" value="reject" class="btn btn-outline-danger btn-sm">Reject</button>
                    </form>
                  </td>
                </tr>
              <?php elseif ($r['kind'] === 'credit' && ($r['validation_status'] ?? '') === 'validated'): ?>
                <tr><td colspan="4" class="text-center text-success small">✅ Payment Validated</td></tr>
              <?php elseif ($r['kind'] === 'credit' && ($r['validation_status'] ?? '') === 'rejected'): ?>
                <tr><td colspan="4" class="text-center text-danger small">❌ Payment Rejected</td></tr>
              <?php endif; ?>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>
</div>


  </div>
</div>

<!-- Bootstrap JS Bundle (Includes Popper) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-..." crossorigin="anonymous"></script>

<script>

document.addEventListener("DOMContentLoaded", () => {
  const form = document.getElementById('transferForm');
  const modal = document.getElementById('pinModal');
  const openBtn = document.getElementById('openPinModalBtn');
  const cancelBtn = document.getElementById('cancelPinBtn'); // ✅ fixed ID
  const verifyBtn = document.getElementById('verifyPinBtn'); // ✅ fixed ID
  const pinInput = document.getElementById('transactionPin');
  const msgBox = document.getElementById('pinMsg');

  // ✅ Only open modal when Send Money is clicked
  openBtn.addEventListener('click', (e) => {
    e.preventDefault();
    modal.classList.add('show');
    pinInput.value = '';
    msgBox.textContent = '';
    pinInput.focus();
  });

  // ✅ Cancel button closes modal
  cancelBtn.addEventListener('click', () => {
    modal.classList.remove('show');
  });

  // ✅ Verify button checks PIN and submits
  verifyBtn.addEventListener('click', () => {
    const pin = pinInput.value.trim();
    if (pin.length < 4 || pin.length > 6 || isNaN(pin)) {
      msgBox.textContent = 'Enter a valid 4–6 digit PIN';
      return;
    }
    let hiddenPin = form.querySelector('input[name="transaction_pin"]');
    if (!hiddenPin) {
      hiddenPin = document.createElement('input');
      hiddenPin.type = 'hidden';
      hiddenPin.name = 'transaction_pin';
      form.appendChild(hiddenPin);
    }
    hiddenPin.value = pin;
    modal.classList.remove('show');
    form.submit();
  });

  // ✅ Clicking outside the modal closes it
  window.addEventListener('click', e => {
    if (e.target === modal) {
      modal.classList.remove('show');
    }
  });
});
</script>




<?php include __DIR__.'/../includes/footer.php'; ?>

<!-- Bottom Mobile Nav -->
<nav class="mobile-bottom-nav d-md-none">
    <a href="dashboard.php" class="nav-item">
        <i class="bi bi-speedometer2"></i>
        <span>Home</span>
    </a>
    <a href="transactions.php" class="nav-item">
        <i class="bi bi-receipt"></i>
        <span>Transactions</span>
    </a>
    <a href="add-money.php" class="nav-item">
        <i class="bi bi-plus-circle"></i>
        <span>Add</span>
    </a>
    <a href="settings.php" class="nav-item">
        <i class="bi bi-gear"></i>
        <span>Settings</span>
    </a>
    <a href="logout.php" class="nav-item">
        <i class="bi bi-box-arrow-right"></i>
        <span>Logout</span>
    </a>
</nav>

