<?php
require_once __DIR__ . '/../config/config.php';

if (!isLoggedIn() || getUserType() !== 'buyer') {
    header('Location: ' . APP_URL . '/auth/login.php');
    exit();
}

use App\Database;
$database = Database::getInstance();
$db = $database->getConnection();
$currentUserId = getUserId();

// Handle unblock action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'unblock') {
    try {
        $sql = "DELETE FROM user_blocks WHERE blocker_id = ? AND blocked_id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$currentUserId, $_POST['user_id']]);
        
        $_SESSION['flash_message'] = 'User unblocked successfully';
        $_SESSION['flash_type'] = 'success';
        header('Location: ' . APP_URL . '/buyer/blocked-users.php');
        exit();
    } catch (Exception $e) {
        $_SESSION['flash_message'] = 'Error: ' . $e->getMessage();
        $_SESSION['flash_type'] = 'error';
    }
}

// Get blocked users
$sql = "SELECT ub.*, u.full_name, u.phone_number, u.user_type, u.profile_picture,
               d.district_name
        FROM user_blocks ub
        INNER JOIN users u ON ub.blocked_id = u.id
        LEFT JOIN districts d ON u.district_id = d.id
        WHERE ub.blocker_id = ?
        ORDER BY ub.created_at DESC";
$stmt = $db->prepare($sql);
$stmt->execute([$currentUserId]);
$blockedUsers = $stmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Blocked Users';
$breadcrumbs = [
    ['title' => 'Settings', 'url' => APP_URL . '/buyer/settings.php'],
    ['title' => 'Blocked Users', 'url' => '']
];

require_once __DIR__ . '/includes/base.php';
renderBuyerHeader($pageTitle, $breadcrumbs);
?>

<div class="card shadow-sm">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0"><i class="bi bi-shield-x me-2"></i>Blocked Users (<?php echo count($blockedUsers); ?>)</h5>
    </div>
    <div class="card-body">
        <?php if (empty($blockedUsers)): ?>
            <div class="text-center py-5">
                <i class="bi bi-shield-check" style="font-size: 4rem; color: #d1d5db;"></i>
                <h5 class="mt-3 text-muted">No blocked users</h5>
                <p class="text-muted">You haven't blocked anyone yet</p>
            </div>
        <?php else: ?>
            <div class="alert alert-info">
                <i class="bi bi-info-circle me-2"></i>
                Blocked users cannot:
                <ul class="mb-0 mt-2">
                    <li>See your contact information</li>
                    <li>Send you messages</li>
                    <li>Bid on your bulk orders</li>
                    <li>Appear in your supplier searches</li>
                </ul>
            </div>
            
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>User</th>
                            <th>Type</th>
                            <th>Location</th>
                            <th>Blocked On</th>
                            <th>Reason</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($blockedUsers as $user): ?>
                        <tr>
                            <td>
                                <div class="d-flex align-items-center">
                                    <?php if ($user['profile_picture']): ?>
                                    <img src="<?php echo htmlspecialchars($user['profile_picture']); ?>" 
                                         class="rounded-circle me-2" width="40" height="40">
                                    <?php else: ?>
                                    <div class="bg-secondary text-white rounded-circle d-flex align-items-center justify-content-center me-2" 
                                         style="width: 40px; height: 40px;">
                                        <?php echo strtoupper(substr($user['full_name'], 0, 1)); ?>
                                    </div>
                                    <?php endif; ?>
                                    <div>
                                        <strong><?php echo htmlspecialchars($user['full_name']); ?></strong><br>
                                        <small class="text-muted"><?php echo htmlspecialchars($user['phone_number']); ?></small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <span class="badge bg-secondary">
                                    <?php echo ucfirst($user['user_type']); ?>
                                </span>
                            </td>
                            <td><?php echo htmlspecialchars($user['district_name'] ?? 'N/A'); ?></td>
                            <td><small><?php echo date('M j, Y', strtotime($user['created_at'])); ?></small></td>
                            <td>
                                <?php if ($user['reason']): ?>
                                <small class="text-muted"><?php echo htmlspecialchars($user['reason']); ?></small>
                                <?php else: ?>
                                <small class="text-muted">No reason given</small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <form method="POST" class="d-inline" onsubmit="return confirm('Unblock this user?')">
                                    <input type="hidden" name="action" value="unblock">
                                    <input type="hidden" name="user_id" value="<?php echo $user['blocked_id']; ?>">
                                    <button type="submit" class="btn btn-sm btn-outline-success">
                                        <i class="bi bi-unlock me-1"></i>Unblock
                                    </button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<div class="card shadow-sm mt-4">
    <div class="card-body">
        <h6><i class="bi bi-info-circle me-2"></i>About Blocking</h6>
        <p class="text-muted mb-0">
            When you block a user, they won't be notified. You can unblock them at any time. 
            Blocking helps you control who can interact with you on the platform.
        </p>
    </div>
</div>

<?php renderBuyerFooter(); ?>