<?php
// ============================================================
//  payment_dashboard.php  —  Submission Payment Status
// ============================================================
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
ini_set("display_errors", 0);
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/inc/payment_helpers.php';
startSession();

$user       = getCurrentUser();
$user_id    = $user['user_id'];
$pageTitle  = 'Payment Dashboard';
$activePage = 'payment_dashboard';

// ── Fetch all payments for this user's submissions ──────────
try {
    $payments_stmt = db()->prepare("
        SELECT
            p.payment_id,
            p.tracking_code,
            p.gateway,
            p.gateway_order_id,
            p.gateway_capture_id,
            p.status,
            p.payer_email,
            p.payer_name,
            p.amount,
            p.currency,
            p.paid_at,
            p.created_at,
            s.submission_id,
            s.submission_status,
            mi.article_title,
            j.name AS journal_name,
            u.country AS user_country
        FROM payments p
        INNER JOIN submissions s ON s.submission_id = p.submission_id
        LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
        LEFT JOIN journals j         ON j.journal_id     = s.journal_id
        LEFT JOIN users u            ON u.user_id        = s.user_id
        WHERE s.user_id = ?
        ORDER BY p.created_at DESC
    ");
    $payments_stmt->execute([$user_id]);
    $all_payments = $payments_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $all_payments = [];
}

// ── User ki country aur currency detect karo ───────────────
$user_country  = normalizeCountry($user['country'] ?? '');
$user_currency = 'USD'; // default
$user_symbol   = '$';

// Country ke hisaab se currency set karo
$country_currency_map = [
    'india'        => ['INR', '₹'],
    'bangladesh'   => ['BDT', '৳'],
    'pakistan'     => ['PKR', 'Rs '],
    'nigeria'      => ['NGN', '₦'],
    'kenya'        => ['KES', 'KSh '],
    'philippines'  => ['PHP', '₱'],
    'malaysia'     => ['MYR', 'RM '],
    'indonesia'    => ['IDR', 'Rp '],
    'sri lanka'    => ['LKR', 'රු '],
    'ethiopia'     => ['ETB', 'Br '],
    'tanzania'     => ['TZS', 'TSh '],
    'zambia'       => ['ZMW', 'ZK '],
    'south africa' => ['ZAR', 'R '],
    'vietnam'      => ['VND', '₫ '],
    'china'        => ['CNY', '¥ '],
    'ghana'        => ['GHS', '₵ '],
    'nepal'        => ['NPR', 'Rs '],
    'turkey'       => ['TRY', '₺'],
    'hungary'      => ['HUF', 'Ft '],
    'argentina'    => ['ARS', 'AR$ '],
];

if (isset($country_currency_map[$user_country])) {
    [$user_currency, $user_symbol] = $country_currency_map[$user_country];
}

// ── Summary counts ──────────────────────────────────────────
$total_count     = count($all_payments);
$completed_count = 0;
$pending_count   = 0;
$total_paid      = 0.0;

foreach ($all_payments as $pay) {
    if ($pay['status'] === 'COMPLETED') {
        $completed_count++;
        $total_paid += (float)$pay['amount'];
    } else {
        $pending_count++;
    }
}

require_once __DIR__ . '/_layout.php';
?>

<style>
.pd-wrap { padding: 24px 28px 60px; }
.pd-page-title { font-size: 18px; font-weight: 700; color: var(--text); margin-bottom: 4px; }
.pd-page-sub   { font-size: 13px; color: var(--muted); margin-bottom: 24px; }

.pd-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
  gap: 14px;
  margin-bottom: 28px;
}
.pd-stat-card {
  background: var(--white);
  border: 1px solid var(--border);
  border-radius: 12px;
  padding: 18px 20px;
}
.pd-stat-label {
  font-size: 12px; font-weight: 600;
  color: var(--muted);
  text-transform: uppercase; letter-spacing: .4px;
  margin-bottom: 8px;
}
.pd-stat-value { font-size: 28px; font-weight: 700; color: var(--text); line-height: 1; }
.pd-stat-value.green { color: #16A34A; }
.pd-stat-value.amber { color: #D97706; }
.pd-stat-value.blue  { color: var(--blue); }

.pd-country-badge {
  display: inline-flex; align-items: center; gap: 6px;
  background: #EFF6FF; border: 1px solid #BFDBFE;
  color: #1D4ED8; border-radius: 20px;
  padding: 4px 12px; font-size: 12px; font-weight: 600;
  margin-bottom: 20px;
}

.pd-filters {
  display: flex; gap: 8px; margin-bottom: 16px; flex-wrap: wrap;
}
.pd-filter-btn {
  display: inline-flex; align-items: center; gap: 6px;
  padding: 6px 16px; border-radius: 20px;
  font-size: 13px; font-weight: 600;
  border: 1.5px solid var(--border);
  background: var(--white); color: var(--muted);
  cursor: pointer; transition: all .15s;
  font-family: var(--font);
}
.pd-filter-btn:hover { border-color: var(--blue); color: var(--blue); }
.pd-filter-btn.active { background: #EFF6FF; color: #1D4ED8; border-color: #BFDBFE; }

.pd-table-wrap {
  background: var(--white);
  border: 1px solid var(--border);
  border-radius: 12px;
  overflow: hidden;
}
.pd-table { width: 100%; border-collapse: collapse; font-size: 13px; }
.pd-table th {
  background: #F9FAFB; padding: 11px 14px;
  text-align: left; font-size: 11px; font-weight: 700;
  color: var(--muted); text-transform: uppercase; letter-spacing: .4px;
  border-bottom: 1px solid var(--border); white-space: nowrap;
}
.pd-table td {
  padding: 11px 14px; color: var(--text);
  border-bottom: 1px solid var(--border); vertical-align: middle;
}
.pd-table tr:last-child td { border-bottom: none; }
.pd-table tr:hover td { background: #FAFAFA; }

.pd-badge {
  display: inline-flex; align-items: center; gap: 5px;
  padding: 3px 10px; border-radius: 20px;
  font-size: 11px; font-weight: 700;
}
.pd-badge::before {
  content: ''; width: 6px; height: 6px;
  border-radius: 50%; display: inline-block;
}
.pd-badge-completed { background: #F0FDF4; color: #15803D; }
.pd-badge-completed::before { background: #15803D; }
.pd-badge-pending   { background: #FFFBEB; color: #92400E; }
.pd-badge-pending::before   { background: #D97706; }

.pd-gw {
  display: inline-block; padding: 2px 8px; border-radius: 5px;
  font-size: 11px; font-weight: 600; border: 1px solid;
}
.pd-gw-paypal   { color: #003087; border-color: #003087; background: #EFF6FF; }
.pd-gw-stripe   { color: #4F46E5; border-color: #C7D2FE; background: #EEF2FF; }
.pd-gw-razorpay { color: #1565C0; border-color: #90CAF9; background: #E3F2FD; }
.pd-gw-bank     { color: #374151; border-color: #D1D5DB; background: #F9FAFB; }

.pd-amount { font-weight: 700; font-size: 13.5px; }

.pd-mono {
  font-family: monospace; font-size: 12px;
  background: #F3F4F6; padding: 2px 7px;
  border-radius: 4px; color: var(--text);
}

.pd-empty { text-align: center; padding: 48px 20px; }
.pd-empty i { font-size: 36px; color: var(--border); display: block; margin-bottom: 12px; }
.pd-empty-title { font-size: 15px; font-weight: 700; color: var(--text); margin-bottom: 5px; }
.pd-empty-sub   { font-size: 13px; color: var(--muted); }

@media (max-width: 600px) {
  .pd-wrap { padding: 16px 14px 48px; }
  .pd-table-wrap { overflow-x: auto; }
}
</style>

<div class="pd-wrap">

  <div class="pd-page-title">Payment Dashboard</div>
  <div class="pd-page-sub">Track all submission payment records — completed and pending</div>

  <!-- ── User country badge ── -->
  <?php if ($user_country): ?>
  <div class="pd-country-badge">
    <i class="fas fa-globe"></i>
    <?= htmlspecialchars(ucwords($user_country)) ?> &nbsp;·&nbsp;
    Currency: <?= htmlspecialchars($user_currency) ?>
  </div>
  <?php endif; ?>

  <!-- ── Summary cards ── -->
  <div class="pd-summary">
    <div class="pd-stat-card">
      <div class="pd-stat-label">Total Records</div>
      <div class="pd-stat-value blue"><?= $total_count ?></div>
    </div>
    <div class="pd-stat-card">
      <div class="pd-stat-label">Completed</div>
      <div class="pd-stat-value green"><?= $completed_count ?></div>
    </div>
    <div class="pd-stat-card">
      <div class="pd-stat-label">Pending</div>
      <div class="pd-stat-value amber"><?= $pending_count ?></div>
    </div>
    <div class="pd-stat-card">
      <div class="pd-stat-label">Total Paid</div>
      <div class="pd-stat-value green">
        <?= htmlspecialchars($user_symbol) ?><?= number_format($total_paid, 2) ?>
        <span style="font-size:13px;font-weight:500;color:var(--muted)"> <?= htmlspecialchars($user_currency) ?></span>
      </div>
    </div>
  </div>

  <!-- ── Filter buttons ── -->
  <div class="pd-filters">
    <button class="pd-filter-btn active" onclick="filterPayments('all', this)">
      <i class="fas fa-list"></i> All (<?= $total_count ?>)
    </button>
    <button class="pd-filter-btn" onclick="filterPayments('completed', this)">
      <i class="fas fa-check-circle"></i> Completed (<?= $completed_count ?>)
    </button>
    <button class="pd-filter-btn" onclick="filterPayments('pending', this)">
      <i class="fas fa-clock"></i> Pending (<?= $pending_count ?>)
    </button>
  </div>

  <!-- ── Payment table ── -->
  <?php if (empty($all_payments)): ?>
  <div class="pd-table-wrap">
    <div class="pd-empty">
      <i class="fas fa-receipt"></i>
      <div class="pd-empty-title">No payment records found</div>
      <div class="pd-empty-sub">Payment records will appear here once you initiate a payment.</div>
    </div>
  </div>

  <?php else: ?>
  <div class="pd-table-wrap">
    <table class="pd-table" id="paymentsTable">
      <thead>
        <tr>
          <th>#</th>
          <th>Tracking Code</th>
          <th>Submission</th>
          <th>Gateway</th>
          <th>Amount</th>
          <th>Payer</th>
          <th>Order ID</th>
          <th>Status</th>
          <th>Date</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($all_payments as $pay):
          $is_completed = $pay['status'] === 'COMPLETED';
          $badge_class  = $is_completed ? 'pd-badge-completed' : 'pd-badge-pending';
          $badge_label  = $is_completed ? 'Completed' : 'Pending';

          $gw_class = 'pd-gw-' . strtolower($pay['gateway'] ?? 'bank');

          // Use getCurrencySymbol from helpers
          $sym    = getCurrencySymbol($pay['currency'] ?? 'USD');
          $amount = $sym . number_format((float)$pay['amount'], 2) . ' ' . $pay['currency'];

          // Amount color based on currency
          $amt_color = match($pay['currency'] ?? 'USD') {
              'INR'  => '#1565C0',
              'USD'  => '#15803D',
              'GBP'  => '#7C3AED',
              'EUR'  => '#0369A1',
              default => '#374151'
          };

          $title   = $pay['article_title']
              ? htmlspecialchars(mb_substr($pay['article_title'], 0, 40)) . (mb_strlen($pay['article_title']) > 40 ? '…' : '')
              : 'Untitled';
          $date    = $is_completed && $pay['paid_at']
              ? date('d M Y, H:i', strtotime($pay['paid_at']))
              : date('d M Y, H:i', strtotime($pay['created_at']));
          $payer   = $pay['payer_email'] ?: ($pay['payer_name'] ?: '—');
          $order   = $pay['gateway_order_id'] ?: ($pay['gateway_capture_id'] ?: '—');
        ?>
        <tr data-status="<?= $is_completed ? 'completed' : 'pending' ?>">
          <td style="color:var(--muted)"><?= (int)$pay['payment_id'] ?></td>
          <td><span class="pd-mono"><?= htmlspecialchars($pay['tracking_code']) ?></span></td>
          <td>
            <div style="font-weight:600;font-size:12.5px">#<?= (int)$pay['submission_id'] ?></div>
            <div style="font-size:11.5px;color:var(--muted);margin-top:2px"><?= $title ?></div>
          </td>
          <td>
            <span class="pd-gw <?= htmlspecialchars($gw_class) ?>">
              <?= htmlspecialchars(ucfirst($pay['gateway'])) ?>
            </span>
          </td>
          <td>
            <span class="pd-amount" style="color:<?= $amt_color ?>">
              <?= $amount ?>
            </span>
          </td>
          <td style="font-size:12px;color:var(--muted)"><?= htmlspecialchars($payer) ?></td>
          <td>
            <?php if ($order !== '—'): ?>
              <span class="pd-mono" style="font-size:11px"><?= htmlspecialchars(mb_substr($order, 0, 20)) ?>…</span>
            <?php else: ?>
              <span style="color:var(--muted)">—</span>
            <?php endif; ?>
          </td>
          <td><span class="pd-badge <?= $badge_class ?>"><?= $badge_label ?></span></td>
          <td style="font-size:12px;color:var(--muted);white-space:nowrap"><?= $date ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>

</div>

<script>
function filterPayments(type, btn) {
  document.querySelectorAll('.pd-filter-btn').forEach(b => b.classList.remove('active'));
  btn.classList.add('active');
  document.querySelectorAll('#paymentsTable tbody tr').forEach(row => {
    row.style.display = (type === 'all' || row.dataset.status === type) ? '' : 'none';
  });
}
</script>

<?php layoutEnd(); ?>