<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once 'includes/auth.php';
requireUserLogin();
$currentUser = currentUser($pdo);
$uid = (int)$_SESSION['user_id'];

// Show popup if set
$showPopup = (bool)$currentUser['show_popup'];
$popupMsg  = $currentUser['popup_message'] ?? '';

// Recent transactions
$txns = $pdo->prepare("SELECT * FROM transactions WHERE user_id=? ORDER BY created_at DESC LIMIT 8");
$txns->execute([$uid]);
$transactions = $txns->fetchAll();

// Stats
$totCredit = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM transactions WHERE user_id=? AND transaction_type='credit' AND status='completed'");
$totCredit->execute([$uid]); $totalCredited = (float)$totCredit->fetchColumn();
$totDebit = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM transactions WHERE user_id=? AND transaction_type IN('debit','transfer') AND status='completed'");
$totDebit->execute([$uid]); $totalDebited = (float)$totDebit->fetchColumn();
$txnCount = $pdo->prepare("SELECT COUNT(*) FROM transactions WHERE user_id=?");
$txnCount->execute([$uid]); $totalTxns = (int)$txnCount->fetchColumn();

// Unread notifications
$unreadQ = $pdo->prepare("SELECT COUNT(*) FROM notifications WHERE user_id=? AND is_read=0");
$unreadQ->execute([$uid]); $unreadNotifs = (int)$unreadQ->fetchColumn();

// Monthly chart data (last 6 months)
$chartData = [];
for ($i = 5; $i >= 0; $i--) {
    $month = date('Y-m', strtotime("-$i months"));
    $label = date('M', strtotime("-$i months"));
    $c = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM transactions WHERE user_id=? AND transaction_type='credit' AND DATE_FORMAT(created_at,'%Y-%m')=? AND status='completed'");
    $c->execute([$uid, $month]); $cr = (float)$c->fetchColumn();
    $d = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM transactions WHERE user_id=? AND transaction_type IN('debit','transfer') AND DATE_FORMAT(created_at,'%Y-%m')=? AND status='completed'");
    $d->execute([$uid, $month]); $dr = (float)$d->fetchColumn();
    $chartData[] = ['label'=>$label,'credit'=>$cr,'debit'=>$dr];
}

// Announcements
$anns = $pdo->query("SELECT * FROM announcements WHERE is_active=1 AND (starts_at IS NULL OR starts_at <= NOW()) AND (ends_at IS NULL OR ends_at >= NOW()) ORDER BY id DESC LIMIT 3")->fetchAll();

$pageTitle = 'Dashboard';
?>
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Dashboard | <?= SITE_NAME ?></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link rel="stylesheet" href="/assets/css/style.css">
</head><body>
<?php include 'includes/header.php'; ?>
<div class="page-wrapper">
<div class="container">

<?php foreach ($anns as $ann): ?>
<div class="alert alert-<?= ['info'=>'info','warning'=>'warning','success'=>'success','maintenance'=>'secondary'][$ann['type']] ?> alert-dismissible fade show mb-3">
  <i class="fa fa-bullhorn me-2"></i><strong><?= sanitize($ann['title']) ?></strong> — <?= sanitize($ann['body']) ?>
  <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endforeach; ?>

<!-- Welcome Banner -->
<div class="card mb-4" style="background:linear-gradient(135deg,var(--secondary),#16213e);color:#fff;border-radius:16px;">
  <div class="card-body p-4">
    <div class="row align-items-center">
      <div class="col-md-8">
        <h4 class="fw-bold mb-1">Welcome back, <?= sanitize($currentUser['first_name']) ?>! 👋</h4>
        <p class="mb-0 opacity-75">Account No: <strong class="text-white"><?= sanitize($currentUser['account_number']) ?></strong>
          <button class="btn btn-sm btn-link text-white p-0 ms-2" data-copy="<?= sanitize($currentUser['account_number']) ?>"><i class="fa fa-copy"></i></button>
        </p>
        <p class="mb-0 opacity-75 small"><?= sanitize(ucfirst($currentUser['account_type'])) ?> Account &bull; <?= sanitize($currentUser['currency']) ?></p>
      </div>
      <div class="col-md-4 text-md-end mt-3 mt-md-0">
        <p class="mb-0 opacity-75 small">Available Balance</p>
        <h2 class="fw-bold mb-0"><?= money((float)$currentUser['available_balance'], $currentUser['currency']) ?></h2>
        <?php if ($currentUser['kyc_status'] !== 'verified'): ?>
          <a href="/kyc.php" class="btn btn-warning btn-sm mt-2 fw-bold"><i class="fa fa-exclamation-triangle me-1"></i>Complete KYC</a>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<!-- Stat Cards -->
<div class="row g-3 mb-4">
  <div class="col-6 col-md-3">
    <div class="stat-card primary">
      <div class="d-flex justify-content-between align-items-start">
        <div><div class="label">Account Balance</div><div class="value"><?= money((float)$currentUser['account_balance'], $currentUser['currency']) ?></div></div>
        <div class="icon"><i class="fa fa-wallet"></i></div>
      </div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="stat-card green">
      <div class="d-flex justify-content-between align-items-start">
        <div><div class="label">Total Credited</div><div class="value"><?= money($totalCredited, $currentUser['currency']) ?></div></div>
        <div class="icon"><i class="fa fa-arrow-down"></i></div>
      </div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="stat-card primary">
      <div class="d-flex justify-content-between align-items-start">
        <div><div class="label">Total Debited</div><div class="value"><?= money($totalDebited, $currentUser['currency']) ?></div></div>
        <div class="icon"><i class="fa fa-arrow-up"></i></div>
      </div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="stat-card dark">
      <div class="d-flex justify-content-between align-items-start">
        <div><div class="label">Transactions</div><div class="value"><?= $totalTxns ?></div></div>
        <div class="icon"><i class="fa fa-exchange-alt"></i></div>
      </div>
    </div>
  </div>
</div>

<!-- Quick Actions -->
<div class="card mb-4">
  <div class="card-header">Quick Actions</div>
  <div class="card-body">
    <div class="row g-2">
      <?php $actions = [
        ['transfer.php','fa-paper-plane','Send Money','primary'],
        ['transactions.php','fa-list','Transactions','dark'],
        ['cards.php','fa-credit-card','My Cards','primary'],
        ['loans.php','fa-hand-holding-usd','Loans','dark'],
        ['investments.php','fa-chart-line','Invest','primary'],
        ['kyc.php','fa-id-card','KYC','dark'],
        ['support.php','fa-headset','Support','primary'],
        ['profile.php','fa-user-cog','Settings','dark'],
      ]; foreach ($actions as [$href,$icon,$label,$cls]): ?>
      <div class="col-6 col-sm-4 col-md-3">
        <a href="/<?= $href ?>" class="btn btn-outline-<?= $cls ?> w-100 d-flex flex-column align-items-center py-3 gap-1">
          <i class="fa <?= $icon ?> fa-lg"></i><small><?= $label ?></small>
        </a>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>

<!-- Chart + Recent Transactions -->
<div class="row g-4">
  <div class="col-lg-8">
    <div class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <span>Transaction Activity (6 Months)</span>
      </div>
      <div class="card-body">
        <canvas id="txnChart" height="120"></canvas>
      </div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="card h-100">
      <div class="card-header d-flex justify-content-between align-items-center">
        <span>Recent Transactions</span>
        <a href="/transactions.php" class="btn btn-sm btn-outline-primary">View All</a>
      </div>
      <div class="card-body p-0">
        <?php if (empty($transactions)): ?>
          <div class="p-3 text-center text-muted small">No transactions yet.</div>
        <?php else: foreach ($transactions as $t): $isCredit = $t['transaction_type']==='credit'; ?>
        <div class="txn-item">
          <div class="txn-icon <?= $isCredit?'credit':'debit' ?>">
            <i class="fa fa-arrow-<?= $isCredit?'down':'up' ?>"></i>
          </div>
          <div class="flex-grow-1 min-w-0">
            <div class="fw-600 text-truncate small"><?= sanitize(substr($t['description'],0,30)) ?></div>
            <div class="text-muted" style="font-size:.75rem"><?= timeAgo($t['created_at']) ?></div>
          </div>
          <div class="txn-amount <?= $isCredit?'credit':'debit' ?> small"><?= ($isCredit?'+':'-').money((float)$t['amount'],$t['currency']) ?></div>
        </div>
        <?php endforeach; endif; ?>
      </div>
    </div>
  </div>
</div>

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

<?php if ($showPopup && $popupMsg): ?>
<div class="modal fade" id="popupModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
  <div class="modal-header bg-warning"><h5 class="modal-title"><i class="fa fa-bell me-2"></i>Important Notice</h5>
    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
  </div>
  <div class="modal-body"><?= nl2br(sanitize($popupMsg)) ?></div>
  <div class="modal-footer"><button type="button" class="btn btn-primary" data-bs-dismiss="modal">I Understand</button></div>
</div></div></div>
<script>new bootstrap.Modal(document.getElementById('popupModal')).show();</script>
<?php endif; ?>

<script>
const labels = <?= json_encode(array_column($chartData,'label')) ?>;
const credits = <?= json_encode(array_column($chartData,'credit')) ?>;
const debits  = <?= json_encode(array_column($chartData,'debit')) ?>;
new Chart(document.getElementById('txnChart'), {
  type: 'bar',
  data: {
    labels,
    datasets: [
      {label:'Credits',data:credits,backgroundColor:'rgba(26,188,156,.7)',borderRadius:6},
      {label:'Debits',data:debits,backgroundColor:'rgba(192,57,43,.7)',borderRadius:6},
    ]
  },
  options: {
    responsive:true, maintainAspectRatio:true,
    plugins:{legend:{position:'top'}},
    scales:{y:{beginAtZero:true,ticks:{callback:v=>'$'+Number(v).toLocaleString()}}}
  }
});
</script>
</body></html>
