<?php
//Developer: CORE TECH WEB DESIGN
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once dirname(__DIR__) . '/include/config.php';

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true || !isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    header('Location: ' . $site_data['web_url'] . '/signin'); exit();
}

// Handle mark as completed
if (isset($_GET['complete']) && is_numeric($_GET['complete'])) {
    $pdo->prepare("UPDATE seller_withdrawals SET status = 'completed', processed_at = NOW() WHERE id = ?")->execute([$_GET['complete']]);
    header('Location: ' . $site_data['web_url'] . '/admin/seller-withdrawals?msg=completed'); exit();
}

// Handle reject (refund to seller balance)
if (isset($_GET['reject']) && is_numeric($_GET['reject'])) {
    $w = $pdo->prepare("SELECT user_id, amount, fee FROM seller_withdrawals WHERE id = ? AND status = 'pending'");
    $w->execute([$_GET['reject']]);
    $withdrawal = $w->fetch(PDO::FETCH_ASSOC);
    if ($withdrawal) {
        $refund = $withdrawal['amount'] + $withdrawal['fee']; // Refund full amount including fee
        $pdo->prepare("UPDATE users SET seller_balance = seller_balance + ? WHERE id = ?")->execute([$refund, $withdrawal['user_id']]);
        $pdo->prepare("UPDATE seller_withdrawals SET status = 'rejected', processed_at = NOW() WHERE id = ?")->execute([$_GET['reject']]);
    }
    header('Location: ' . $site_data['web_url'] . '/admin/seller-withdrawals?msg=rejected'); exit();
}

include('include/header.php');
$page_title = WEB_NAME . " | Seller Withdrawals";

$withdrawals = $pdo->query("SELECT sw.*, u.username, u.email, u.full_name as user_fullname FROM seller_withdrawals sw LEFT JOIN users u ON sw.user_id = u.id ORDER BY sw.created_at DESC")->fetchAll(PDO::FETCH_ASSOC);

// Stats
$pending_count = 0; $total_paid = 0;
foreach ($withdrawals as $w) {
    if ($w['status'] === 'pending') $pending_count++;
    if ($w['status'] === 'completed') $total_paid += $w['amount'];
}
?>
<title><?php echo $page_title; ?></title>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800"><i class="fas fa-money-bill-transfer mr-2"></i>Seller Withdrawals</h1>

    <?php if (isset($_GET['msg'])): ?>
    <div class="alert alert-success alert-dismissible fade show">
        <?php echo $_GET['msg'] === 'completed' ? 'Withdrawal marked as completed!' : 'Withdrawal rejected and refunded to seller.'; ?>
        <button type="button" class="close" data-dismiss="alert">&times;</button>
    </div>
    <?php endif; ?>

    <!-- Stats -->
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body"><div class="row no-gutters align-items-center"><div class="col mr-2"><div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Pending</div><div class="h5 mb-0 font-weight-bold"><?php echo $pending_count; ?></div></div><div class="col-auto"><i class="fas fa-clock fa-2x text-gray-300"></i></div></div></div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body"><div class="row no-gutters align-items-center"><div class="col mr-2"><div class="text-xs font-weight-bold text-success text-uppercase mb-1">Total Paid</div><div class="h5 mb-0 font-weight-bold">₦<?php echo number_format($total_paid, 2); ?></div></div><div class="col-auto"><i class="fas fa-check-circle fa-2x text-gray-300"></i></div></div></div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card border-left-info shadow h-100 py-2">
                <div class="card-body"><div class="row no-gutters align-items-center"><div class="col mr-2"><div class="text-xs font-weight-bold text-info text-uppercase mb-1">Total Requests</div><div class="h5 mb-0 font-weight-bold"><?php echo count($withdrawals); ?></div></div><div class="col-auto"><i class="fas fa-list fa-2x text-gray-300"></i></div></div></div>
            </div>
        </div>
    </div>

    <!-- Withdrawals Table -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">All Withdrawal Requests</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover">
                    <thead class="thead-light">
                        <tr>
                            <th>#</th>
                            <th>Seller</th>
                            <th>Amount</th>
                            <th>Fee</th>
                            <th>Bank Details</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($withdrawals as $w): ?>
                        <tr class="<?php echo $w['status'] === 'pending' ? 'table-warning' : ''; ?>">
                            <td><?php echo $w['id']; ?></td>
                            <td>
                                <strong><?php echo htmlspecialchars($w['username']); ?></strong><br>
                                <small class="text-muted"><?php echo htmlspecialchars($w['email']); ?></small>
                            </td>
                            <td><strong>₦<?php echo number_format($w['amount'], 2); ?></strong></td>
                            <td><small>₦<?php echo number_format($w['fee'], 2); ?></small></td>
                            <td>
                                <strong><?php echo htmlspecialchars($w['bank_name']); ?></strong><br>
                                <span class="text-primary font-weight-bold"><?php echo htmlspecialchars($w['account_number']); ?></span><br>
                                <small><?php echo htmlspecialchars($w['account_name']); ?></small>
                            </td>
                            <td>
                                <?php if ($w['status'] === 'pending'): ?>
                                    <span class="badge badge-warning">Pending</span>
                                <?php elseif ($w['status'] === 'completed'): ?>
                                    <span class="badge badge-success">Completed</span>
                                <?php else: ?>
                                    <span class="badge badge-danger">Rejected</span>
                                <?php endif; ?>
                            </td>
                            <td><small><?php echo date('M d, Y H:i', strtotime($w['created_at'])); ?></small></td>
                            <td>
                                <?php if ($w['status'] === 'pending'): ?>
                                <a href="<?php echo $site_data['web_url']; ?>/admin/seller-withdrawals?complete=<?php echo $w['id']; ?>" class="btn btn-sm btn-success mb-1" onclick="return confirm('Mark as paid/completed?')">
                                    <i class="fas fa-check"></i> Paid
                                </a>
                                <a href="<?php echo $site_data['web_url']; ?>/admin/seller-withdrawals?reject=<?php echo $w['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Reject and refund to seller?')">
                                    <i class="fas fa-times"></i> Reject
                                </a>
                                <?php else: ?>
                                <small class="text-muted"><?php echo $w['processed_at'] ? date('M d', strtotime($w['processed_at'])) : '-'; ?></small>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($withdrawals)): ?>
                        <tr><td colspan="8" class="text-center text-muted py-4">No withdrawal requests yet</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php include('include/footer.php'); ?>
