<?php
require_once 'header.php'; 
$page_title = 'My Earnings';

// --- Fetch Earnings Data FIRST ---
// This is needed for both the display and the POST logic.

// Available for Payout
$stmt_avail = $conn->prepare("SELECT SUM(earned_amount) as total FROM earnings WHERE partner_id = ? AND status = 'cleared'");
$stmt_avail->bind_param("i", $partner_id);
$stmt_avail->execute();
$available_for_payout = $stmt_avail->get_result()->fetch_assoc()['total'] ?? 0;
$stmt_avail->close();

// Pending Clearance
$stmt_pending = $conn->prepare("SELECT SUM(earned_amount) as total FROM earnings WHERE partner_id = ? AND status = 'pending_clearance'");
$stmt_pending->bind_param("i", $partner_id);
$stmt_pending->execute();
$pending_clearance = $stmt_pending->get_result()->fetch_assoc()['total'] ?? 0;
$stmt_pending->close();

// Lifetime Earnings (cleared + pending)
$total_earnings = $available_for_payout + $pending_clearance;


// --- Handle Payout Request ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'request_payout') {
    $amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
    
    if ($partner_user['payout_details']) {
        if ($amount > 0 && $amount <= $available_for_payout) {
            // Insert into payout_requests table
            $stmt = $conn->prepare("INSERT INTO payout_requests (partner_id, amount, status) VALUES (?, ?, 'pending')");
            $stmt->bind_param("id", $partner_id, $amount);
            $stmt->execute();
            $_SESSION['success_message'] = "Your payout request of " . format_price($amount) . " has been submitted for review.";
        } else {
            $_SESSION['error_message'] = "Invalid amount or insufficient available balance for payout.";
        }
    } else {
        $_SESSION['error_message'] = "You must set your payout details in your profile before requesting a payout.";
    }
    header("Location: earnings.php");
    exit();
}


// Fetch detailed earnings list for the table
$stmt_list = $conn->prepare("SELECT booking_type, booking_total, commission_rate, earned_amount, status, created_at FROM earnings WHERE partner_id = ? ORDER BY created_at DESC");
$stmt_list->bind_param("i", $partner_id);
$stmt_list->execute();
$earnings_list = $stmt_list->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt_list->close();
?>

<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"><i class="bi bi-cash-coin me-2"></i>My Earnings</h1>
</div>

<?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 elseif (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="row">
    <div class="col-md-4 mb-3"><div class="card card-body text-center shadow-sm h-100"><h6>Available for Payout</h6><h3 class="fw-bold text-success"><?php echo format_price($available_for_payout); ?></h3></div></div>
    <div class="col-md-4 mb-3"><div class="card card-body text-center shadow-sm h-100"><h6>Pending Clearance</h6><h3 class="fw-bold text-warning"><?php echo format_price($pending_clearance); ?></h3></div></div>
    <div class="col-md-4 mb-3"><div class="card card-body text-center shadow-sm h-100"><h6>Lifetime Earnings</h6><h3 class="fw-bold text-primary"><?php echo format_price($total_earnings); ?></h3></div></div>
</div>

<div class="row mt-4">
    <div class="col-lg-5 mb-4">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-light border-0"><h5>Request a Payout</h5></div>
            <div class="card-body">
                <?php if (empty($partner_user['payout_details'])): ?>
                    <div class="alert alert-warning">Please set your payout details in your profile before requesting a payout. <a href="edit-profile.php">Update Profile</a></div>
                <?php else: ?>
                    <p>Your payout will be sent to your saved details.</p>
                    <form method="POST">
                        <input type="hidden" name="action" value="request_payout">
                        <label for="payoutAmount" class="form-label">Amount to withdraw (Available: <?php echo format_price($available_for_payout); ?>)</label>
                        <div class="input-group">
                            <span class="input-group-text">₱</span>
                            <input type="number" class="form-control" name="amount" id="payoutAmount" step="0.01" max="<?php echo $available_for_payout; ?>" placeholder="0.00" required>
                            <button class="btn btn-primary" type="submit" <?php if($available_for_payout <= 0) echo 'disabled'; ?>>Request</button>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <div class="col-lg-7">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-light border-0"><h5>Earnings History</h5></div>
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead><tr><th>Date</th><th>Booking Type</th><th>Commission</th><th>Status</th></tr></thead>
                    <tbody>
                        <?php if(empty($earnings_list)): ?>
                            <tr><td colspan="4" class="text-center text-muted p-4">No earnings recorded yet.</td></tr>
                        <?php else: ?>
                            <?php foreach($earnings_list as $item): ?>
                            <tr>
                                <td><?php echo date('M d, Y', strtotime($item['created_at'])); ?></td>
                                <td><?php echo ucfirst($item['booking_type']); ?></td>
                                <td class="fw-bold text-success">+<?php echo format_price($item['earned_amount']); ?></td>
                                <td><span class="badge bg-secondary"><?php echo str_replace('_', ' ', ucfirst($item['status'])); ?></span></td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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