<?php
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();

$supplierId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$supplierId) {
    header('Location: ' . APP_URL . '/buyer/find-suppliers.php');
    exit();
}

// Get supplier details
$sql = "SELECT u.*, d.district_name, r.region_name, s.subcounty_name,
               up.bio, up.tagline, up.farm_size_acres, up.years_in_farming,
               up.cover_photo,
               COUNT(DISTINCT p.id) as product_count,
               COUNT(DISTINCT o.id) as completed_orders,
               COALESCE(AVG(rev.rating), 0) as avg_rating,
               COUNT(DISTINCT rev.id) as review_count
        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 user_profiles up ON u.id = up.user_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.id = ? AND u.user_type = 'farmer'
        GROUP BY u.id";
$stmt = $db->prepare($sql);
$stmt->execute([$supplierId]);
$supplier = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$supplier) {
    $_SESSION['flash_message'] = 'Supplier not found';
    $_SESSION['flash_type'] = 'error';
    header('Location: ' . APP_URL . '/buyer/find-suppliers.php');
    exit();
}

// Get supplier products
$sql = "SELECT * FROM products WHERE seller_id = ? AND status = 'available' ORDER BY created_at DESC LIMIT 6";
$stmt = $db->prepare($sql);
$stmt->execute([$supplierId]);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get recent reviews
$sql = "SELECT r.*, u.full_name, o.order_number
        FROM reviews r
        INNER JOIN users u ON r.reviewer_id = u.id
        LEFT JOIN orders o ON r.order_id = o.id
        WHERE r.reviewed_user_id = ?
        ORDER BY r.created_at DESC LIMIT 5";
$stmt = $db->prepare($sql);
$stmt->execute([$supplierId]);
$reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = $supplier['full_name'] . ' - Supplier Profile';
$breadcrumbs = [
    ['title' => 'Find Suppliers', 'url' => APP_URL . '/buyer/find-suppliers.php'],
    ['title' => 'Supplier Profile', 'url' => '']
];

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

<style>
    .profile-header {
        background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
        color: white;
        padding: 2rem 0;
        border-radius: 12px;
        margin-bottom: 2rem;
    }
    .profile-avatar {
        width: 120px;
        height: 120px;
        border-radius: 50%;
        border: 4px solid white;
        background: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 3rem;
        font-weight: bold;
        color: var(--primary-color);
    }
    .stat-card {
        text-align: center;
        padding: 1.5rem;
        background: rgba(255,255,255,0.1);
        border-radius: 8px;
    }
</style>

<!-- Profile Header -->
<div class="profile-header">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-md-2 text-center">
                <div class="profile-avatar mx-auto">
                    <?php echo strtoupper(substr($supplier['full_name'], 0, 1)); ?>
                </div>
            </div>
            <div class="col-md-6">
                <h2 class="mb-2"><?php echo htmlspecialchars($supplier['full_name']); ?></h2>
                <?php if (!empty($supplier['tagline'])): ?>
                <p class="mb-2 opacity-90"><?php echo htmlspecialchars($supplier['tagline']); ?></p>
                <?php endif; ?>
                <p class="mb-0">
                    <i class="bi bi-geo-alt me-2"></i>
                    <?php 
                    $location = [];
                    if ($supplier['subcounty_name']) $location[] = $supplier['subcounty_name'];
                    if ($supplier['district_name']) $location[] = $supplier['district_name'];
                    echo htmlspecialchars(implode(', ', $location));
                    ?>
                </p>
            </div>
            <div class="col-md-4">
                <div class="d-grid gap-2">
                    <a href="<?php echo APP_URL; ?>/chat/?user=<?php echo $supplier['id']; ?>" 
                       class="btn btn-light">
                        <i class="bi bi-chat-dots me-2"></i>Send Message
                    </a>
                    <a href="tel:<?php echo $supplier['phone_number']; ?>" 
                       class="btn btn-outline-light">
                        <i class="bi bi-telephone me-2"></i><?php echo htmlspecialchars($supplier['phone_number']); ?>
                    </a>
                </div>
            </div>
        </div>
        
        <!-- Stats -->
        <div class="row mt-4 g-3">
            <div class="col-md-3">
                <div class="stat-card">
                    <h3 class="mb-0"><?php echo $supplier['product_count']; ?></h3>
                    <small>Products</small>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <h3 class="mb-0"><?php echo $supplier['completed_orders']; ?></h3>
                    <small>Completed Orders</small>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div><?php echo getRatingStars($supplier['avg_rating']); ?></div>
                    <small><?php echo number_format($supplier['avg_rating'], 1); ?> Rating</small>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <h3 class="mb-0"><?php echo $supplier['years_in_farming']; ?></h3>
                    <small>Years in Farming</small>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Main Content -->
    <div class="col-lg-8">
        <!-- About -->
        <?php if (!empty($supplier['bio'])): ?>
        <div class="card shadow-sm mb-4">
            <div class="card-body">
                <h5 class="mb-3"><i class="bi bi-person me-2"></i>About</h5>
                <p><?php echo nl2br(htmlspecialchars($supplier['bio'])); ?></p>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Products -->
        <div class="card shadow-sm mb-4">
            <div class="card-header bg-white py-3">
                <div class="row align-items-center">
                    <div class="col">
                        <h5 class="mb-0"><i class="bi bi-box me-2"></i>Products (<?php echo count($products); ?>)</h5>
                    </div>
                    <div class="col-auto">
                        <a href="<?php echo APP_URL; ?>/marketplace/?seller=<?php echo $supplier['id']; ?>" 
                           class="btn btn-sm btn-outline-primary">
                            View All
                        </a>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <?php if (empty($products)): ?>
                    <p class="text-muted text-center py-4">No products available</p>
                <?php else: ?>
                    <div class="row g-3">
                        <?php foreach ($products as $product): ?>
                        <div class="col-md-4">
                            <div class="card h-100">
                                <img src="<?php echo getProductImage($product['images']); ?>" 
                                     class="card-img-top" style="height: 150px; object-fit: cover;"
                                     alt="<?php echo htmlspecialchars($product['product_name']); ?>">
                                <div class="card-body">
                                    <h6 class="card-title"><?php echo htmlspecialchars($product['product_name']); ?></h6>
                                    <p class="text-success mb-2">
                                        <strong><?php echo formatCurrency($product['price_per_unit']); ?></strong>
                                        <small class="text-muted">/ <?php echo htmlspecialchars($product['unit']); ?></small>
                                    </p>
                                    <a href="<?php echo APP_URL; ?>/marketplace/product-details.php?id=<?php echo $product['id']; ?>" 
                                       class="btn btn-sm btn-primary w-100">
                                        View Details
                                    </a>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Reviews -->
        <div class="card shadow-sm">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0"><i class="bi bi-star me-2"></i>Reviews (<?php echo $supplier['review_count']; ?>)</h5>
            </div>
            <div class="card-body">
                <?php if (empty($reviews)): ?>
                    <p class="text-muted text-center py-4">No reviews yet</p>
                <?php else: ?>
                    <?php foreach ($reviews as $review): ?>
                    <div class="mb-3 pb-3 border-bottom">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <div>
                                <strong><?php echo htmlspecialchars($review['full_name']); ?></strong>
                                <?php if ($review['order_number']): ?>
                                <small class="text-muted">• Order #<?php echo htmlspecialchars($review['order_number']); ?></small>
                                <?php endif; ?>
                            </div>
                            <div>
                                <?php echo getRatingStars($review['rating']); ?>
                            </div>
                        </div>
                        <?php if ($review['review_text']): ?>
                        <p class="mb-1"><?php echo htmlspecialchars($review['review_text']); ?></p>
                        <?php endif; ?>
                        <small class="text-muted"><?php echo timeAgo($review['created_at']); ?></small>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- Sidebar -->
    <div class="col-lg-4">
        <!-- Contact Info -->
        <div class="card shadow-sm mb-3">
            <div class="card-body">
                <h6 class="mb-3">Contact Information</h6>
                <p class="mb-2">
                    <i class="bi bi-telephone me-2"></i>
                    <a href="tel:<?php echo $supplier['phone_number']; ?>">
                        <?php echo htmlspecialchars($supplier['phone_number']); ?>
                    </a>
                </p>
                <?php if ($supplier['email']): ?>
                <p class="mb-2">
                    <i class="bi bi-envelope me-2"></i>
                    <a href="mailto:<?php echo $supplier['email']; ?>">
                        <?php echo htmlspecialchars($supplier['email']); ?>
                    </a>
                </p>
                <?php endif; ?>
                <p class="mb-0">
                    <i class="bi bi-geo-alt me-2"></i>
                    <?php echo htmlspecialchars($supplier['district_name'] ?? 'Not specified'); ?>
                </p>
            </div>
        </div>
        
        <!-- Farm Info -->
        <?php if ($supplier['farm_size_acres'] > 0): ?>
        <div class="card shadow-sm mb-3">
            <div class="card-body">
                <h6 class="mb-3">Farm Information</h6>
                <p class="mb-2">
                    <strong>Farm Size:</strong> <?php echo number_format($supplier['farm_size_acres'], 2); ?> acres
                </p>
                <p class="mb-0">
                    <strong>Experience:</strong> <?php echo $supplier['years_in_farming']; ?> years
                </p>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Quick Actions -->
        <div class="card shadow-sm">
            <div class="card-body">
                <h6 class="mb-3">Quick Actions</h6>
                <div class="d-grid gap-2">
                    <a href="<?php echo APP_URL; ?>/buyer/purchase-requests.php?supplier=<?php echo $supplier['id']; ?>" 
                       class="btn btn-outline-primary">
                        <i class="bi bi-file-text me-2"></i>Request Quote
                    </a>
                    <a href="<?php echo APP_URL; ?>/marketplace/?seller=<?php echo $supplier['id']; ?>" 
                       class="btn btn-outline-success">
                        <i class="bi bi-shop me-2"></i>View All Products
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<?php renderBuyerFooter(); ?>