<?php
// =========================================================
// AFFILIATE ADMIN PANEL
// =========================================================
session_start();
require_once '../config.php';

// Check admin login
if (!isset($_SESSION['admin'])) {
    header('Location: login.php');
    exit;
}

// =========================================================
// HANDLE ACTIONS
// =========================================================
$msg = '';
$msgType = 'success';

// Approve referral
if (isset($_GET['approve_referral'])) {
    $id = (int)$_GET['approve_referral'];
    $conn->query("UPDATE affiliate_referrals SET status = 'approved', approved_at = NOW() WHERE id = $id");
    $msg = 'Referral approved successfully!';
    header('Location: affiliates.php?tab=referrals');
    exit;
}

// Pay referral
if (isset($_GET['pay_referral'])) {
    $id = (int)$_GET['pay_referral'];
    $conn->query("UPDATE affiliate_referrals SET status = 'paid', paid_at = NOW() WHERE id = $id");
    $msg = 'Referral paid successfully!';
    header('Location: affiliates.php?tab=referrals');
    exit;
}

// Cancel referral
if (isset($_GET['cancel_referral'])) {
    $id = (int)$_GET['cancel_referral'];
    $conn->query("UPDATE affiliate_referrals SET status = 'cancelled' WHERE id = $id");
    $msg = 'Referral cancelled successfully!';
    header('Location: affiliates.php?tab=referrals');
    exit;
}

// Approve payout
if (isset($_GET['approve_payout'])) {
    $id = (int)$_GET['approve_payout'];
    $conn->query("UPDATE affiliate_payouts SET status = 'completed', completed_at = NOW() WHERE id = $id");
    $msg = 'Payout completed successfully!';
    header('Location: affiliates.php?tab=payouts');
    exit;
}

// Reject payout
if (isset($_GET['reject_payout'])) {
    $id = (int)$_GET['reject_payout'];
    $payout = $conn->query("SELECT affiliate_id, amount FROM affiliate_payouts WHERE id = $id")->fetch_assoc();
    if ($payout) {
        // Refund the amount back to affiliate balance
        $conn->query("UPDATE affiliates SET balance = balance + {$payout['amount']} WHERE id = {$payout['affiliate_id']}");
        $conn->query("UPDATE affiliate_payouts SET status = 'failed' WHERE id = $id");
    }
    $msg = 'Payout rejected. Amount refunded to affiliate balance.';
    header('Location: affiliates.php?tab=payouts');
    exit;
}

// Toggle affiliate status
if (isset($_GET['toggle_status']) && isset($_GET['affiliate_id'])) {
    $id = (int)$_GET['affiliate_id'];
    $current = $conn->query("SELECT status FROM affiliates WHERE id = $id")->fetch_assoc();
    $new_status = ($current['status'] == 'active') ? 'inactive' : 'active';
    $conn->query("UPDATE affiliates SET status = '$new_status' WHERE id = $id");
    $msg = 'Affiliate status updated!';
    header('Location: affiliates.php?tab=affiliates');
    exit;
}

// Update commission rate
if (isset($_POST['update_commission'])) {
    $id = (int)$_POST['affiliate_id'];
    $rate = (float)$_POST['commission_rate'];
    $conn->query("UPDATE affiliates SET commission_rate = $rate WHERE id = $id");
    $msg = 'Commission rate updated!';
    $msgType = 'success';
}

// =========================================================
// GET DATA
// =========================================================
$tab = $_GET['tab'] ?? 'dashboard';

// Get all affiliates
$affiliates = $conn->query("SELECT * FROM affiliates ORDER BY id DESC");

// Get referrals with affiliate info
$referrals = $conn->query("SELECT r.*, a.name as affiliate_name, a.email as affiliate_email, o.order_number, o.total_amount 
                           FROM affiliate_referrals r 
                           LEFT JOIN affiliates a ON r.affiliate_id = a.id 
                           LEFT JOIN orders o ON r.order_id = o.id 
                           ORDER BY r.created_at DESC");

// Get payouts with affiliate info
$payouts = $conn->query("SELECT p.*, a.name as affiliate_name, a.email as affiliate_email 
                         FROM affiliate_payouts p 
                         LEFT JOIN affiliates a ON p.affiliate_id = a.id 
                         ORDER BY p.requested_at DESC");

// Summary stats
$total_affiliates = $conn->query("SELECT COUNT(*) as count FROM affiliates")->fetch_assoc()['count'];
$active_affiliates = $conn->query("SELECT COUNT(*) as count FROM affiliates WHERE status = 'active'")->fetch_assoc()['count'];
$total_referrals_count = $conn->query("SELECT COUNT(*) as count FROM affiliate_referrals")->fetch_assoc()['count'];
$total_commission = $conn->query("SELECT SUM(commission_amount) as total FROM affiliate_referrals WHERE status IN ('approved','paid')")->fetch_assoc()['total'] ?? 0;
$pending_payouts = $conn->query("SELECT SUM(amount) as total FROM affiliate_payouts WHERE status = 'pending'")->fetch_assoc()['total'] ?? 0;

$brand = getBrand();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>Affiliate Management | <?= htmlspecialchars($brand['name']) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        :root{--p:#2d6a4f;--pl:#52b788;--pd:#1b4332}
        *{font-family:'Segoe UI',sans-serif}
        body{background:#f0f2f5;overflow-x:hidden}
        .sidebar{background:linear-gradient(180deg,#1b4332,#2d6a4f);min-height:100vh;color:#fff;position:fixed;width:250px;z-index:1000;overflow-y:auto;transition:all .3s}
        .sidebar .brand{padding:20px;text-align:center;border-bottom:1px solid rgba(255,255,255,.1)}
        .sidebar a{color:rgba(255,255,255,.85);text-decoration:none;padding:11px 18px;display:block;margin:2px 10px;border-radius:10px;transition:.3s;font-size:.9rem}
        .sidebar a:hover,.sidebar a.active{background:rgba(255,255,255,.15);color:#fff;transform:translateX(5px)}
        .sidebar a i{width:22px;margin-right:10px}
        .main-content{margin-left:250px;padding:20px;transition:all .3s}
        .card{border:none;border-radius:15px;box-shadow:0 3px 15px rgba(0,0,0,.08);margin-bottom:20px;background:#fff}
        .card-header{background:var(--p);color:#fff;border-radius:15px 15px 0 0!important;padding:14px 20px;font-weight:600}
        .stat-card{background:#fff;border-radius:15px;padding:20px;box-shadow:0 3px 15px rgba(0,0,0,.08);border-left:4px solid var(--p);transition:.3s}
        .stat-card:hover{transform:translateY(-5px);box-shadow:0 10px 25px rgba(0,0,0,.1)}
        .stat-number{font-size:2rem;font-weight:800;color:var(--p)}
        .stat-label{color:#6c757d;font-size:.85rem}
        .stat-icon{font-size:2rem;opacity:.2;float:right}
        .badge-pending{background:#ffc107;color:#000}
        .badge-approved{background:#28a745;color:#fff}
        .badge-paid{background:#17a2b8;color:#fff}
        .badge-cancelled{background:#dc3545;color:#fff}
        .badge-active{background:#28a745;color:#fff}
        .badge-inactive{background:#6c757d;color:#fff}
        .btn-primary{background:var(--p);border:none}
        .btn-primary:hover{background:var(--pd)}
        .menu-toggle{display:none;position:fixed;top:15px;left:15px;z-index:1001;background:var(--p);color:#fff;border:none;width:40px;height:40px;border-radius:50%;cursor:pointer}
        @media(max-width:992px){.menu-toggle{display:block}.sidebar{left:-250px}.sidebar.show{left:0}.main-content{margin-left:0;padding-top:60px}}
        @media(max-width:768px){.stat-number{font-size:1.5rem}}
        .table th{background:#f8f9fa;font-weight:600;font-size:.85rem;white-space:nowrap}
        .table td{vertical-align:middle;font-size:.85rem}
        .btn-sm .spinner{display:inline-block;animation:spin 1s linear infinite}
        @keyframes spin{to{transform:rotate(360deg)}}
    </style>
</head>
<body>
<button class="menu-toggle" id="menuToggle" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
<div class="d-flex">
    <div class="sidebar" id="sidebar">
        <div class="brand"><h6><i class="fas fa-handshake"></i> Affiliates</h6><small>Management</small></div>
        <div class="p-2">
            <a href="?tab=dashboard" class="<?=$tab=='dashboard'?'active':''?>"><i class="fas fa-th-large"></i> Dashboard</a>
            <a href="?tab=affiliates" class="<?=$tab=='affiliates'?'active':''?>"><i class="fas fa-users"></i> Affiliates</a>
            <a href="?tab=referrals" class="<?=$tab=='referrals'?'active':''?>"><i class="fas fa-link"></i> Referrals</a>
            <a href="?tab=payouts" class="<?=$tab=='payouts'?'active':''?>"><i class="fas fa-money-bill-wave"></i> Payouts</a>
            <hr>
            <a href="admin.php"><i class="fas fa-arrow-left"></i> Back to Admin</a>
            <a href="../index.php" target="_blank"><i class="fas fa-globe"></i> View Site</a>
            <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>

    <div class="main-content flex-grow-1">
        <?php if ($msg): ?>
            <div class="alert alert-<?=$msgType?> alert-dismissible fade show"><?=$msg?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
        <?php endif; ?>

        <!-- =========================================================
             DASHBOARD
             ========================================================= -->
        <?php if($tab=='dashboard'): ?>
        <div class="animated">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h4><i class="fas fa-chart-line"></i> Affiliate Dashboard</h4>
                <span><?=date('l, d M Y')?></span>
            </div>
            <div class="row g-3 mb-4">
                <div class="col-md-3 col-6"><div class="stat-card"><div class="stat-number"><?=$total_affiliates?></div><div class="stat-label">Total Affiliates</div><div class="stat-icon"><i class="fas fa-users"></i></div></div></div>
                <div class="col-md-3 col-6"><div class="stat-card"><div class="stat-number"><?=$active_affiliates?></div><div class="stat-label">Active Affiliates</div><div class="stat-icon"><i class="fas fa-user-check"></i></div></div></div>
                <div class="col-md-3 col-6"><div class="stat-card"><div class="stat-number"><?=$total_referrals_count?></div><div class="stat-label">Total Referrals</div><div class="stat-icon"><i class="fas fa-link"></i></div></div></div>
                <div class="col-md-3 col-6"><div class="stat-card"><div class="stat-number">৳<?=number_format($total_commission, 2)?></div><div class="stat-label">Total Commission</div><div class="stat-icon"><i class="fas fa-money-bill"></i></div></div></div>
            </div>
            <div class="row g-3 mb-4">
                <div class="col-md-3 col-6"><div class="stat-card" style="border-left-color:#ffc107"><div class="stat-number"><?=$conn->query("SELECT COUNT(*) as count FROM affiliate_referrals WHERE status='pending'")->fetch_assoc()['count']?></div><div class="stat-label">Pending Referrals</div><div class="stat-icon"><i class="fas fa-clock"></i></div></div></div>
                <div class="col-md-3 col-6"><div class="stat-card" style="border-left-color:#17a2b8"><div class="stat-number"><?=$conn->query("SELECT COUNT(*) as count FROM affiliate_referrals WHERE status='approved'")->fetch_assoc()['count']?></div><div class="stat-label">Approved Referrals</div><div class="stat-icon"><i class="fas fa-check-circle"></i></div></div></div>
                <div class="col-md-3 col-6"><div class="stat-card" style="border-left-color:#28a745"><div class="stat-number"><?=$conn->query("SELECT COUNT(*) as count FROM affiliate_referrals WHERE status='paid'")->fetch_assoc()['count']?></div><div class="stat-label">Paid Referrals</div><div class="stat-icon"><i class="fas fa-dollar-sign"></i></div></div></div>
                <div class="col-md-3 col-6"><div class="stat-card" style="border-left-color:#dc3545"><div class="stat-number">৳<?=number_format($pending_payouts, 2)?></div><div class="stat-label">Pending Payouts</div><div class="stat-icon"><i class="fas fa-hourglass"></i></div></div></div>
            </div>
            <div class="card">
                <div class="card-header">Quick Actions</div>
                <div class="card-body">
                    <div class="row g-2">
                        <div class="col-md-3 col-6"><a href="?tab=affiliates" class="btn btn-primary w-100"><i class="fas fa-users"></i> View Affiliates</a></div>
                        <div class="col-md-3 col-6"><a href="?tab=referrals" class="btn btn-primary w-100"><i class="fas fa-link"></i> Manage Referrals</a></div>
                        <div class="col-md-3 col-6"><a href="?tab=payouts" class="btn btn-primary w-100"><i class="fas fa-money-bill-wave"></i> Process Payouts</a></div>
                        <div class="col-md-3 col-6"><a href="affiliate_settings.php" class="btn btn-primary w-100"><i class="fas fa-cog"></i> Settings</a></div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- =========================================================
             AFFILIATES LIST
             ========================================================= -->
        <?php if($tab=='affiliates'): ?>
        <div class="card">
            <div class="card-header d-flex justify-content-between">
                <span><i class="fas fa-users"></i> Affiliates (<?=$total_affiliates?>)</span>
                <a href="?tab=affiliates&export=1" class="btn btn-light btn-sm"><i class="fas fa-download"></i> Export</a>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr><th>ID</th><th>Name</th><th>Email</th><th>Referral Code</th><th>Commission</th><th>Earnings</th><th>Balance</th><th>Status</th><th>Actions</th></tr>
                        </thead>
                        <tbody>
                        <?php while($a = $affiliates->fetch_assoc()): ?>
                            <tr>
                                <td><?= $a['id'] ?></td>
                                <td><strong><?= htmlspecialchars($a['name']) ?></strong></td>
                                <td><?= $a['email'] ?></td>
                                <td><code><?= $a['referral_code'] ?></code></td>
                                <td><?= $a['commission_rate'] ?>%</td>
                                <td>৳<?= number_format($a['total_earnings'], 2) ?></td>
                                <td>৳<?= number_format($a['balance'], 2) ?></td>
                                <td><span class="badge badge-<?= $a['status'] ?>"><?= ucfirst($a['status']) ?></span></td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <a href="?toggle_status=1&affiliate_id=<?= $a['id'] ?>" class="btn btn-warning" onclick="return confirm('Toggle status?')">
                                            <i class="fas fa-toggle-<?= $a['status']=='active'?'on':'off' ?>"></i>
                                        </a>
                                        <button class="btn btn-info" onclick="editCommission(<?= $a['id'] ?>, '<?= addslashes($a['name']) ?>', <?= $a['commission_rate'] ?>)">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Edit Commission Modal -->
        <div class="modal fade" id="commissionModal" tabindex="-1">
            <div class="modal-dialog"><div class="modal-content">
                <div class="modal-header"><h5>Edit Commission Rate</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="affiliate_id" id="editAffiliateId">
                        <label>Affiliate: <strong id="editAffiliateName"></strong></label>
                        <input type="number" name="commission_rate" id="editCommissionRate" class="form-control" step="0.1" min="1" max="50">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="update_commission" class="btn btn-primary">Update</button>
                    </div>
                </form>
            </div></div>
        </div>
        <script>
        function editCommission(id, name, rate) {
            document.getElementById('editAffiliateId').value = id;
            document.getElementById('editAffiliateName').textContent = name;
            document.getElementById('editCommissionRate').value = rate;
            new bootstrap.Modal(document.getElementById('commissionModal')).show();
        }
        </script>
        <?php endif; ?>

        <!-- =========================================================
             REFERRALS LIST
             ========================================================= -->
        <?php if($tab=='referrals'): ?>
        <div class="card">
            <div class="card-header">
                <span><i class="fas fa-link"></i> Referrals (<?=$total_referrals_count?>)</span>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr><th>ID</th><th>Affiliate</th><th>Type</th><th>Customer</th><th>Order</th><th>Amount</th><th>Commission</th><th>Status</th><th>Date</th><th>Actions</th></tr>
                        </thead>
                        <tbody>
                        <?php while($r = $referrals->fetch_assoc()): ?>
                            <tr>
                                <td><?= $r['id'] ?></td>
                                <td><?= htmlspecialchars($r['affiliate_name']) ?></td>
                                <td><span class="badge bg-secondary"><?= ucfirst($r['referral_type'] ?? 'general') ?></span></td>
                                <td><?= htmlspecialchars($r['referred_customer_email'] ?? 'N/A') ?></td>
                                <td>#<?= htmlspecialchars($r['order_number'] ?? '—') ?></td>
                                <td>৳<?= number_format($r['total_amount'] ?? 0, 2) ?></td>
                                <td>৳<?= number_format($r['commission_amount'], 2) ?></td>
                                <td><span class="badge badge-<?= $r['status'] ?>"><?= ucfirst($r['status']) ?></span></td>
                                <td><?= date('d M Y', strtotime($r['created_at'])) ?></td>
                                <td>
                                    <?php if($r['status'] == 'pending'): ?>
                                        <a href="?approve_referral=<?= $r['id'] ?>" class="btn btn-sm btn-success" onclick="return confirm('Approve this referral?')"><i class="fas fa-check"></i></a>
                                        <a href="?cancel_referral=<?= $r['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Cancel this referral?')"><i class="fas fa-times"></i></a>
                                    <?php elseif($r['status'] == 'approved'): ?>
                                        <a href="?pay_referral=<?= $r['id'] ?>" class="btn btn-sm btn-info" onclick="return confirm('Mark as paid?')"><i class="fas fa-dollar-sign"></i></a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- =========================================================
             PAYOUTS LIST
             ========================================================= -->
        <?php if($tab=='payouts'): ?>
        <div class="card">
            <div class="card-header">
                <span><i class="fas fa-money-bill-wave"></i> Payouts</span>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr><th>ID</th><th>Affiliate</th><th>Amount</th><th>Method</th><th>Status</th><th>Requested</th><th>Actions</th></tr>
                        </thead>
                        <tbody>
                        <?php while($p = $payouts->fetch_assoc()): ?>
                            <tr>
                                <td><?= $p['id'] ?></td>
                                <td><?= htmlspecialchars($p['affiliate_name']) ?></td>
                                <td><strong>৳<?= number_format($p['amount'], 2) ?></strong></td>
                                <td><?= strtoupper($p['payment_method']) ?></td>
                                <td><span class="badge badge-<?= $p['status'] == 'completed' ? 'success' : ($p['status'] == 'pending' ? 'warning' : 'secondary') ?>"><?= ucfirst($p['status']) ?></span></td>
                                <td><?= date('d M Y', strtotime($p['requested_at'])) ?></td>
                                <td>
                                    <?php if($p['status'] == 'pending'): ?>
                                        <a href="?approve_payout=<?= $p['id'] ?>" class="btn btn-sm btn-success" onclick="return confirm('Approve this payout?')"><i class="fas fa-check"></i> Approve</a>
                                        <a href="?reject_payout=<?= $p['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Reject this payout? Amount will be refunded.')"><i class="fas fa-times"></i> Reject</a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
function toggleSidebar() {
    document.getElementById('sidebar').classList.toggle('show');
}

// Close sidebar on mobile
document.addEventListener('click', function(e) {
    const sidebar = document.getElementById('sidebar');
    const toggle = document.getElementById('menuToggle');
    if (window.innerWidth <= 992 && sidebar.classList.contains('show')) {
        if (!sidebar.contains(e.target) && !toggle.contains(e.target)) {
            sidebar.classList.remove('show');
        }
    }
});
</script>
</body>
</html>