<?php
require_once __DIR__ . '/../app/bootstrap.php';

use App\Core\Auth;
use App\Core\Database;

Auth::requireRole(['vendor', 'admin'], 'public/login.php');
$user = current_user();
$vendor = Auth::role() === 'vendor'
    ? Database::safeFetchOne('SELECT * FROM vendors WHERE user_id=? AND status IN ("approved","active") LIMIT 1', [Auth::id()])
    : Database::safeFetchOne('SELECT * FROM vendors WHERE id=? AND status IN ("approved","active") LIMIT 1', [(int)($_GET['vendor_id'] ?? 0)]);
if (!$vendor) {
    http_response_code(403);
    exit('Vendor profile not found or not approved.');
}
$panelType = 'vendor';
$pageTitle = 'Vendor Affiliate';
$member = Database::safeFetchOne('SELECT * FROM affiliate_members WHERE user_id=? LIMIT 1', [$vendor['user_id']]);
include ROOT_PATH . '/app/Layouts/panel_header.php';
?>
<div class="row g-4">
    <div class="col-md-4"><div class="card metric-card"><div class="card-body"><span class="text-muted">Rank</span><h3><?= e($member['rank_code'] ?? 'Not enrolled') ?></h3></div></div></div>
    <div class="col-md-4"><div class="card metric-card"><div class="card-body"><span class="text-muted">Total PSA</span><h3><?= money($member['total_psa'] ?? 0) ?></h3></div></div></div>
    <div class="col-md-4"><div class="card metric-card"><div class="card-body"><span class="text-muted">Weekly Sales</span><h3><?= money($member['weekly_personal_sales'] ?? 0) ?></h3></div></div></div>
</div>
<div class="table-card p-4 mt-4"><h5>Share Tools</h5>
<?php if ($member): $shareUrl = url('landing/member.php?ref=' . urlencode((string)$member['referral_code'])); ?>
    <p>Referral Code: <strong><?= e($member['referral_code']) ?></strong></p>
    <a class="btn btn-success" target="_blank" rel="noopener" href="https://wa.me/?text=<?= rawurlencode($shareUrl) ?>">Share WhatsApp</a>
<?php else: ?>
    <div class="alert alert-info mb-0">This vendor account is not enrolled in the affiliate program.</div>
<?php endif; ?>
</div>
<?php include ROOT_PATH . '/app/Layouts/panel_footer.php'; ?>
