<?php
/**
 * ============================================================================
 * friends/find-users.php - Enhanced Find People Page
 * ============================================================================
 */

define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Find People';
$userId = getUserId();

// Get database connection
$database = new Database();
$db = $database->getConnection();
$friendshipClass = new \App\Friendship($db);

// Get filter parameters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$userType = isset($_GET['user_type']) ? trim($_GET['user_type']) : '';
$district = isset($_GET['district']) ? trim($_GET['district']) : '';

// Search users
$users = [];
if ($search || $userType || $district) {
    $users = $friendshipClass->searchAllUsers($userId, $search, $userType, $district);
}

// Get all districts for filter dropdown
$districtsQuery = "SELECT DISTINCT district_name FROM districts ORDER BY district_name";
$districtsResult = $db->query($districtsQuery);
$districts = $districtsResult->fetchAll(PDO::FETCH_COLUMN);

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<style>
    .find-container {
        background: #f0f2f5;
        min-height: 100vh;
    }
    
    .search-header {
        background: white;
        padding: 2rem;
        border-radius: 8px;
        margin-bottom: 1.5rem;
        box-shadow: 0 1px 2px rgba(0,0,0,0.1);
    }
    
    .search-box {
        background: #f0f2f5;
        border: 1px solid #e4e6eb;
        border-radius: 50px;
        padding: 0.75rem 1.5rem;
    }
    
    .search-box:focus {
        background: white;
        border-color: #1877f2;
        outline: none;
    }
    
    .filter-select {
        background: #f0f2f5;
        border: 1px solid #e4e6eb;
        border-radius: 8px;
        padding: 0.75rem 1rem;
    }
    
    .filter-select:focus {
        background: white;
        border-color: #1877f2;
        outline: none;
    }
    
    .user-card {
        background: white;
        border-radius: 8px;
        overflow: hidden;
        transition: all 0.3s;
        box-shadow: 0 1px 2px rgba(0,0,0,0.1);
    }
    
    .user-card:hover {
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        transform: translateY(-2px);
    }
    
    .user-card-image {
        width: 100%;
        height: 200px;
        object-fit: cover;
        background: #f0f2f5;
    }
    
    .user-card-body {
        padding: 1rem;
    }
    
    .user-name {
        font-weight: 600;
        font-size: 1rem;
        margin-bottom: 0.25rem;
        color: #050505;
    }
    
    .user-info {
        font-size: 0.875rem;
        color: #65676b;
        margin-bottom: 0.75rem;
    }
    
    .user-type-badge {
        display: inline-block;
        padding: 0.25rem 0.75rem;
        border-radius: 12px;
        font-size: 0.75rem;
        font-weight: 600;
        margin-bottom: 0.75rem;
    }
    
    .badge-farmer {
        background-color: #d4edda;
        color: #155724;
    }
    
    .badge-buyer {
        background-color: #d1ecf1;
        color: #0c5460;
    }
    
    .badge-extension_officer {
        background-color: #fff3cd;
        color: #856404;
    }
    
    .status-badge {
        font-size: 0.8125rem;
        padding: 0.375rem 0.75rem;
        border-radius: 12px;
        font-weight: 600;
    }
    
    .status-friends {
        background-color: #d4edda;
        color: #155724;
    }
    
    .status-pending {
        background-color: #fff3cd;
        color: #856404;
    }
    
    .btn-action {
        width: 100%;
        padding: 0.5rem;
        border-radius: 6px;
        font-weight: 600;
        border: none;
        cursor: pointer;
        transition: all 0.2s;
        font-size: 0.9rem;
    }
    
    .btn-primary-fb {
        background: #1877f2;
        color: white;
    }
    
    .btn-primary-fb:hover {
        background: #166fe5;
    }
    
    .btn-secondary-fb {
        background: #e4e6eb;
        color: #050505;
    }
    
    .btn-secondary-fb:hover {
        background: #d8dadf;
    }
    
    .btn-outline-fb {
        background: transparent;
        color: #1877f2;
        border: 1px solid #1877f2;
    }
    
    .btn-outline-fb:hover {
        background: #e7f3ff;
    }
    
    .empty-state {
        background: white;
        border-radius: 8px;
        padding: 4rem 2rem;
        text-align: center;
    }
    
    .empty-state i {
        font-size: 5rem;
        color: #d8dadf;
        margin-bottom: 1.5rem;
    }
</style>

<div class="find-container">
    <div class="container py-4">
        <!-- Search Header -->
        <div class="search-header">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h4 class="mb-0" style="font-weight: 700;">
                    <i class="bi bi-search"></i> Find People
                </h4>
                <a href="index.php" class="btn btn-link text-decoration-none">
                    <i class="bi bi-arrow-left"></i> Back to Friends
                </a>
            </div>
            
            <form method="GET" action="">
                <div class="row g-3">
                    <div class="col-md-5">
                        <input type="text" 
                               class="form-control search-box" 
                               name="search" 
                               placeholder="Search by name or phone number..."
                               value="<?= htmlspecialchars($search) ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select filter-select" name="user_type">
                            <option value="">All Types</option>
                            <option value="farmer" <?= $userType === 'farmer' ? 'selected' : '' ?>>Farmers</option>
                            <option value="buyer" <?= $userType === 'buyer' ? 'selected' : '' ?>>Buyers</option>
                            <option value="extension_officer" <?= $userType === 'extension_officer' ? 'selected' : '' ?>>Extension Officers</option>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <select class="form-select filter-select" name="district">
                            <option value="">All Districts</option>
                            <?php foreach ($districts as $dist): ?>
                                <option value="<?= htmlspecialchars($dist) ?>" 
                                        <?= $district === $dist ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($dist) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary w-100" style="padding: 0.75rem;">
                            <i class="bi bi-search"></i> Search
                        </button>
                    </div>
                </div>
            </form>
        </div>
        
        <!-- Search Results -->
        <?php if ($search || $userType || $district): ?>
            <?php if (count($users) > 0): ?>
                <div class="mb-3">
                    <h5 style="font-weight: 700;">Found <?= count($users) ?> people</h5>
                </div>
                
                <div class="row g-3">
                    <?php foreach ($users as $user): ?>
                        <div class="col-lg-3 col-md-4 col-sm-6">
                            <div class="user-card">
                                <img src="<?= APP_URL . '/' . htmlspecialchars($user['profile_picture']) ?>" 
                                     alt="<?= htmlspecialchars($user['full_name']) ?>" 
                                     class="user-card-image"
                                     style="cursor: pointer;"
                                     onclick="window.location.href='profile.php?id=<?= $user['id'] ?>'">
                                <div class="user-card-body">
                                    <div class="user-name"><?= htmlspecialchars($user['full_name']) ?></div>
                                    <div class="user-info">
                                        <i class="bi bi-geo-alt"></i> 
                                        <?= htmlspecialchars($user['district'] ?? 'Unknown') ?>
                                        <?php if ($user['subcounty']): ?>
                                            , <?= htmlspecialchars($user['subcounty']) ?>
                                        <?php endif; ?>
                                    </div>
                                    <span class="user-type-badge badge-<?= $user['user_type'] ?>">
                                        <?= ucfirst(str_replace('_', ' ', $user['user_type'])) ?>
                                    </span>
                                    
                                    <?php
                                    $status = $user['friendship_status'];
                                    ?>
                                    
                                    <div class="d-flex gap-2">
                                        <?php if ($status === 'accepted'): ?>
                                            <button class="btn-action btn-primary-fb flex-grow-1" 
                                                    onclick="window.location.href='../chat/one-on-one.php?user_id=<?= $user['id'] ?>'">
                                                <i class="bi bi-messenger"></i> Message
                                            </button>
                                            <button class="btn-action btn-outline-fb" 
                                                    onclick="window.location.href='profile.php?id=<?= $user['id'] ?>'">
                                                <i class="bi bi-eye"></i>
                                            </button>
                                        <?php elseif ($status === 'pending'): ?>
                                            <button class="btn-action btn-secondary-fb flex-grow-1" disabled>
                                                <i class="bi bi-clock"></i> Pending
                                            </button>
                                            <button class="btn-action btn-outline-fb" 
                                                    onclick="window.location.href='profile.php?id=<?= $user['id'] ?>'">
                                                <i class="bi bi-eye"></i>
                                            </button>
                                        <?php else: ?>
                                            <button class="btn-action btn-primary-fb flex-grow-1"
                                                    onclick="sendFriendRequest(<?= $user['id'] ?>, this)">
                                                <i class="bi bi-person-plus"></i> Add Friend
                                            </button>
                                            <button class="btn-action btn-outline-fb" 
                                                    onclick="window.location.href='profile.php?id=<?= $user['id'] ?>'">
                                                <i class="bi bi-eye"></i>
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="empty-state">
                    <i class="bi bi-search"></i>
                    <h4>No Results Found</h4>
                    <p class="text-muted">Try adjusting your search filters</p>
                </div>
            <?php endif; ?>
        <?php else: ?>
            <div class="empty-state">
                <i class="bi bi-search"></i>
                <h4>Start Your Search</h4>
                <p class="text-muted">Use the filters above to find farmers, buyers, and extension officers</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Toast -->
<div class="position-fixed top-0 end-0 p-3" style="z-index: 11">
    <div id="toast" class="toast align-items-center" role="alert">
        <div class="d-flex">
            <div class="toast-body"></div>
            <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
function showToast(message, type = 'success') {
    const toast = document.getElementById('toast');
    const toastBody = toast.querySelector('.toast-body');
    
    toast.classList.remove('bg-success', 'bg-danger', 'text-white');
    toast.classList.add(type === 'success' ? 'bg-success' : 'bg-danger', 'text-white');
    toastBody.textContent = message;
    
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();
}

function sendFriendRequest(friendId, btn) {
    const $btn = $(btn);
    const originalHtml = $btn.html();
    
    $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');
    
    $.post('<?= APP_URL ?>/friends/ajax/send-request.php', {
        friend_id: friendId
    })
    .done(function(response) {
        if (response.success) {
            showToast(response.message, 'success');
            $btn.html('<i class="bi bi-clock"></i> Pending')
                .removeClass('btn-primary-fb')
                .addClass('btn-secondary-fb');
        } else {
            showToast(response.message, 'error');
            $btn.prop('disabled', false).html(originalHtml);
        }
    })
    .fail(function() {
        showToast('Failed to send friend request. Please try again.', 'error');
        $btn.prop('disabled', false).html(originalHtml);
    });
}
</script>

<?php
include_once __DIR__ . '/../includes/footer.php';
include_once __DIR__ . '/../includes/bottom-nav.php';
?>