<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/referrals.php';
require_customer();

$uid = $_SESSION['user']['id'];
$user = $_SESSION['user'];

$refStats = get_referral_stats($pdo, $uid);
$refCode = ensure_user_ref_code($pdo, $uid);
$baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
$refLink = $baseUrl . "/register.php?ref=" . $refCode;

// Fetch recent commissions
$hist = $pdo->prepare("SELECT c.*, s.service_name FROM commissions c JOIN applications a ON c.application_id=a.id JOIN services s ON a.service_id=s.id WHERE c.referrer_id=? ORDER BY c.created_at DESC LIMIT 10");
$hist->execute([$uid]);
$comms = $hist->fetchAll();

include __DIR__ . '/../includes/header.php';
?>

<style>
.referral-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32px;
}
.referral-header h1 {
    font-size: 24px;
    font-weight: 700;
    color: var(--text);
    margin: 0;
}
.kpi-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 32px;
}
.kpi-card {
    background: #fff;
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
}
.kpi-card.currency-card {
    flex-direction: row;
    align-items: center;
    gap: 16px;
}
.kpi-currency-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    background: #eff6ff; /* Example background, can be customized */
    color: var(--primary); /* Example color */
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    font-weight: 700;
}
.kpi-label {
    font-size: 13px;
    color: var(--muted);
    font-weight: 500;
}
.kpi-value {
    font-size: 24px;
    font-weight: 700;
    color: var(--text);
}

.referral-link-section {
    background: #fff;
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 24px;
    margin-bottom: 32px;
}
.referral-link-section h2 {
    font-size: 18px;
    font-weight: 700;
    color: var(--text);
    margin: 0 0 16px;
}
.input-bar {
    display: flex;
    gap: 8px;
    margin-bottom: 16px;
}
.input-bar input {
    flex: 1;
    padding: 10px 14px;
    border: 1px solid var(--border);
    border-radius: 8px;
    font-size: 14px;
    background: #f8fafc;
}
.input-bar button {
    padding: 10px 16px;
    font-size: 14px;
    font-weight: 600;
    border-radius: 8px;
    background: var(--primary);
    color: #fff;
    border: none;
    cursor: pointer;
}
.social-share-buttons {
    display: flex;
    gap: 12px;
}
.social-share-buttons .btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 600;
    text-decoration: none;
    color: var(--text);
    border: 1px solid var(--border);
    background: #fff;
}
.social-share-buttons .btn:hover {
    background: #f8fafc;
}

.commissions-section {
    background: #fff;
    border: 1px solid var(--border);
    border-radius: 12px;
    overflow: hidden;
}
.commissions-section h2 {
    font-size: 18px;
    font-weight: 700;
    color: var(--text);
    margin: 0;
    padding: 16px 24px;
    border-bottom: 1px solid var(--border);
}
.table-wrap {
    overflow-x: auto;
}
.table {
    width: 100%;
    border-collapse: collapse;
}
.table th, .table td {
    padding: 12px 24px;
    text-align: left;
    border-bottom: 1px solid #f1f5f9;
}
.table th {
    background: #f8fafc;
    font-size: 12px;
    font-weight: 600;
    color: var(--muted);
    text-transform: uppercase;
}
.table td {
    font-size: 14px;
    color: var(--text);
}
.chip {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 6px;
    font-size: 11px;
    font-weight: 700;
    text-transform: capitalize;
}
.chip-pending { background: #fff7ed; color: #ea580c; }
.chip-paid { background: #f0fdf4; color: #16a34a; }
.chip-void { background: #fef2f2; color: #ef4444; }

/* Mobile Grid for Commissions */
.mobile-grid {
    display: none; /* Hidden by default on desktop */
    padding: 16px;
    gap: 16px;
}
.mobile-grid .card {
    margin-bottom: 0;
    padding: 20px;
    border-radius: 16px;
    border: 1px solid var(--border);
    background: #fff;
}
.mobile-grid .card > div:first-child {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 16px;
}
.mobile-grid .card .kpi-label {
    font-size: 12px;
    color: var(--muted);
}
.mobile-grid .card .kpi-value {
    font-size: 18px;
    font-weight: 700;
    color: var(--text);
}
.mobile-grid .card .chip {
    font-size: 11px;
}
.mobile-grid .card .muted {
    font-size: 13px;
    color: var(--muted);
}

@media(max-width:767px){
    .referral-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 16px;
    }
    .referral-header .btn {
        width: 100%;
        justify-content: center;
    }
    .kpi-grid {
        grid-template-columns: 1fr; /* Stack KPI cards on small screens */
    }
    .input-bar {
        flex-direction: column;
        gap: 8px;
    }
    .input-bar input {
        width: 100%;
    }
    .input-bar button {
        width: 100%;
        justify-content: center;
    }
    .social-share-buttons {
        flex-direction: column;
        gap: 12px;
    }
    .social-share-buttons .btn {
        width: 100%;
        justify-content: center;
    }
    .table-wrap { display: none; }
    .mobile-grid { display: grid; }
}
</style>

<div class="referral-header">
    <h1>Referral Program</h1>
    <a href="/customer/payments.php" class="btn">View Payouts</a>
</div>

<div class="kpi-grid">
    <div class="kpi-card">
        <div class="kpi-label">Total Visits</div>
        <div class="kpi-value"><?=number_format($refStats['visits'] ?? 0)?></div>
    </div>
    <div class="kpi-card">
        <div class="kpi-label">Successful Signups</div>
        <div class="kpi-value"><?=number_format($refStats['registrations'] ?? 0)?></div>
    </div>
    <div class="kpi-card currency-card">
        <div class="kpi-currency-icon">₦</div>
        <div>
            <div class="kpi-label">Total Earnings</div>
            <div class="kpi-value">₦<?=number_format($refStats['total_earnings'] ?? 0.0, 2)?></div>
        </div>
    </div>
    <div class="kpi-card currency-card">
        <div class="kpi-currency-icon">₦</div>
        <div>
            <div class="kpi-label">Pending Payout</div>
            <div class="kpi-value">₦<?=number_format($refStats['pending_earnings'] ?? 0.0, 2)?></div>
        </div>
    </div>
</div>

<div class="referral-link-section">
    <h2>Share Your Referral Link</h2>
    <div class="input-bar">
        <input type="text" id="referral-link" value="<?=e($refLink)?>" readonly>
        <button onclick="copyReferralLink()">Copy Link</button>
    </div>
    <div class="social-share-buttons">
        <a href="https://wa.me/?text=<?=urlencode("Join Go Legal and register your business with my referral link: " . $refLink)?>" target="_blank" class="btn">
            <?=ui_icon('whatsapp', 16)?> Share on WhatsApp
        </a>
        <a href="https://twitter.com/intent/tweet?text=<?=urlencode("Join Go Legal and register your business with my referral link: " . $refLink)?>" target="_blank" class="btn">
            <?=ui_icon('twitter', 16)?> Share on Twitter
        </a>
    </div>
</div>

<div class="commissions-section">
    <h2>Recent Commissions</h2>
    <div class="table-wrap">
        <table class="table">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Service</th>
                    <th>Rate</th>
                    <th>Raw Amount</th>
                    <th>Payout</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($comms)): ?>
                    <tr><td colspan="6" style="text-align:center; padding:40px; color:var(--muted)">No recent commissions. Share your link to start earning!</td></tr>
                <?php else: ?>
                    <?php foreach ($comms as $c): 
                        $isCapped = (float)$c['raw_amount'] > (float)$c['capped_amount'];
                    ?>
                        <tr>
                            <td><?=date('M j, Y', strtotime($c['created_at']))?></td>
                            <td><?=e($c['service_name'])?></td>
                            <td><?=e((string)$c['percentage_applied'])?>%</td>
                            <td>₦<?=number_format((float)$c['raw_amount'], 2)?></td>
                            <td>
                                ₦<?=number_format((float)$c['amount'], 2)?>
                                <?php if($isCapped): ?><span style="font-size:10px;color:var(--orange)" title="Capped at max limit">CAPPED</span><?php endif; ?>
                            </td>
                            <td><span class="chip chip-<?=e($c['status'])?>"><?=e($c['status'])?></span></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <div class="mobile-grid">
        <?php if (empty($comms)): ?>
            <div class="card" style="text-align:center; padding:40px; color:var(--muted)">No recent commissions. Share your link to start earning!</div>
        <?php else: ?>
            <?php foreach ($comms as $c): 
                $isCapped = (float)$c['raw_amount'] > (float)$c['capped_amount'];
            ?>
                <div class="card">
                    <div>
                        <div class="kpi-label">Service: <span class="kpi-value" style="font-size:16px"><?=e($c['service_name'])?></span></div>
                        <span class="chip chip-<?=e($c['status'])?>"><?=e($c['status'])?></span>
                    </div>
                    <div style="margin-bottom:8px;">
                        <div class="kpi-label">Date: <span class="kpi-value" style="font-size:14px"><?=date('M j, Y', strtotime($c['created_at']))?></span></div>
                    </div>
                    <div style="display:flex; justify-content:space-between; align-items:center; border-top:1px solid #f1f5f9; padding-top:12px; margin-top:12px;">
                        <div>
                            <div class="kpi-label">Payout</div>
                            <div class="kpi-value">
                                ₦<?=number_format((float)$c['amount'], 2)?>
                                <?php if($isCapped): ?><span style="font-size:10px;color:var(--orange)" title="Capped at max limit">CAPPED</span><?php endif; ?>
                            </div>
                        </div>
                        <div>
                            <div class="kpi-label">Raw Amount</div>
                            <div class="kpi-value muted">₦<?=number_format((float)$c['raw_amount'], 2)?></div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<script>
function copyReferralLink() {
    const linkInput = document.getElementById('referral-link');
    linkInput.select();
    document.execCommand('copy');
    alert('Referral link copied to clipboard!');
}
</script>

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