<?php
require_once __DIR__ . '/includes/functions.php';
startSecureSession();
requireLogin();

$user = getUserById($_SESSION['user_id']);
if (!$user) {
    header('Location: logout.php');
    exit;
}

// Release session lock to allow concurrent tab loading (fast tab switching)
session_write_close();

$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_phone') {
    csrfVerify();
    $phone = trim($_POST['phone'] ?? '');
    if (!empty($phone)) {
        $user['phone'] = $phone;
        saveUser($user);
        header('Location: dashboard.php?msg=phone_saved');
        exit;
    } else {
        $message = "Please enter a valid phone number.";
        $messageType = "error";
    }
}

if (isset($_GET['msg']) && $_GET['msg'] === 'phone_saved') {
    $message = "Phone number saved successfully!";
    $messageType = "success";
}

$db = getDB();

// Calculate dynamic pending stats so manual payment links and active orders are reflected
$stmtPending = $db->prepare("
    SELECT 
        (SELECT COUNT(*) FROM payment_links WHERE user_id = ?) as manual_links,
        (SELECT COUNT(*) FROM payment_links WHERE user_id = ? AND status = 'pending' AND expires_at > UNIX_TIMESTAMP()) as pending_links,
        (SELECT COUNT(*) FROM orders WHERE user_id = ? AND status = 'pending') as pending_orders
");
$stmtPending->execute([$user['id'], $user['id'], $user['id']]);
$pendingStats = $stmtPending->fetch(PDO::FETCH_ASSOC);

$totalRequestsDisplay = $user['total_requests'] + $pendingStats['manual_links'];
$totalFailedPendingDisplay = $user['total_failed'] + $pendingStats['pending_links'] + $pendingStats['pending_orders'];

// Fetch Chart Data
$db = getDB();
$stmt = $db->prepare("
    SELECT DATE(created_at) as date, COUNT(*) as count, SUM(CASE WHEN status = 'success' THEN amount ELSE 0 END) as revenue
    FROM orders
    WHERE user_id = ? AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    GROUP BY DATE(created_at)
    ORDER BY DATE(created_at) ASC
");
$stmt->execute([$user['id']]);
$chartData = $stmt->fetchAll(PDO::FETCH_ASSOC);

$last30Days = [];
for ($i = 29; $i >= 0; $i--) {
    $dateKey = date('Y-m-d', strtotime("-$i days"));
    $last30Days[$dateKey] = ['count' => 0, 'revenue' => 0];
}
foreach ($chartData as $row) {
    if (isset($last30Days[$row['date']])) {
        $last30Days[$row['date']] = ['count' => (int)$row['count'], 'revenue' => (float)($row['revenue'] ?: 0)];
    }
}

function getChartSlice($dataMap, $days) {
    $slice = array_slice($dataMap, -$days, $days, true);
    return [
        'labels' => array_map(function($d) { return date('M d', strtotime($d)); }, array_keys($slice)),
        'revenue' => array_values(array_column($slice, 'revenue')),
        'requests' => array_values(array_column($slice, 'count'))
    ];
}
$chart7  = getChartSlice($last30Days, 7);
$chart15 = getChartSlice($last30Days, 15);
$chart30 = getChartSlice($last30Days, 30);

// Recent Transactions
$stmtRecent = $db->prepare("
    SELECT order_id, amount, status, created_at, utr
    FROM orders
    WHERE user_id = ?
    ORDER BY created_at DESC
    LIMIT 10
");
$stmtRecent->execute([$user['id']]);
$recentOrders = $stmtRecent->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php $pageTitle = "Dashboard — FamGateway"; include 'includes/header.php'; ?>
<style>
  .chart-wrapper { position: relative; height: 320px; width: 100%; margin-top: 14px; }
  .chart-time-pills {
    display: inline-flex;
    background: #f1f5f9;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 3px;
    gap: 2px;
  }
  .time-pill {
    background: transparent;
    border: none;
    padding: 4px 12px;
    font-size: 12px;
    font-weight: 600;
    color: #64748b;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.15s;
    font-family: 'Poppins', sans-serif;
  }
  .time-pill:hover { color: #0f172a; }
  .time-pill.active {
    background: #ffffff;
    color: #2563eb;
    box-shadow: 0 1px 3px rgba(0,0,0,0.08);
  }
  .chart-toggle-btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: #ffffff;
    border: 1px solid #e2e8f0;
    padding: 5px 12px;
    border-radius: 8px;
    font-size: 12px;
    font-weight: 600;
    color: #64748b;
    cursor: pointer;
    transition: all 0.15s;
    font-family: 'Poppins', sans-serif;
  }
  .chart-toggle-btn:hover { border-color: #cbd5e1; color: #0f172a; }
  .chart-toggle-btn.active {
    background: #eff6ff;
    border-color: #bfdbfe;
    color: #1d4ed8;
  }
  .chart-toggle-btn .dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
  .chart-toggle-btn .rev-dot { background: #2563eb; }
  .chart-toggle-btn .req-dot { background: #9333ea; }
</style>
</head>
<body>
<?php include 'includes/nav.php'; ?>

<main class="main-content">
  <div class="wrap">

    <?php if ($message): ?>
    <div class="callout callout-<?= $messageType === 'success' ? 'success' : 'error' ?>">
      <?= htmlspecialchars($message) ?>
    </div>
    <?php endif; ?>

    <!-- Page Title -->
    <div class="dash-anim-right page-title-row" style="margin-bottom: 24px; display: flex; justify-content: space-between; flex-wrap: wrap; gap: 16px;">
      <div>
        <h1 style="font-size: 22px; font-weight: 700; color: var(--color-ink); letter-spacing: -0.5px;">
          Good <?= (date('H') < 12 ? 'morning' : (date('H') < 17 ? 'afternoon' : 'evening')) ?>, <?= htmlspecialchars(explode(' ', $user['name'])[0]) ?> 👋
        </h1>
        <p style="font-size: 13px; color: var(--color-ink-mute); margin-top: 4px;">Here's what's happening with your API today.</p>
      </div>
      <div style="display: flex; align-items: center;">
        <div id="imapStatusWidget" style="display:inline-flex; align-items:center; gap:8px; padding:6px 12px; background:var(--surface-page); border:1px solid var(--color-hairline); border-radius:50px; font-size:12px; font-weight:500; cursor:default; box-shadow:0 1px 2px rgba(0,0,0,0.02); transition:all 0.3s ease;" title="Checking IMAP connection...">
          <div class="dot" id="imapStatusDot" style="background:#94a3b8; width:8px; height:8px; border-radius:50%; animation: pulseOpacity 1.5s infinite;"></div>
          <span id="imapStatusText" style="color:var(--color-ink-secondary);">Checking Sync Status...</span>
        </div>
        <style>@keyframes pulseOpacity { 0% { opacity: 0.4; } 50% { opacity: 1; } 100% { opacity: 0.4; } }</style>
      </div>
    </div>

    <!-- STAT CARDS -->
    <div class="stat-grid dash-stagger">
      <div class="stat-card">
        <div class="stat-card-top">
          <div class="stat-card-label">Total Requests</div>
          <div class="stat-card-icon blue"><i data-lucide="activity" style="width:17px;height:17px;"></i></div>
        </div>
        <div class="stat-card-value tnum"><?= number_format($totalRequestsDisplay) ?></div>
      </div>
      <div class="stat-card">
        <div class="stat-card-top">
          <div class="stat-card-label">Successful</div>
          <div class="stat-card-icon green"><i data-lucide="check-circle-2" style="width:17px;height:17px;"></i></div>
        </div>
        <div class="stat-card-value tnum"><?= number_format($user['total_success']) ?></div>
      </div>
      <div class="stat-card">
        <div class="stat-card-top">
          <div class="stat-card-label">Failed / Pending</div>
          <div class="stat-card-icon red"><i data-lucide="alert-circle" style="width:17px;height:17px;"></i></div>
        </div>
        <div class="stat-card-value tnum"><?= number_format($totalFailedPendingDisplay) ?></div>
      </div>
      <div class="stat-card">
        <div class="stat-card-top">
          <div class="stat-card-label">Total Revenue</div>
          <div class="stat-card-icon green"><i data-lucide="indian-rupee" style="width:17px;height:17px;"></i></div>
        </div>
        <div class="stat-card-value tnum" style="color: #10b981;">₹<?= number_format($user['total_amount_received'], 2) ?></div>
      </div>
    </div>

    <!-- CHART -->
    <div class="card dash-anim-up" style="animation-delay:0.1s">
      <div class="card-header" style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:12px;">
        <div>
          <div class="card-title" id="chartTitleText"><i data-lucide="trending-up" style="width:18px;height:18px;color:var(--color-primary);"></i> Activity — Last 7 Days</div>
          <div class="card-sub">API requests and revenue over time</div>
        </div>
        <div style="display:flex; align-items:center; gap:12px; flex-wrap:wrap;">
          <!-- Dataset Toggles -->
          <div style="display:flex; gap:6px;">
            <button class="chart-toggle-btn active" id="toggleRev" onclick="toggleDataset(0)"><span class="dot rev-dot"></span> Revenue</button>
            <button class="chart-toggle-btn active" id="toggleReq" onclick="toggleDataset(1)"><span class="dot req-dot"></span> Requests</button>
          </div>
          <!-- Time Range Toggles -->
          <div class="chart-time-pills">
            <button class="time-pill active" onclick="switchTimeRange(7, this)">7D</button>
            <button class="time-pill" onclick="switchTimeRange(15, this)">15D</button>
            <button class="time-pill" onclick="switchTimeRange(30, this)">30D</button>
          </div>
        </div>
      </div>
      <div class="chart-wrapper">
        <canvas id="activityChart"></canvas>
      </div>
    </div>

    <!-- RECENT TRANSACTIONS -->
    <div class="card dash-anim-up" style="padding: 0; overflow: hidden; animation-delay: 0.2s;">
      <div style="padding: 22px 28px; border-bottom: 1px solid var(--color-hairline); display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:12px;">
        <div>
          <div class="card-title"><i data-lucide="receipt" style="width:18px;height:18px;color:var(--color-primary);"></i> Recent Transactions</div>
          <div class="card-sub">Your last 10 orders</div>
        </div>
        <a href="transactions.php" class="btn btn-secondary btn-sm"><i data-lucide="arrow-right" style="width:14px;height:14px;"></i> View All</a>
      </div>

      <div class="table-container" style="margin: 0; border-top: none;">
        <table class="table">
          <thead>
            <tr>
              <th>Order ID</th>
              <th>Amount</th>
              <th>Status</th>
              <th>Date &amp; Time</th>
              <th>UTR</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($recentOrders)): ?>
            <tr>
              <td colspan="5">
                <div class="empty-state">
                  <div class="empty-state-icon"><i data-lucide="inbox" style="width:24px;height:24px;"></i></div>
                  <div class="empty-state-title">No transactions yet</div>
                  <div class="empty-state-sub">Create your first payment link to get started</div>
                </div>
              </td>
            </tr>
            <?php else: ?>
            <?php foreach ($recentOrders as $order): ?>
            <tr>
              <td>
                <div style="font-weight: 500; color: var(--color-ink); display: flex; align-items: center; gap: 6px;">
                  <i data-lucide="hash" style="width:13px;height:13px;color:var(--color-ink-mute-2);"></i> <?= htmlspecialchars($order['order_id']) ?>
                </div>
              </td>
              <td class="tnum" style="font-weight:600; color:var(--color-ink); font-size: 14px;">₹<?= number_format($order['amount'], 2) ?></td>
              <td>
                <?php if ($order['status'] === 'success'): ?>
                  <span class="badge badge-success" style="padding:4px 10px;"><i data-lucide="check" style="width:12px;height:12px;"></i> Success</span>
                <?php elseif ($order['status'] === 'pending'): ?>
                  <span class="badge badge-warning" style="padding:4px 10px;"><i data-lucide="clock" style="width:12px;height:12px;"></i> Pending</span>
                <?php else: ?>
                  <span class="badge badge-danger" style="padding:4px 10px;"><i data-lucide="x" style="width:12px;height:12px;"></i> <?= htmlspecialchars(ucfirst($order['status'])) ?></span>
                <?php endif; ?>
              </td>
              <td class="tnum" style="color:var(--color-ink-secondary); font-size:12.5px;"><?= date('M d, Y · h:i A', strtotime($order['created_at'])) ?></td>
              <td>
                <?php if ($order['utr']): ?>
                  <code style="font-family:monospace; font-size:12px; color:var(--color-ink-secondary); background:var(--surface-page); padding:3px 7px; border-radius:5px; border:1px solid var(--color-hairline);"><?= htmlspecialchars($order['utr']) ?></code>
                <?php else: ?>
                  <span style="color:var(--ink-200); font-weight: 500;">—</span>
                <?php endif; ?>
              </td>
            </tr>
            <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

  </div>
</main>
</div><!-- .dashboard-layout -->

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('activityChart').getContext('2d');

const grad = ctx.createLinearGradient(0, 0, 0, 300);
grad.addColorStop(0,   'rgba(37, 99, 235, 0.22)');
grad.addColorStop(1,   'rgba(37, 99, 235, 0.0)');

// Custom crosshair plugin
const crosshairPlugin = {
  id: 'crosshair',
  afterDraw: (chart) => {
    if (chart.tooltip && chart.tooltip._active && chart.tooltip._active.length) {
      const activePoint = chart.tooltip._active[0];
      const ctx = chart.ctx;
      const x = activePoint.element.x;
      const topY = chart.scales.y.top;
      const bottomY = chart.scales.y.bottom;

      ctx.save();
      ctx.beginPath();
      ctx.moveTo(x, topY);
      ctx.lineTo(x, bottomY);
      ctx.lineWidth = 1.5;
      ctx.strokeStyle = '#94a3b8';
      ctx.setLineDash([4, 4]);
      ctx.stroke();
      ctx.restore();
    }
  }
};

const chartDataMap = {
  7: <?= json_encode($chart7) ?>,
  15: <?= json_encode($chart15) ?>,
  30: <?= json_encode($chart30) ?>
};

const myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: chartDataMap[7].labels,
    datasets: [
      {
        label: 'Revenue',
        data: chartDataMap[7].revenue,
        borderColor: '#2563eb',
        backgroundColor: grad,
        borderWidth: 3,
        tension: 0.35,
        fill: true,
        pointBackgroundColor: '#2563eb',
        pointBorderColor: '#ffffff',
        pointBorderWidth: 2,
        pointRadius: 4,
        pointHoverRadius: 7,
        pointHoverBackgroundColor: '#2563eb',
        pointHoverBorderColor: '#ffffff',
        pointHoverBorderWidth: 3,
        yAxisID: 'y'
      },
      {
        label: 'API Requests',
        data: chartDataMap[7].requests,
        borderColor: '#9333ea',
        backgroundColor: 'rgba(147, 51, 234, 0.04)',
        borderWidth: 2.5,
        borderDash: [5, 5],
        tension: 0.35,
        fill: false,
        pointBackgroundColor: '#9333ea',
        pointBorderColor: '#ffffff',
        pointBorderWidth: 2,
        pointRadius: 4,
        pointHoverRadius: 7,
        pointHoverBackgroundColor: '#9333ea',
        pointHoverBorderColor: '#ffffff',
        pointHoverBorderWidth: 3,
        yAxisID: 'y1'
      }
    ]
  },
  options: {
    animation: false,
    responsive: true,
    maintainAspectRatio: false,
    interaction: { mode: 'index', intersect: false },
    plugins: {
      legend: { display: false },
      tooltip: {
        backgroundColor: '#0f172a',
        titleColor: '#f8fafc',
        bodyColor: '#e2e8f0',
        padding: 14,
        cornerRadius: 12,
        borderColor: 'rgba(255,255,255,0.1)',
        borderWidth: 1,
        displayColors: true,
        boxPadding: 6,
        usePointStyle: true,
        titleFont: { family: 'Poppins', size: 14, weight: '700' },
        bodyFont: { family: 'Poppins', size: 13, weight: '500' },
        callbacks: {
          label: function(context) {
            let label = context.dataset.label || '';
            if (label) label += ': ';
            if (context.dataset.yAxisID === 'y') {
              label += '₹' + Number(context.raw).toLocaleString('en-IN', {minimumFractionDigits: 2, maximumFractionDigits: 2});
            } else {
              label += context.raw + ' reqs';
            }
            return label;
          }
        }
      }
    },
    scales: {
      x: {
        grid: { display: false },
        border: { display: false },
        ticks: { color: '#64748b', font: { family: 'Poppins', size: 12 } }
      },
      y: {
        position: 'left',
        grid: { color: '#f1f5f9', lineWidth: 1 },
        border: { display: false, dash: [4, 4] },
        ticks: { color: '#64748b', font: { family: 'Poppins', size: 12 }, callback: v => '₹' + v }
      },
      y1: {
        position: 'right',
        grid: { drawOnChartArea: false },
        border: { display: false },
        ticks: { color: '#64748b', font: { family: 'Poppins', size: 12 } }
      }
    }
  },
  plugins: [crosshairPlugin]
});

function switchTimeRange(days, btn) {
  document.querySelectorAll('.time-pill').forEach(el => el.classList.remove('active'));
  btn.classList.add('active');

  document.getElementById('chartTitleText').innerHTML = `<i data-lucide="trending-up" style="width:18px;height:18px;color:var(--color-primary);vertical-align:text-bottom;margin-right:6px;"></i> Activity — Last ${days} Days`;
  if (window.lucide) lucide.createIcons();

  const selectedData = chartDataMap[days];
  myChart.data.labels = selectedData.labels;
  myChart.data.datasets[0].data = selectedData.revenue;
  myChart.data.datasets[1].data = selectedData.requests;
  myChart.update();
}

function toggleDataset(index) {
  const meta = myChart.getDatasetMeta(index);
  meta.hidden = meta.hidden === null ? !myChart.data.datasets[index].hidden : null;
  myChart.update();
  
  const btnId = index === 0 ? 'toggleRev' : 'toggleReq';
  const btn = document.getElementById(btnId);
  if (meta.hidden) {
    btn.classList.remove('active');
    btn.style.opacity = '0.5';
  } else {
    btn.classList.add('active');
    btn.style.opacity = '1';
  }
}
</script>

<script>
// IMAP Health Check
fetch('api/imap-health.php')
  .then(res => res.json())
  .then(data => {
      const dot = document.getElementById('imapStatusDot');
      const text = document.getElementById('imapStatusText');
      const widget = document.getElementById('imapStatusWidget');
      
      dot.style.animation = 'none'; // stop pulsing
      
      if (data.status === 'success') {
          dot.style.background = '#10b981'; // Green
          text.style.color = '#15803d';
          text.innerText = 'IMAP Sync Healthy';
          widget.style.background = '#f0fdf4';
          widget.style.borderColor = '#bbf7d0';
          widget.title = 'IMAP is connected and parsing emails normally.';
      } else if (data.code === 'NOT_CONFIGURED') {
          dot.style.background = '#f59e0b'; // Yellow
          text.style.color = '#b45309';
          text.innerHTML = 'IMAP Not Configured <a href="integrations.php" style="margin-left:8px; padding:2px 8px; background:#f59e0b; color:#fff; border-radius:4px; text-decoration:none; font-weight:600; font-size:11px; box-shadow:0 2px 4px rgba(245,158,11,0.3);">Configure</a>';
          widget.style.background = '#fffbeb';
          widget.style.borderColor = '#f59e0b'; // Make border darker
          widget.style.boxShadow = '0 0 0 4px rgba(245, 158, 11, 0.2)'; // Add glow
          widget.title = 'Please configure your Gmail App Password in Integrations.';
      } else {
          dot.style.background = '#ef4444'; // Red
          text.style.color = '#b91c1c';
          text.innerText = 'IMAP Disconnected';
          widget.style.background = '#fef2f2';
          widget.style.borderColor = '#fecaca';
          widget.title = 'Error: ' + data.message;
      }
  })
  .catch(err => {
      document.getElementById('imapStatusDot').style.animation = 'none';
      document.getElementById('imapStatusDot').style.background = '#94a3b8';
      document.getElementById('imapStatusText').innerText = 'IMAP Status Unknown';
  });

if (window.lucide) lucide.createIcons();
</script>

<?php if (empty($user['phone'])): ?>
<div style="position: fixed; inset: 0; background: rgba(15, 23, 42, 0.6); backdrop-filter: blur(4px); display: flex; align-items: center; justify-content: center; z-index: 99999;">
  <div class="card" style="width: 100%; max-width: 420px; padding: 28px; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); animation: dashPopup 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards; margin: 20px;">
    <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 16px;">
        <div style="width: 48px; height: 48px; border-radius: 50%; background: #eff6ff; display: flex; align-items: center; justify-content: center; color: #3b82f6;">
            <i data-lucide="smartphone" style="width: 24px; height: 24px;"></i>
        </div>
        <div>
            <h2 style="margin: 0; font-size: 18px; font-weight: 700; color: var(--color-ink);">Add Phone Number</h2>
            <p style="margin: 2px 0 0; color: var(--color-ink-mute); font-size: 13px;">Required to complete your profile</p>
        </div>
    </div>
    
    <form method="POST" style="margin-top: 20px;">
      <input type="hidden" name="action" value="save_phone">
      <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">
      
      <div class="form-group">
        <label class="form-label" style="font-size: 13px; font-weight: 600; color: var(--color-ink);">Enter Phone Number</label>
        <div style="display: flex;">
          <span style="background: #f8fafc; border: 1px solid var(--color-border); border-right: none; border-radius: 8px 0 0 8px; padding: 12px 16px; color: var(--color-ink-secondary); font-weight: 600; font-size: 14px; display: flex; align-items: center;">+91</span>
          <input type="text" name="phone" class="form-input" style="border-radius: 0 8px 8px 0; border-left: 1px solid var(--color-border); font-size: 15px; letter-spacing: 0.5px;" placeholder="9876543210" required pattern="[0-9]{10}" title="Please enter a valid 10-digit phone number">
        </div>
      </div>
      
      <button type="submit" class="btn btn-primary" style="width: 100%; padding: 14px; margin-top: 8px; font-size: 14px; font-weight: 600;"><i data-lucide="save" style="width:16px;height:16px;"></i> Save & Continue</button>
    </form>
  </div>
</div>
<style>
  @keyframes dashPopup {
      0% { opacity: 0; transform: scale(0.9) translateY(10px); }
      100% { opacity: 1; transform: scale(1) translateY(0); }
  }
  body { overflow: hidden; } /* Prevents scrolling behind the popup */
</style>
<script>
    if (window.lucide) lucide.createIcons();
</script>
<?php endif; ?>

</body>
</html>
