<?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 approve
if (isset($_GET['approve']) && is_numeric($_GET['approve'])) {
    $app = $pdo->prepare("SELECT user_id FROM seller_applications WHERE id = ?");
    $app->execute([$_GET['approve']]);
    $application = $app->fetch(PDO::FETCH_ASSOC);
    if ($application) {
        $pdo->prepare("UPDATE seller_applications SET status = 'approved' WHERE id = ?")->execute([$_GET['approve']]);
        $pdo->prepare("UPDATE users SET is_seller = 1 WHERE id = ?")->execute([$application['user_id']]);
    }
    header('Location: ' . $site_data['web_url'] . '/admin/seller-applications?msg=approved'); exit();
}

// Handle reject
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'reject_seller') {
    $app = $pdo->prepare("SELECT user_id, fee_paid FROM seller_applications WHERE id = ?");
    $app->execute([intval($_POST['id'])]);
    $application = $app->fetch(PDO::FETCH_ASSOC);
    if ($application) {
        $pdo->prepare("UPDATE seller_applications SET status = 'rejected', rejection_reason = ? WHERE id = ?")->execute([trim($_POST['reason'] ?? ''), intval($_POST['id'])]);
        // Refund fee
        $pdo->prepare("UPDATE users SET main_balance = main_balance + ? WHERE id = ?")->execute([$application['fee_paid'], $application['user_id']]);
    }
    header('Location: ' . $site_data['web_url'] . '/admin/seller-applications?msg=rejected'); exit();
}

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

$applications = $pdo->query("SELECT sa.*, u.username, u.email FROM seller_applications sa LEFT JOIN users u ON sa.user_id = u.id ORDER BY sa.created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
?>
<title><?php echo $page_title; ?></title>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800"><i class="fas fa-user-tie mr-2"></i>Seller Applications</h1>

    <?php if (isset($_GET['msg'])): ?>
    <div class="alert alert-success alert-dismissible fade show">
        <?php echo $_GET['msg'] === 'approved' ? 'Seller approved! User can now list accounts.' : 'Application rejected. Fee refunded to user.'; ?>
        <button type="button" class="close" data-dismiss="alert">&times;</button>
    </div>
    <?php endif; ?>

    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">All Applications (<?php echo count($applications); ?>)</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover">
                    <thead class="thead-light">
                        <tr>
                            <th>User</th>
                            <th>Full Name</th>
                            <th>Phone</th>
                            <th>Bank Details</th>
                            <th>Fee Paid</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($applications as $app): ?>
                        <tr>
                            <td><small><strong><?php echo htmlspecialchars($app['username']); ?></strong><br><span class="text-muted"><?php echo htmlspecialchars($app['email']); ?></span></small></td>
                            <td><?php echo htmlspecialchars($app['full_name']); ?></td>
                            <td><?php echo htmlspecialchars($app['phone']); ?></td>
                            <td><small><?php echo htmlspecialchars($app['bank_name']); ?><br><?php echo htmlspecialchars($app['account_number']); ?><br><?php echo htmlspecialchars($app['account_name']); ?></small></td>
                            <td>₦<?php echo number_format($app['fee_paid'], 2); ?></td>
                            <td>
                                <?php if ($app['status'] === 'approved'): ?>
                                    <span class="badge badge-success">Approved</span>
                                <?php elseif ($app['status'] === 'rejected'): ?>
                                    <span class="badge badge-danger">Rejected</span>
                                <?php else: ?>
                                    <span class="badge badge-warning">Pending</span>
                                <?php endif; ?>
                            </td>
                            <td><small><?php echo date('M d, Y', strtotime($app['created_at'])); ?></small></td>
                            <td>
                                <?php if ($app['status'] === 'pending'): ?>
                                <a href="<?php echo $site_data['web_url']; ?>/admin/seller-applications?approve=<?php echo $app['id']; ?>" class="btn btn-sm btn-success mb-1" onclick="return confirm('Approve this seller?')"><i class="fas fa-check"></i></a>
                                <button class="btn btn-sm btn-danger" onclick="rejectSeller(<?php echo $app['id']; ?>)"><i class="fas fa-times"></i></button>
                                <?php else: ?>
                                <small class="text-muted"><?php echo ucfirst($app['status']); ?></small>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($applications)): ?>
                        <tr><td colspan="8" class="text-center text-muted py-4">No applications yet</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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

<script>
function rejectSeller(id) {
    Swal.fire({
        title: 'Reject Application',
        html: '<p class="text-muted">Fee will be refunded to the user.</p>',
        input: 'text',
        inputLabel: 'Reason (optional)',
        inputPlaceholder: 'e.g. Incomplete information',
        showCancelButton: true,
        confirmButtonColor: '#dc3545',
        confirmButtonText: 'Reject & Refund'
    }).then(function(result) {
        if (result.isConfirmed) {
            var form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = '<input type="hidden" name="action" value="reject_seller"><input type="hidden" name="id" value="' + id + '"><input type="hidden" name="reason" value="' + (result.value || '') + '">';
            document.body.appendChild(form);
            form.submit();
        }
    });
}
</script>
