<?php
require_once 'admin-header.php'; 
$page_title = 'Manage Withdrawals';

// --- Handle Approve/Decline Actions ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $request_id = filter_input(INPUT_POST, 'request_id', FILTER_VALIDATE_INT);
    $partner_id = filter_input(INPUT_POST, 'partner_id', FILTER_VALIDATE_INT);
    $action = $_POST['action'] ?? '';

    if ($action === 'approve' && $request_id && $partner_id) {
        // Use a transaction for financial safety
        $conn->begin_transaction();
        try {
            // 1. Mark the request as processed
            $stmt1 = $conn->prepare("UPDATE payout_requests SET status = 'processed', processed_at = NOW() WHERE id = ? AND status = 'pending'");
            $stmt1->bind_param("i", $request_id);
            $stmt1->execute();

            // 2. Mark the source earnings as withdrawn to prevent double-payout
            $stmt2 = $conn->prepare("UPDATE earnings SET status = 'withdrawn' WHERE partner_id = ? AND status = 'cleared'");
            $stmt2->bind_param("i", $partner_id);
            $stmt2->execute();
            
            $conn->commit();
            $_SESSION['success_message'] = "Payout request has been approved and processed.";

        } catch (mysqli_sql_exception $exception) {
            $conn->rollback();
            $_SESSION['error_message'] = "A database error occurred. The transaction was rolled back.";
        }

    } elseif ($action === 'decline' && $request_id) {
        $reason = trim($_POST['reason']);
        $stmt = $conn->prepare("UPDATE payout_requests SET status = 'declined', admin_notes = ? WHERE id = ? AND status = 'pending'");
        $stmt->bind_param("si", $reason, $request_id);
        $stmt->execute();
        $_SESSION['success_message'] = "Payout request has been declined.";
    }
    header("Location: manage-withdrawals.php");
    exit();
}

// --- Fetch Data for Display ---
// 1. KPIs
$pending_total = $conn->query("SELECT SUM(amount) as total FROM payout_requests WHERE status = 'pending'")->fetch_assoc()['total'] ?? 0;
$processed_total = $conn->query("SELECT SUM(amount) as total FROM payout_requests WHERE status = 'processed' AND MONTH(processed_at) = MONTH(CURDATE())")->fetch_assoc()['total'] ?? 0;

// 2. Main List Query
$filter_status = $_GET['status'] ?? 'pending';
$where_sql = '';
if (!empty($filter_status)) { $where_sql = "WHERE pr.status = '" . $conn->real_escape_string($filter_status) . "'"; }

$requests = $conn->query("
    SELECT 
        pr.*, 
        u.full_name, 
        u.business_name, 
        u.payout_details,
        (SELECT SUM(earned_amount) FROM earnings WHERE partner_id = pr.partner_id AND status = 'cleared') as available_balance
    FROM payout_requests pr
    JOIN users u ON pr.partner_id = u.id
    $where_sql
    ORDER BY pr.requested_at DESC
")->fetch_all(MYSQLI_ASSOC);
?>

<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-box-arrow-up-right me-2"></i>Manage Withdrawals</h1>
</div>

<div class="row">
    <div class="col-md-6 mb-3"><div class="card card-body shadow-sm"><h6 class="text-muted">Total Pending Payouts</h6><h3 class="fw-bold text-warning"><?php echo format_price($pending_total); ?></h3></div></div>
    <div class="col-md-6 mb-3"><div class="card card-body shadow-sm"><h6 class="text-muted">Processed This Month</h6><h3 class="fw-bold text-success"><?php echo format_price($processed_total); ?></h3></div></div>
</div>

<div class="card shadow-sm border-0">
    <div class="card-header bg-light border-0">
        <form method="GET" class="d-flex align-items-center"><label for="status" class="form-label me-2 mb-0">Status:</label><select name="status" id="status" class="form-select w-auto" onchange="this.form.submit()"><option value="pending" <?php if($filter_status == 'pending') echo 'selected'; ?>>Pending</option><option value="processed" <?php if($filter_status == 'processed') echo 'selected'; ?>>Processed</option><option value="declined" <?php if($filter_status == 'declined') echo 'selected'; ?>>Declined</option><option value="">All</option></select></form>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="table-light">
                    <tr><th>Partner</th><th>Requested Amount</th><th>Available Balance</th><th>Requested On</th><th class="text-end">Actions</th></tr>
                </thead>
                <tbody>
                    <?php if (empty($requests)): ?>
                        <tr><td colspan="5" class="text-center p-5 text-muted">No <?php echo htmlspecialchars($filter_status); ?> requests found.</td></tr>
                    <?php else: ?>
                        <?php foreach ($requests as $req): ?>
                        <tr>
                            <td>
                                <strong class="d-block"><?php echo htmlspecialchars($req['business_name']); ?></strong>
                                <small class="text-muted"><?php echo htmlspecialchars($req['full_name']); ?></small>
                            </td>
                            <td class="fw-bold"><?php echo format_price($req['amount']); ?></td>
                            <td><?php echo format_price($req['available_balance'] ?? 0); ?></td>
                            <td><?php echo date('M d, Y', strtotime($req['requested_at'])); ?></td>
                            <td class="text-end">
                                <button type="button" class="btn btn-sm btn-outline-info" data-bs-toggle="modal" data-bs-target="#detailsModal-<?php echo $req['id']; ?>">Details</button>
                                <?php if ($req['status'] === 'pending'): ?>
                                    <form method="POST" class="d-inline" onsubmit="return confirm('Confirm you have SENT the payment.');"><input type="hidden" name="action" value="approve"><input type="hidden" name="request_id" value="<?php echo $req['id']; ?>"><input type="hidden" name="partner_id" value="<?php echo $req['partner_id']; ?>"><button type="submit" class="btn btn-sm btn-success">Approve</button></form>
                                    <button type="button" class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#declineModal-<?php echo $req['id']; ?>">Decline</button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <div class="modal fade" id="detailsModal-<?php echo $req['id']; ?>"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h5 class="modal-title">Payout Details</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><p><strong>Partner:</strong> <?php echo htmlspecialchars($req['full_name']); ?></p><p><strong>Details:</strong></p><pre><?php echo htmlspecialchars($req['payout_details']); ?></pre></div></div></div></div>
                        <div class="modal fade" id="declineModal-<?php echo $req['id']; ?>"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h5 class="modal-title">Decline Request</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><form method="POST"><div class="modal-body"><input type="hidden" name="action" value="decline"><input type="hidden" name="request_id" value="<?php echo $req['id']; ?>"><div class="mb-3"><label for="reason-<?php echo $req['id']; ?>" class="form-label">Reason</label><textarea class="form-control" id="reason-<?php echo $req['id']; ?>" name="reason" rows="3" required></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-danger">Confirm</button></div></form></div></div></div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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