<?php
// 1. INCLUDE THE LOGIC-ONLY FILE
// This connects to DB, starts session, checks security, and sets up menu variables.
require_once 'admin-logic.php';


// --- Page-Specific Logic Starts Here ---

// 2. HANDLE PAYOUT FORM SUBMISSION
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'process_payout') {
    $partner_id = filter_input(INPUT_POST, 'partner_id', FILTER_VALIDATE_INT);
    $amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
    $payment_method = trim($_POST['payment_method']);
    $notes = trim($_POST['notes']);

    if ($partner_id && $amount > 0 && !empty($payment_method)) {
        $status = 'Completed';
        $stmt = $conn->prepare("INSERT INTO withdrawals (partner_id, amount, status, payment_details, admin_notes) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("idsss", $partner_id, $amount, $status, $payment_method, $notes);
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "Payout of ₱" . number_format($amount, 2) . " processed successfully.";
        } else {
            $_SESSION['error_message'] = "Database error: Could not record the payout.";
        }
        $stmt->close();
    } else {
        $_SESSION['error_message'] = "Invalid payout data provided.";
    }
    header("Location: manage-affiliates.php");
    exit();
}


// 3. FETCH AFFILIATES FOR DISPLAY
$records_per_page = 15;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $records_per_page;

// Base clause: Must have an affiliate code to be listed here.
$where_clauses = ["u.affiliate_code IS NOT NULL AND u.affiliate_code != ''"];
$params = [];
$types = '';

// Search term for name or affiliate code
$search_term = $_GET['search'] ?? '';
if (!empty($search_term)) {
    $where_clauses[] = "(u.full_name LIKE ? OR u.affiliate_code LIKE ?)";
    $like_term = "%{$search_term}%";
    array_push($params, $like_term, $like_term);
    $types .= 'ss';
}

$where_sql = "WHERE " . implode(' AND ', $where_clauses);

// Database queries using subqueries for stats
$base_query = "FROM users u $where_sql";

$count_sql = "SELECT COUNT(u.id) as total $base_query";
$stmt_count = $conn->prepare($count_sql);
if (count($params) > 0) { $stmt_count->bind_param($types, ...$params); }
$stmt_count->execute();
$total_records = $stmt_count->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_records / $records_per_page);
$stmt_count->close();

$fetch_sql = "SELECT u.id, u.full_name, u.email, u.affiliate_code, u.status,
                (SELECT COUNT(*) FROM users ref WHERE ref.referred_by_id = u.id) as referral_count,
                (SELECT COALESCE(SUM(commission_amount), 0) FROM transactions WHERE affiliate_id = u.id AND status = 'Completed') as total_earned,
                (SELECT COALESCE(SUM(amount), 0) FROM withdrawals WHERE partner_id = u.id AND status = 'Completed') as total_paid
              $base_query
              ORDER BY total_earned DESC
              LIMIT ? OFFSET ?";

$params[] = $records_per_page; $params[] = $offset; $types .= 'ii';
$stmt_fetch = $conn->prepare($fetch_sql);
if (count($params) > 0) { $stmt_fetch->bind_param($types, ...$params); }
$stmt_fetch->execute();
$affiliates_result = $stmt_fetch->get_result();


// 4. INCLUDE THE HTML HEADER
include 'admin-header.php';
?>

<?php if (isset($_SESSION['success_message'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>
<?php if (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<div class="card mb-4 shadow-sm">
    <div class="card-header"><i class="bi bi-filter me-1"></i> Filter Affiliates</div>
    <div class="card-body">
         <form action="manage-affiliates.php" method="GET" class="row g-3">
            <div class="col-md-9">
                <input type="text" name="search" class="form-control" placeholder="Search by Affiliate Name or Code..." value="<?php echo htmlspecialchars($search_term); ?>">
            </div>
            <div class="col-md-3 d-grid d-md-flex gap-2">
                <button type="submit" class="btn btn-primary flex-grow-1">Search</button>
                <a href="manage-affiliates.php" class="btn btn-secondary flex-grow-1">Clear</a>
            </div>
        </form>
    </div>
</div>

<div class="table-responsive">
    <table class="table table-striped table-hover">
        <thead class="table-dark align-middle">
            <tr>
                <th>Affiliate</th>
                <th>Affiliate Code</th>
                <th class="text-center">Referrals</th>
                <th>Total Earned</th>
                <th>Total Paid</th>
                <th>Commission Due</th>
                <th class="text-center">Status</th>
                <th class="text-end">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($affiliates_result->num_rows > 0): ?>
                <?php while ($affiliate = $affiliates_result->fetch_assoc()):
                    $commission_due = $affiliate['total_earned'] - $affiliate['total_paid'];
                ?>
                    <tr>
                        <td>
                            <div class="fw-bold"><?php echo htmlspecialchars($affiliate['full_name']); ?></div>
                            <small class="text-muted"><?php echo htmlspecialchars($affiliate['email']); ?></small>
                        </td>
                        <td><code class="user-select-all"><?php echo htmlspecialchars($affiliate['affiliate_code']); ?></code></td>
                        <td class="text-center"><?php echo $affiliate['referral_count']; ?></td>
                        <td>₱<?php echo number_format($affiliate['total_earned'], 2); ?></td>
                        <td>₱<?php echo number_format($affiliate['total_paid'], 2); ?></td>
                        <td><strong class="text-success">₱<?php echo number_format($commission_due, 2); ?></strong></td>
                        <td class="text-center">
                            <span class="badge bg-<?php echo ($affiliate['status'] == 'active') ? 'success' : 'danger'; ?>"><?php echo htmlspecialchars(ucfirst($affiliate['status'])); ?></span>
                        </td>
                        <td class="text-end">
                            <button type="button" class="btn btn-sm btn-primary process-payout-btn"
                                    data-bs-toggle="modal" data-bs-target="#payoutModal"
                                    data-affiliate-id="<?php echo $affiliate['id']; ?>"
                                    data-affiliate-name="<?php echo htmlspecialchars($affiliate['full_name']); ?>"
                                    data-amount-due="<?php echo $commission_due; ?>"
                                    <?php echo ($commission_due <= 0) ? 'disabled' : ''; ?>>
                                <i class="bi bi-wallet-fill me-1"></i> Payout
                            </button>
                            <a href="edit-user.php?id=<?php echo $affiliate['id']; ?>" class="btn btn-sm btn-warning" title="Edit User Profile"><i class="bi bi-person-fill-gear"></i></a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="8" class="text-center p-4">No affiliates found.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<?php if($total_pages > 1): ?>
<nav><ul class="pagination justify-content-center mt-4">
    <?php $query_params = $_GET; for ($i = 1; $i <= $total_pages; $i++): $query_params['page'] = $i; ?>
        <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>"><a class="page-link" href="?<?php echo http_build_query($query_params); ?>"><?php echo $i; ?></a></li>
    <?php endfor; ?>
</ul></nav>
<?php endif; ?>

<div class="modal fade" id="payoutModal" tabindex="-1" aria-labelledby="payoutModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form action="manage-affiliates.php" method="POST">
        <div class="modal-header">
          <h5 class="modal-title" id="payoutModalLabel">Process Payout</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
            <input type="hidden" name="action" value="process_payout">
            <p>Processing payment for <strong id="modal-affiliate-name"></strong>.</p>
            <input type="hidden" name="partner_id" id="modal-affiliate-id">
            <div class="mb-3">
                <label for="modal-payout-amount" class="form-label">Payout Amount (Max: <span id="modal-max-amount"></span>)</label>
                <div class="input-group">
                    <span class="input-group-text">₱</span>
                    <input type="number" step="0.01" class="form-control" id="modal-payout-amount" name="amount" required>
                </div>
            </div>
            <div class="mb-3">
                <label for="modal-payout-method" class="form-label">Payment Method</label>
                <input type="text" class="form-control" id="modal-payout-method" name="payment_method" placeholder="e.g., Bank Transfer, PayPal" required>
            </div>
             <div class="mb-3">
                <label for="modal-notes" class="form-label">Notes / Reference #</label>
                <textarea class="form-control" id="modal-notes" name="notes" rows="2"></textarea>
            </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary">Confirm Payout</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const payoutModal = document.getElementById('payoutModal');
    payoutModal.addEventListener('show.bs.modal', function (event) {
        const button = event.relatedTarget;
        const affiliateId = button.getAttribute('data-affiliate-id');
        const affiliateName = button.getAttribute('data-affiliate-name');
        const amountDue = parseFloat(button.getAttribute('data-amount-due')).toFixed(2);

        document.getElementById('modal-affiliate-name').textContent = affiliateName;
        document.getElementById('modal-affiliate-id').value = affiliateId;
        document.getElementById('modal-max-amount').textContent = '₱' + amountDue;
        
        const amountInput = document.getElementById('modal-payout-amount');
        amountInput.value = amountDue;
        amountInput.max = amountDue;
    });
});
</script>

<?php include 'admin-footer.php'; ?>
