<?php
include 'header.php'; // Includes user data ($user, $user_id) and site settings ($site_settings)

$message = '';
// --- ACTION: TRANSFER EARNINGS TO WALLET ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['transfer_earnings'])) {
    $amount_to_transfer = floatval($user['affiliate_earnings']);
    if ($amount_to_transfer > 0) {
        $conn->begin_transaction();
        try {
            // Deduct from affiliate earnings and add to main wallet in one query
            $stmt1 = $conn->prepare("UPDATE users SET affiliate_earnings = 0, wallet_balance = wallet_balance + ? WHERE id = ?");
            $stmt1->bind_param("di", $amount_to_transfer, $user_id);
            $stmt1->execute();

            // Log the transaction for the user's history
            $stmt2 = $conn->prepare("INSERT INTO transactions (user_id, transaction_type, amount, status, admin_notes) VALUES (?, 'Affiliate Payout', ?, 'Completed', ?)");
            $trans_note = 'Transfer from affiliate balance to main wallet';
            $stmt2->bind_param("ids", $user_id, $amount_to_transfer, $trans_note);
            $stmt2->execute();
            
            $conn->commit();
            $message = '<div class="alert alert-success">Successfully transferred ₱'.number_format($amount_to_transfer, 2).' to your main wallet!</div>';
            
            // Refresh user data on the page immediately after the transfer
            $user['affiliate_earnings'] = 0;
            $user['wallet_balance'] += $amount_to_transfer;

        } catch (mysqli_sql_exception $e) {
            $conn->rollback();
            $message = '<div class="alert alert-danger">An error occurred during the transfer. Please try again.</div>';
        }
    }
}

// --- DATA FETCHING FOR DISPLAY ---
// Get affiliate reward settings to display to the user
$reward_type = $site_settings['affiliate_reward_type'] ?? 'fixed';
$reward_value = floatval($site_settings['affiliate_reward_value'] ?? 0);
$reward_text = ($reward_type == 'fixed') ? '₱'.number_format($reward_value, 2) : $reward_value.'%';

// Get list of users referred by the current user
$referrals_stmt = $conn->prepare("SELECT full_name, created_at FROM users WHERE referred_by = ?");
$referrals_stmt->bind_param("i", $user_id);
$referrals_stmt->execute();
$referrals_result = $referrals_stmt->get_result();
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Affiliate Program</h1>
</div>
<?php echo $message; ?>

<div class="row">
    <div class="col-lg-8">
        <div class="card shadow-sm mb-4">
            <div class="card-body">
                <h5 class="card-title">Your Unique Referral Link</h5>
                <p>Share this link with your friends. When they sign up and make their first paid booking, you'll earn a commission of **<?php echo $reward_text; ?>**!</p>
                <div class="input-group">
                    <input type="text" class="form-control bg-light" value="http://<?php echo $_SERVER['HTTP_HOST']; ?>/register.php?ref=<?php echo $user['referral_code']; ?>" id="referralLink" readonly>
                    <button class="btn btn-outline-secondary" onclick="copyLink()" id="copyBtn"><i class="bi bi-clipboard"></i> Copy</button>
                </div>
            </div>
        </div>

        <div class="card shadow-sm">
            <div class="card-header fw-bold">My Successful Referrals</div>
            <div class="table-responsive">
                <table class="table mb-0">
                    <thead>
                        <tr>
                            <th>Referred User</th>
                            <th>Date Joined</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($referrals_result->num_rows > 0): while($ref = $referrals_result->fetch_assoc()): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($ref['full_name']); ?></td>
                            <td><?php echo date('M d, Y', strtotime($ref['created_at'])); ?></td>
                        </tr>
                        <?php endwhile; else: ?>
                        <tr>
                            <td colspan="2" class="text-center text-muted p-4">You have no successful referrals yet. Start sharing your link!</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="card shadow-sm text-center">
            <div class="card-body p-4">
                <h5 class="text-muted">Affiliate Earnings Balance</h5>
                <h1 class="display-5 fw-bold my-3">₱<?php echo number_format($user['affiliate_earnings'], 2); ?></h1>
                <form method="POST" onsubmit="return confirm('Are you sure you want to transfer your entire affiliate balance to your main wallet?')">
                    <div class="d-grid">
                        <button type="submit" name="transfer_earnings" class="btn btn-success btn-lg" <?php if($user['affiliate_earnings'] <= 0) echo 'disabled'; ?>>
                            <i class="bi bi-arrow-down-square-fill"></i> Transfer to My Wallet
                        </button>
                    </div>
                </form>
                <small class="text-muted mt-2 d-block">You can use your main wallet balance to pay for any booking on this site.</small>
            </div>
        </div>
    </div>
</div>

<script>
function copyLink() {
    const linkInput = document.getElementById('referralLink');
    linkInput.select();
    linkInput.setSelectionRange(0, 99999); // For mobile devices
    document.execCommand('copy');

    const copyBtn = document.getElementById('copyBtn');
    copyBtn.innerHTML = '<i class="bi bi-check-lg"></i> Copied!';
    setTimeout(function(){
        copyBtn.innerHTML = '<i class="bi bi-clipboard"></i> Copy';
    }, 2000);
}
</script>

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