<?php
/**
 * ============================================================================
 * buyer/find-suppliers.php
 * Find and Connect with Agricultural Suppliers
 * ============================================================================
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/BuyerSystem.php';

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

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

// Build search query
$searchParams = [];
$sql = "SELECT DISTINCT u.id, u.full_name, u.phone_number, u.email,
               d.district_name, r.region_name, s.subcounty_name,
               COUNT(DISTINCT p.id) as product_count,
               COUNT(DISTINCT o.id) as total_sales,
               COALESCE(AVG(rev.rating), 0) as avg_rating,
               GROUP_CONCAT(DISTINCT p.category) as categories
        FROM users u
        LEFT JOIN districts d ON u.district_id = d.id
        LEFT JOIN regions r ON d.region_id = r.id
        LEFT JOIN subcounties s ON u.subcounty_id = s.id
        LEFT JOIN products p ON u.id = p.seller_id AND p.status = 'available'
        LEFT JOIN orders o ON u.id = o.seller_id AND o.status = 'completed'
        LEFT JOIN reviews rev ON u.id = rev.reviewed_user_id
        WHERE u.user_type = 'farmer' AND u.is_active = 1";

// Apply filters
if (!empty($_GET['category'])) {
    $sql .= " AND p.category = ?";
    $searchParams[] = $_GET['category'];
}

if (!empty($_GET['district'])) {
    $sql .= " AND u.district_id = ?";
    $searchParams[] = $_GET['district'];
}

if (!empty($_GET['region'])) {
    $sql .= " AND d.region_id = ?";
    $searchParams[] = $_GET['region'];
}

if (!empty($_GET['search'])) {
    $sql .= " AND (u.full_name LIKE ? OR p.product_name LIKE ?)";
    $searchTerm = '%' . $_GET['search'] . '%';
    $searchParams[] = $searchTerm;
    $searchParams[] = $searchTerm;
}

if (!empty($_GET['min_rating'])) {
    // This will be applied after grouping
    $minRating = (float)$_GET['min_rating'];
}

$sql .= " GROUP BY u.id, u.full_name, u.phone_number, u.email, 
          d.district_name, r.region_name, s.subcounty_name";

if (isset($minRating)) {
    $sql .= " HAVING avg_rating >= ?";
    $searchParams[] = $minRating;
}

$sql .= " ORDER BY product_count DESC, avg_rating DESC";

$stmt = $db->prepare($sql);
$stmt->execute($searchParams);
$suppliers = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get filter options
$categoriesQuery = "SELECT DISTINCT category FROM products WHERE status = 'approved' ORDER BY category";
$categories = $db->query($categoriesQuery)->fetchAll(PDO::FETCH_COLUMN);

$districtsQuery = "SELECT id, district_name FROM districts ORDER BY district_name";
$districts = $db->query($districtsQuery)->fetchAll(PDO::FETCH_ASSOC);

$regionsQuery = "SELECT id, region_name FROM regions ORDER BY region_name";
$regions = $db->query($regionsQuery)->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Find Suppliers';
$breadcrumbs = [['title' => 'Find Suppliers', 'url' => '']];

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

<style>
    .supplier-card {
        transition: all 0.3s ease;
        border: 1px solid #e5e7eb;
        border-radius: 12px;
        overflow: hidden;
    }
    .supplier-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 16px rgba(0,0,0,0.1);
        border-color: var(--primary-color);
    }
    .supplier-avatar {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 2rem;
        font-weight: bold;
    }
    .category-badge {
        display: inline-block;
        padding: 0.25rem 0.75rem;
        margin: 0.25rem;
        border-radius: 20px;
        font-size: 0.75rem;
        background: #e5e7eb;
        color: #1f2937;
    }
    .filter-card {
        position: sticky;
        top: 20px;
    }
</style>

<div class="row mb-4">
    <div class="col">
        <h4><i class="bi bi-search me-2"></i>Find Agricultural Suppliers</h4>
        <p class="text-muted">Connect with reliable farmers and suppliers across Uganda</p>
    </div>
</div>

<div class="row">
    <!-- Filters Sidebar -->
    <div class="col-lg-3">
        <div class="card shadow-sm filter-card">
            <div class="card-header bg-white py-3">
                <h6 class="mb-0"><i class="bi bi-funnel me-2"></i>Filters</h6>
            </div>
            <div class="card-body">
                <form method="GET" id="filterForm">
                    <!-- Search -->
                    <div class="mb-3">
                        <label class="form-label small text-muted">Search</label>
                        <input type="text" name="search" class="form-control" 
                               placeholder="Name or product..." 
                               value="<?php echo htmlspecialchars($_GET['search'] ?? ''); ?>">
                    </div>
                    
                    <!-- Category -->
                    <div class="mb-3">
                        <label class="form-label small text-muted">Product Category</label>
                        <select name="category" class="form-select">
                            <option value="">All Categories</option>
                            <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo $cat; ?>" 
                                    <?php echo (isset($_GET['category']) && $_GET['category'] === $cat) ? 'selected' : ''; ?>>
                                <?php echo ucfirst(str_replace('_', ' ', $cat)); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- Region -->
                    <div class="mb-3">
                        <label class="form-label small text-muted">Region</label>
                        <select name="region" class="form-select">
                            <option value="">All Regions</option>
                            <?php foreach ($regions as $region): ?>
                            <option value="<?php echo $region['id']; ?>"
                                    <?php echo (isset($_GET['region']) && $_GET['region'] == $region['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($region['region_name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- District -->
                    <div class="mb-3">
                        <label class="form-label small text-muted">District</label>
                        <select name="district" class="form-select">
                            <option value="">All Districts</option>
                            <?php foreach ($districts as $district): ?>
                            <option value="<?php echo $district['id']; ?>"
                                    <?php echo (isset($_GET['district']) && $_GET['district'] == $district['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($district['district_name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- Minimum Rating -->
                    <div class="mb-3">
                        <label class="form-label small text-muted">Minimum Rating</label>
                        <select name="min_rating" class="form-select">
                            <option value="">Any Rating</option>
                            <option value="4" <?php echo (isset($_GET['min_rating']) && $_GET['min_rating'] == '4') ? 'selected' : ''; ?>>
                                4+ Stars
                            </option>
                            <option value="3" <?php echo (isset($_GET['min_rating']) && $_GET['min_rating'] == '3') ? 'selected' : ''; ?>>
                                3+ Stars
                            </option>
                            <option value="2" <?php echo (isset($_GET['min_rating']) && $_GET['min_rating'] == '2') ? 'selected' : ''; ?>>
                                2+ Stars
                            </option>
                        </select>
                    </div>
                    
                    <!-- Buttons -->
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-search me-2"></i>Apply Filters
                        </button>
                        <a href="<?php echo APP_URL; ?>/buyer/find-suppliers.php" class="btn btn-outline-secondary">
                            <i class="bi bi-x-circle me-2"></i>Clear All
                        </a>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Quick Stats -->
        <div class="card shadow-sm mt-3">
            <div class="card-body">
                <h6 class="mb-3">Search Results</h6>
                <div class="d-flex justify-content-between mb-2">
                    <span class="text-muted">Total Suppliers:</span>
                    <strong><?php echo count($suppliers); ?></strong>
                </div>
                <div class="d-flex justify-content-between">
                    <span class="text-muted">Avg Products:</span>
                    <strong>
                        <?php 
                        $avgProducts = !empty($suppliers) 
                            ? array_sum(array_column($suppliers, 'product_count')) / count($suppliers) 
                            : 0;
                        echo number_format($avgProducts, 1);
                        ?>
                    </strong>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Suppliers Grid -->
    <div class="col-lg-9">
        <?php if (empty($suppliers)): ?>
            <div class="card shadow-sm">
                <div class="card-body text-center py-5">
                    <i class="bi bi-search" style="font-size: 4rem; color: #d1d5db;"></i>
                    <h5 class="mt-3 text-muted">No suppliers found</h5>
                    <p class="text-muted">Try adjusting your search filters</p>
                </div>
            </div>
        <?php else: ?>
            <div class="row g-3">
                <?php foreach ($suppliers as $supplier): ?>
                <div class="col-md-6">
                    <div class="supplier-card card h-100">
                        <div class="card-body">
                            <div class="d-flex align-items-start mb-3">
                                <div class="supplier-avatar me-3">
                                    <?php echo strtoupper(substr($supplier['full_name'], 0, 1)); ?>
                                </div>
                                <div class="flex-grow-1">
                                    <h5 class="mb-1"><?php echo htmlspecialchars($supplier['full_name']); ?></h5>
                                    <div class="mb-2">
                                        <?php echo getRatingStars($supplier['avg_rating']); ?>
                                        <small class="text-muted ms-2">
                                            (<?php echo number_format($supplier['avg_rating'], 1); ?>)
                                        </small>
                                    </div>
                                    <p class="text-muted small mb-1">
                                        <i class="bi bi-geo-alt me-1"></i>
                                        <?php 
                                        $location = [];
                                        if (!empty($supplier['subcounty_name'])) $location[] = $supplier['subcounty_name'];
                                        if (!empty($supplier['district_name'])) $location[] = $supplier['district_name'];
                                        echo htmlspecialchars(implode(', ', $location) ?: 'Location not specified');
                                        ?>
                                    </p>
                                </div>
                            </div>
                            
                            <!-- Stats -->
                            <div class="row text-center mb-3">
                                <div class="col-6">
                                    <div class="p-2 bg-light rounded">
                                        <div class="h5 mb-0 text-primary"><?php echo $supplier['product_count']; ?></div>
                                        <small class="text-muted">Products</small>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="p-2 bg-light rounded">
                                        <div class="h5 mb-0 text-success"><?php echo $supplier['total_sales']; ?></div>
                                        <small class="text-muted">Sales</small>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Categories -->
                            <?php if (!empty($supplier['categories'])): ?>
                            <div class="mb-3">
                                <?php 
                                $cats = array_unique(explode(',', $supplier['categories']));
                                foreach ($cats as $cat):
                                ?>
                                <span class="category-badge">
                                    <i class="<?php echo getCategoryIcon($cat); ?> me-1"></i>
                                    <?php echo ucfirst(str_replace('_', ' ', $cat)); ?>
                                </span>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>
                            
                            <!-- Actions -->
                            <div class="d-grid gap-2">
                                <a href="<?php echo APP_URL; ?>/buyer/supplier-profile.php?id=<?php echo $supplier['id']; ?>" 
                                   class="btn btn-outline-primary">
                                    <i class="bi bi-eye me-2"></i>View Profile
                                </a>
                                <div class="btn-group">
                                    <a href="<?php echo APP_URL; ?>/chat/?user=<?php echo $supplier['id']; ?>" 
                                       class="btn btn-primary">
                                        <i class="bi bi-chat-dots me-1"></i>Message
                                    </a>
                                    <a href="tel:<?php echo $supplier['phone_number']; ?>" 
                                       class="btn btn-success">
                                        <i class="bi bi-telephone"></i>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            
            <!-- Load More / Pagination -->
            <?php if (count($suppliers) >= 20): ?>
            <div class="text-center mt-4">
                <button class="btn btn-outline-primary" onclick="loadMore()">
                    <i class="bi bi-arrow-down-circle me-2"></i>Load More Suppliers
                </button>
            </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<script>
function loadMore() {
    // Implement pagination/load more functionality
    showToast('Loading more suppliers...', 'info');
}

// Auto-submit form on filter change
document.querySelectorAll('#filterForm select').forEach(select => {
    select.addEventListener('change', function() {
        document.getElementById('filterForm').submit();
    });
});
</script>

<?php renderBuyerFooter(); ?>