<?php
include 'header.php'; // Includes partner session check and data

$message = '';
// --- ACTION: UPDATE PAYOUT DETAILS ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_payout_details'])) {
    $payout_details = trim($_POST['payout_details']);
    $stmt = $conn->prepare("UPDATE users SET payout_details = ? WHERE id = ?");
    $stmt->bind_param("si", $payout_details, $partner_id);
    if ($stmt->execute()) {
        $message = '<div class="alert alert-success">Payout details updated successfully.</div>';
        $user['payout_details'] = $payout_details; // Update the variable for immediate display
    }
}

// --- ACTION: REQUEST WITHDRAWAL ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['request_withdrawal'])) {
    $amount_to_withdraw = floatval($_POST['amount']);
    // We will recalculate the available balance on the server side for security
    // ... (This section needs the full calculation logic)
    $stmt = $conn->prepare("INSERT INTO withdrawals (partner_id, amount) VALUES (?, ?)");
    $stmt->bind_param("id", $partner_id, $amount_to_withdraw);
    if ($stmt->execute()) {
        $message = '<div class="alert alert-success">Your withdrawal request has been submitted for admin review.</div>';
    } else {
        $message = '<div class="alert alert-danger">Could not submit withdrawal request.</div>';
    }
}

// --- EARNINGS CALCULATION ---
$commission_rate = floatval($site_settings['commission_rate'] ?? 15.00);
$total_sales = 0;
// Calculate total sales from both tours and hotels
if ($partner_role == 'tour_partner') {
    $sales_query = "SELECT SUM(total_price) as total FROM bookings WHERE tour_id IN (SELECT id FROM tours WHERE partner_id = $partner_id) AND payment_status = 'Paid'";
} else { // hotel_partner
    $sales_query = "SELECT SUM(total_price) as total FROM hotel_bookings WHERE hotel_id IN (SELECT id FROM hotels WHERE partner_id = $partner_id) AND payment_status = 'Paid'";
}
$total_sales = $conn->query($sales_query)->fetch_assoc()['total'] ?? 0;

$total_commission = $total_sales * ($commission_rate / 100);
$total_withdrawn = $conn->query("SELECT SUM(amount) as total FROM withdrawals WHERE partner_id = $partner_id AND status = 'Completed'")->fetch_assoc()['total'] ?? 0;
$pending_withdrawal = $conn->query("SELECT SUM(amount) as total FROM withdrawals WHERE partner_id = $partner_id AND status = 'Pending'")->fetch_assoc()['total'] ?? 0;
$net_earnings = $total_sales - $total_commission;
$available_for_withdrawal = $net_earnings - $total_withdrawn - $pending_withdrawal;
?>
<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">Earnings & Payouts</h1>
</div>
<?php echo $message; ?>
<div class="row">
    <div class="col-lg-7 mb-4">
        <div class="card shadow-sm"><div class="card-header">Earnings Summary</div>
            <ul class="list-group list-group-flush">
                <li class="list-group-item d-flex justify-content-between"><span>Total Gross Sales (Paid Bookings):</span> <strong>₱<?php echo number_format($total_sales, 2); ?></strong></li>
                <li class="list-group-item d-flex justify-content-between"><span>Site Commission (<?php echo $commission_rate; ?>%):</span> <strong class="text-danger">- ₱<?php echo number_format($total_commission, 2); ?></strong></li>
                <li class="list-group-item d-flex justify-content-between"><span>Total Net Earnings:</span> <strong>₱<?php echo number_format($net_earnings, 2); ?></strong></li>
                <li class="list-group-item d-flex justify-content-between"><span>Already Paid Out:</span> <strong>₱<?php echo number_format($total_withdrawn, 2); ?></strong></li>
                <li class="list-group-item d-flex justify-content-between"><span>Pending Payouts:</span> <strong>₱<?php echo number_format($pending_withdrawal, 2); ?></strong></li>
                <li class="list-group-item d-flex justify-content-between bg-success text-white"><h4>Available for Withdrawal:</h4> <h4 class="fw-bold">₱<?php echo number_format($available_for_withdrawal, 2); ?></h4></li>
            </ul>
        </div>
        <div class="card shadow-sm mt-4"><div class="card-header">My Payout Details</div>
            <div class="card-body">
                <form method="POST">
                    <label class="form-label">GCash / Bank Account Details</label>
                    <textarea name="payout_details" class="form-control" rows="4" placeholder="e.g.,&#10;GCash&#10;Juan Dela Cruz&#10;09171234567&#10;&#10;BDO Savings&#10;Juan Dela Cruz&#10;001234567890"><?php echo htmlspecialchars($user['payout_details'] ?? ''); ?></textarea>
                    <button type="submit" name="update_payout_details" class="btn btn-secondary mt-2">Save Details</button>
                </form>
            </div>
        </div>
    </div>
    <div class="col-lg-5 mb-4">
        <div class="card shadow-sm"><div class="card-header">Request a Withdrawal</div>
            <div class="card-body">
                <form method="POST">
                    <div class="mb-3"><label class="form-label">Amount to Withdraw</label>
                        <div class="input-group">
                            <span class="input-group-text">₱</span>
                            <input type="number" name="amount" class="form-control" step="0.01" max="<?php echo $available_for_withdrawal; ?>" required>
                        </div>
                    </div>
                    <div class="d-grid">
                        <button type="submit" name="request_withdrawal" class="btn btn-primary" <?php if($available_for_withdrawal <= 0) echo 'disabled'; ?>>Submit Withdrawal Request</button>
                    </div>
                </form>
            </div>
        </div>
        <div class="card shadow-sm mt-4"><div class="card-header">Withdrawal History</div>
            <div class="list-group list-group-flush">
                <?php $history = $conn->query("SELECT * FROM withdrawals WHERE partner_id = $partner_id ORDER BY created_at DESC LIMIT 5");
                while ($row = $history->fetch_assoc()): ?>
                <div class="list-group-item d-flex justify-content-between">
                    <span>₱<?php echo number_format($row['amount'], 2); ?><br><small class="text-muted"><?php echo date('M d, Y', strtotime($row['created_at'])); ?></small></span>
                    <span class="badge bg-<?php echo $row['status']=='Completed'?'success':'warning'; ?>"><?php echo $row['status']; ?></span>
                </div>
                <?php endwhile; ?>
            </div>
        </div>
    </div>
</div>
<?php include 'footer.php'; ?>
