<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();

// Redirect to login if the admin is not authenticated
if (!isset($_SESSION['admin_id'])) {
    header("Location: index.php");
    exit();
}

// Include Database Connection
require_once "../account/include/db.php";

// --- ACTION LOGIC (Pay / Edit / Delete) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $earning_id = (int)$_POST['earning_id'];

    // 1. DELETE ACTION
    if ($action === 'delete') {
        $del_q = "DELETE FROM `referral_earnings` WHERE `id` = ?";
        if ($stmt = mysqli_prepare($conn, $del_q)) {
            mysqli_stmt_bind_param($stmt, "i", $earning_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Referral earning record deleted.";
                $_SESSION['swal_title'] = "Removed";
            }
            mysqli_stmt_close($stmt);
        }
    }

    // 2. APPROVE & PAY ACTION
    elseif ($action === 'pay') {
        // Fetch earning details to credit the user
        $fetch_q = "SELECT referrer_id, amount, status FROM `referral_earnings` WHERE id = ? LIMIT 1";
        if ($stmt = mysqli_prepare($conn, $fetch_q)) {
            mysqli_stmt_bind_param($stmt, "i", $earning_id);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_bind_result($stmt, $ref_id, $amt, $stat);
            
            if (mysqli_stmt_fetch($stmt)) {
                mysqli_stmt_close($stmt);

                if ($stat === 'pending') {
                    // Update Earning Status
                    $upd_e = "UPDATE `referral_earnings` SET `status` = 'paid', `paid_at` = NOW() WHERE `id` = ?";
                    // Add to User Balance
                    $upd_u = "UPDATE `users` SET `balance` = `balance` + ?, `referral_earnings` = `referral_earnings` + ? WHERE `id` = ?";
                    
                    $s1 = mysqli_prepare($conn, $upd_e);
                    mysqli_stmt_bind_param($s1, "i", $earning_id);
                    
                    $s2 = mysqli_prepare($conn, $upd_u);
                    mysqli_stmt_bind_param($s2, "ddi", $amt, $amt, $ref_id);

                    if (mysqli_stmt_execute($s1) && mysqli_stmt_execute($s2)) {
                        $_SESSION['swal_success'] = "Commission of $" . number_format($amt, 2) . " credited to user balance.";
                        $_SESSION['swal_title'] = "Payment Released";
                    }
                }
            } else { mysqli_stmt_close($stmt); }
        }
    }

    // 3. EDIT ACTION
    elseif ($action === 'edit') {
        $amt  = (float)$_POST['amount'];
        $type = mysqli_real_escape_string($conn, $_POST['type']);
        $desc = mysqli_real_escape_string($conn, $_POST['description']);

        $upd_q = "UPDATE `referral_earnings` SET `amount` = ?, `type` = ?, `description` = ? WHERE `id` = ?";
        if ($stmt = mysqli_prepare($conn, $upd_q)) {
            mysqli_stmt_bind_param($stmt, "dsi", $amt, $type, $desc, $earning_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Commission record updated.";
                $_SESSION['swal_title'] = "Updated";
            }
            mysqli_stmt_close($stmt);
        }
    }

    header("Location: referral_config.php?page=" . (isset($_GET['page']) ? (int)$_GET['page'] : 1));
    exit();
}

// --- PAGINATION ---
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

$total_res = mysqli_query($conn, "SELECT COUNT(*) as total FROM `referral_earnings` ");
$total_data = mysqli_fetch_assoc($total_res);
$total_records = $total_data['total'] ?? 0;
$total_pages = ceil($total_records / $limit);

// Fetch Data with Referrer and Referred User Names
$query = "SELECT e.*, u1.full_name as referrer_name, u1.username as referrer_username, u2.full_name as referred_name 
          FROM `referral_earnings` e 
          JOIN `users` u1 ON e.referrer_id = u1.id 
          LEFT JOIN `users` u2 ON e.referred_id = u2.id 
          ORDER BY e.created_at DESC 
          LIMIT $limit OFFSET $offset";
$result = mysqli_query($conn, $query);

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

<style>
    body { font-family: 'Inter', sans-serif !important; }
    .status-pill { padding: 2px 8px; border-radius: 4px; font-size: 10px; font-weight: 700; text-transform: uppercase; }
    .pagination-btn { transition: all 0.2s; border: 1px solid #1e293b; color: #94a3b8; }
    .pagination-btn.active { background: #3b82f6; border-color: #3b82f6; color: white; }
</style>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<main class="md:ml-64 p-4 md:p-6 min-h-[calc(100vh-65px)] bg-slate-950 relative z-10">
    
    <div class="mb-8">
        <div class="text-[10px] font-bold text-blue-500 tracking-widest uppercase mb-1">Affiliate Network</div>
        <h1 class="text-3xl font-bold text-white tracking-tight">Referral Management</h1>
        <p class="text-slate-400 mt-1 text-sm">Control commissions and monitor affiliate growth</p>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        <div class="bg-slate-900 border border-slate-800 p-5 rounded-xl">
            <h3 class="text-[10px] uppercase font-bold text-slate-500 mb-2">Total Earnings Records</h3>
            <div class="text-2xl font-bold text-white"><?php echo number_format($total_records); ?></div>
        </div>
    </div>

    <div class="bg-slate-900 border border-slate-800 rounded-xl overflow-hidden shadow-2xl flex flex-col">
        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse min-w-[1000px]">
                <thead>
                    <tr class="border-b border-slate-800 bg-slate-950 text-xs text-slate-400 uppercase tracking-widest">
                        <th class="p-4">Referrer (Affiliate)</th>
                        <th class="p-4">Referred User</th>
                        <th class="p-4">Commission</th>
                        <th class="p-4">Type / Description</th>
                        <th class="p-4">Status</th>
                        <th class="p-4 text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="text-sm text-slate-300 divide-y divide-slate-800/50">
                    <?php if($result && mysqli_num_rows($result) > 0): ?>
                        <?php while ($row = mysqli_fetch_assoc($result)): ?>
                        <tr class="hover:bg-slate-800/30 transition-colors">
                            <td class="p-4">
                                <div class="font-bold text-slate-100"><?php echo htmlspecialchars($row['referrer_name'] ?? ''); ?></div>
                                <div class="text-[10px] text-slate-500">@<?php echo htmlspecialchars($row['referrer_username'] ?? ''); ?></div>
                            </td>
                            <td class="p-4">
                                <div class="text-slate-200"><?php echo htmlspecialchars($row['referred_name'] ?? 'Direct System'); ?></div>
                                <div class="text-[10px] text-slate-500"><?php echo date('M d, Y', strtotime($row['created_at'])); ?></div>
                            </td>
                            <td class="p-4">
                                <span class="text-emerald-400 font-mono font-bold">$<?php echo number_format($row['amount'] ?? 0, 2); ?></span>
                            </td>
                            <td class="p-4">
                                <div class="text-xs uppercase font-bold text-blue-500"><?php echo htmlspecialchars($row['type'] ?? 'N/A'); ?></div>
                                <div class="text-[10px] text-slate-500 truncate max-w-[150px]"><?php echo htmlspecialchars($row['description'] ?? ''); ?></div>
                            </td>
                            <td class="p-4">
                                <?php if(($row['status'] ?? '') == 'pending'): ?>
                                    <span class="status-pill bg-amber-500/10 text-amber-500 border border-amber-500/20">Pending</span>
                                <?php elseif(($row['status'] ?? '') == 'paid'): ?>
                                    <span class="status-pill bg-emerald-500/10 text-emerald-500 border border-emerald-500/20">Paid</span>
                                <?php else: ?>
                                    <span class="status-pill bg-slate-800 text-slate-500 border border-slate-700"><?php echo htmlspecialchars($row['status'] ?? 'N/A'); ?></span>
                                <?php endif; ?>
                            </td>
                            <td class="p-4 text-right">
                                <div class="flex justify-end gap-3 items-center">
                                    <?php if(($row['status'] ?? '') == 'pending'): ?>
                                        <form method="POST" class="inline m-0">
                                            <input type="hidden" name="earning_id" value="<?php echo $row['id']; ?>">
                                            <input type="hidden" name="action" value="pay">
                                            <button type="button" onclick="confirmRef(this.form, 'pay')" class="text-emerald-500 text-[10px] font-bold uppercase hover:underline">Pay</button>
                                        </form>
                                    <?php endif; ?>

                                    <button onclick='refModal("edit", <?php echo json_encode($row); ?>)' class="text-blue-500 text-[10px] font-bold uppercase hover:underline">Edit</button>
                                    
                                    <form method="POST" class="inline" onsubmit="return confirm('Remove this earning record?');">
                                        <input type="hidden" name="earning_id" value="<?php echo $row['id']; ?>">
                                        <input type="hidden" name="action" value="delete">
                                        <button type="submit" class="text-red-500 text-[10px] font-bold uppercase hover:underline">Delete</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="6" class="p-12 text-center text-slate-500 italic">No referral commissions found in logs.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if($total_pages > 1): ?>
        <div class="p-4 border-t border-slate-800 bg-slate-900/50 flex items-center justify-between">
            <div class="text-xs text-slate-500">Page <?php echo $page; ?> of <?php echo $total_pages; ?></div>
            <div class="flex gap-1">
                <?php if($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs">Prev</a>
                <?php endif; ?>
                <?php for($i = max(1, $page-1); $i <= min($total_pages, $page+1); $i++): ?>
                    <a href="?page=<?php echo $i; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs <?php echo ($i == $page) ? 'active' : ''; ?>"><?php echo $i; ?></a>
                <?php endfor; ?>
                <?php if($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs">Next</a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</main>

<script>
function refModal(mode, data = null) {
    Swal.fire({
        title: 'Edit Commission',
        background: '#0f172a',
        color: '#f1f5f9',
        html: `
            <form id="refForm" method="POST" class="text-left mt-4">
                <input type="hidden" name="action" value="edit">
                <input type="hidden" name="earning_id" value="${data.id}">
                
                <div class="mb-4">
                    <label class="text-[10px] uppercase font-bold text-slate-500">Commission Amount ($)</label>
                    <input type="number" step="0.01" name="amount" value="${data.amount}" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                </div>

                <div class="mb-4">
                    <label class="text-[10px] uppercase font-bold text-slate-500">Earnings Type</label>
                    <input type="text" name="type" value="${data.type}" placeholder="e.g. Deposit Bonus / Trade Commission" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                </div>

                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">Description</label>
                    <textarea name="description" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1 h-20 text-sm">${data.description ?? ''}</textarea>
                </div>
            </form>
        `,
        showCancelButton: true,
        confirmButtonText: 'Save Changes',
        confirmButtonColor: '#3b82f6',
        preConfirm: () => { document.getElementById('refForm').submit(); }
    });
}

function confirmRef(form, type) {
    Swal.fire({
        title: 'Approve Payout?',
        text: "The commission amount will be added to the user's available balance immediately.",
        icon: 'success',
        showCancelButton: true,
        confirmButtonColor: '#10b981',
        cancelButtonColor: '#1e293b',
        confirmButtonText: 'Yes, Pay Now!',
        background: '#0f172a',
        color: '#f1f5f9'
    }).then((result) => { if (result.isConfirmed) form.submit(); });
}

<?php if (isset($_SESSION['swal_success'])): ?>
    Swal.fire({ title: '<?php echo $_SESSION['swal_title']; ?>', text: '<?php echo $_SESSION['swal_success']; ?>', icon: 'success', background: '#0f172a', color: '#f1f5f9', confirmButtonColor: '#3b82f6' });
    <?php unset($_SESSION['swal_success'], $_SESSION['swal_title']); ?>
<?php endif; ?>
</script>

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