<?php
/**
 * ============================================================================
 * buyer/dashboard.php
 * Main Buyer Dashboard - Statistics, Orders, and Quick Actions
 * ============================================================================
 */

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

// Check login
if (!isLoggedIn()) {
    header('Location: ' . APP_URL . '/auth/login.php');
    exit();
}

// Check user type
if (getUserType() !== 'buyer') {
    header('Location: ' . APP_URL . '/dashboard/');
    exit();
}

// Initialize
use App\Database;
$database = Database::getInstance();
$db = $database->getConnection();
$currentUserId = getUserId();
$currentUserType = getUserType();
$currentUserName = getUserName();
$buyerSystem = new BuyerSystem($database, $currentUserId);

// Get statistics
$stats = $buyerSystem->getStatistics();

// Get recent orders
$recentOrders = $buyerSystem->getPurchaseOrders(['limit' => 5]);

// Get recent activity - FIXED VERSION
$recentActivity = [];

try {
    // Get recent orders activity
    $sql = "SELECT 
                'order_placed' as activity_type,
                o.order_number as reference,
                p.product_name as description,
                o.created_at as timestamp
            FROM orders o
            INNER JOIN products p ON o.product_id = p.id
            WHERE o.buyer_id = ?
            ORDER BY o.created_at DESC
            LIMIT 10";
    
    $stmt = $db->prepare($sql);
    $stmt->execute([$currentUserId]);
    $orderActivity = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get recent favorites activity
    $sql = "SELECT 
                'favorite_added' as activity_type,
                CAST(f.id AS CHAR(50)) as reference,
                p.product_name as description,
                f.created_at as timestamp
            FROM favorites f
            INNER JOIN products p ON f.product_id = p.id
            WHERE f.user_id = ?
            ORDER BY f.created_at DESC
            LIMIT 10";
    
    $stmt = $db->prepare($sql);
    $stmt->execute([$currentUserId]);
    $favoriteActivity = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Merge and sort by timestamp
    $recentActivity = array_merge($orderActivity, $favoriteActivity);
    usort($recentActivity, function($a, $b) {
        return strtotime($b['timestamp']) - strtotime($a['timestamp']);
    });
    $recentActivity = array_slice($recentActivity, 0, 10);
    
} catch (Exception $e) {
    error_log("Error fetching recent activity: " . $e->getMessage());
    $recentActivity = [];
}

// Get trending products
try {
    $sql = "SELECT 
                p.*,
                u.full_name as seller_name,
                COUNT(DISTINCT o.id) as order_count
            FROM products p
            INNER JOIN users u ON p.seller_id = u.id
            LEFT JOIN orders o ON p.id = o.product_id AND o.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
            WHERE p.status = 'available'
            GROUP BY p.id
            ORDER BY order_count DESC, p.views DESC
            LIMIT 6";
    
    $stmt = $db->prepare($sql);
    $stmt->execute();
    $trendingProducts = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    error_log("Error fetching trending products: " . $e->getMessage());
    $trendingProducts = [];
}

// Get top suppliers
$topSuppliers = $buyerSystem->getSuppliers();
$topSuppliers = array_slice($topSuppliers, 0, 5);

// Buyer profile
$profile = $buyerSystem->getProfile();

// Page title and breadcrumbs
$pageTitle = 'Buyer Dashboard';
$breadcrumbs = [
    ['title' => 'Dashboard', 'url' => '']
];

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

require_once __DIR__ . '/includes/helpers.php';
?>

<style>
    .welcome-card {
        background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
        border-radius: 15px;
        color: white;
        padding: 2rem;
        position: relative;
        overflow: hidden;
    }
    
    .welcome-card::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -10%;
        width: 300px;
        height: 300px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 50%;
    }
    
    .stat-card {
        border-radius: 12px;
        border: none;
        transition: all 0.3s ease;
        height: 100%;
    }
    
    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 25px rgba(0,0,0,0.1);
    }
    
    .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.8rem;
    }
    
    .quick-action-btn {
        border-radius: 12px;
        padding: 1.5rem;
        text-align: center;
        transition: all 0.3s ease;
        border: 2px solid #e5e7eb;
        background: white;
        text-decoration: none;
        display: block;
    }
    
    .quick-action-btn:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        border-color: var(--primary-color);
    }
    
    .quick-action-btn i {
        font-size: 2.5rem;
        margin-bottom: 0.5rem;
        display: block;
    }
    
    .product-card {
        border-radius: 12px;
        overflow: hidden;
        transition: all 0.3s ease;
        border: 1px solid #e5e7eb;
        height: 100%;
    }
    
    .product-card:hover {
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        transform: translateY(-3px);
    }
    
    .product-img {
        width: 100%;
        height: 180px;
        object-fit: cover;
    }
    
    .activity-item {
        padding: 1rem;
        border-left: 3px solid var(--primary-color);
        background: #f8f9fa;
        border-radius: 8px;
        margin-bottom: 0.75rem;
    }
    
    .supplier-item {
        padding: 1rem;
        border-radius: 8px;
        background: white;
        border: 1px solid #e5e7eb;
        margin-bottom: 0.75rem;
        transition: all 0.2s ease;
    }
    
    .supplier-item:hover {
        border-color: var(--primary-color);
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    }
</style>

<!-- Welcome Banner -->
<div class="row mb-4">
    <div class="col-12">
        <div class="welcome-card">
            <div class="row align-items-center position-relative">
                <div class="col-md-8">
                    <h2 class="mb-2 fw-bold">Welcome back, <?php echo htmlspecialchars($profile['full_name'] ?? 'Buyer'); ?>! 🛒</h2>
                    <p class="mb-3 opacity-90">
                        <?php echo htmlspecialchars($profile['business_name'] ?? 'Business Name'); ?> - 
                        <?php echo formatBuyerType($buyerSystem->getBuyerType()); ?>
                    </p>
                    <div class="d-flex gap-2 flex-wrap">
                        <?php if ($buyerSystem->isVerified()): ?>
                        <span class="badge bg-success bg-opacity-25 border border-success text-white px-3 py-2">
                            <i class="bi bi-patch-check-fill me-1"></i> Verified Buyer
                        </span>
                        <?php else: ?>
                        <span class="badge bg-warning bg-opacity-25 border border-warning text-white px-3 py-2">
                            <i class="bi bi-exclamation-circle me-1"></i> Not Verified
                        </span>
                        <?php endif; ?>
                        <span class="badge bg-light bg-opacity-25 border border-light text-white px-3 py-2">
                            <i class="bi bi-bar-chart me-1"></i> <?php echo htmlspecialchars($buyerSystem->getBuyingCapacity()); ?> Capacity
                        </span>
                    </div>
                </div>
                <div class="col-md-4 text-md-end mt-3 mt-md-0">
                    <?php if (!$buyerSystem->isVerified() && in_array($buyerSystem->getBuyerType(), ['processor', 'exporter', 'wholesaler'])): ?>
                    <a href="<?php echo APP_URL; ?>/buyer/verification.php" class="btn btn-light btn-lg">
                        <i class="bi bi-patch-check me-2"></i> Get Verified
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Statistics Cards -->
<div class="row mb-4">
    <div class="col-lg-3 col-md-6 mb-3">
        <div class="card stat-card shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-muted mb-1 small">Total Orders</p>
                        <h3 class="mb-0 fw-bold"><?php echo number_format($stats['total_orders']); ?></h3>
                        <small class="text-success">
                            <i class="bi bi-arrow-up"></i> All time
                        </small>
                    </div>
                    <div class="stat-icon bg-primary bg-opacity-10 text-primary">
                        <i class="bi bi-cart-check"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-3 col-md-6 mb-3">
        <div class="card stat-card shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-muted mb-1 small">Pending Orders</p>
                        <h3 class="mb-0 fw-bold"><?php echo number_format($stats['pending_orders']); ?></h3>
                        <small class="text-warning">
                            <i class="bi bi-clock"></i> Awaiting
                        </small>
                    </div>
                    <div class="stat-icon bg-warning bg-opacity-10 text-warning">
                        <i class="bi bi-hourglass-split"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-3 col-md-6 mb-3">
        <div class="card stat-card shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-muted mb-1 small">Total Spent</p>
                        <h3 class="mb-0 fw-bold"><?php echo formatCurrency($stats['total_spent']); ?></h3>
                        <small class="text-info">
                            <i class="bi bi-wallet2"></i> All time
                        </small>
                    </div>
                    <div class="stat-icon bg-success bg-opacity-10 text-success">
                        <i class="bi bi-cash-coin"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-3 col-md-6 mb-3">
        <div class="card stat-card shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-muted mb-1 small">Active Suppliers</p>
                        <h3 class="mb-0 fw-bold"><?php echo number_format($stats['active_suppliers']); ?></h3>
                        <small class="text-primary">
                            <i class="bi bi-people"></i> Connected
                        </small>
                    </div>
                    <div class="stat-icon bg-info bg-opacity-10 text-info">
                        <i class="bi bi-person-check"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Quick Actions -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-0 py-3">
                <h5 class="mb-0 fw-bold"><i class="bi bi-lightning-charge text-warning me-2"></i>Quick Actions</h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-lg-2 col-md-4 col-6">
                        <a href="<?php echo APP_URL; ?>/marketplace/" class="quick-action-btn">
                            <i class="bi bi-shop text-primary"></i>
                            <div class="fw-semibold small">Browse Products</div>
                        </a>
                    </div>
                    <div class="col-lg-2 col-md-4 col-6">
                        <a href="<?php echo APP_URL; ?>/buyer/orders.php" class="quick-action-btn">
                            <i class="bi bi-list-check text-success"></i>
                            <div class="fw-semibold small">My Orders</div>
                        </a>
                    </div>
                    <div class="col-lg-2 col-md-4 col-6">
                        <a href="<?php echo APP_URL; ?>/prices/" class="quick-action-btn">
                            <i class="bi bi-graph-up text-info"></i>
                            <div class="fw-semibold small">Market Prices</div>
                        </a>
                    </div>
                    <div class="col-lg-2 col-md-4 col-6">
                        <a href="<?php echo APP_URL; ?>/chat/" class="quick-action-btn">
                            <i class="bi bi-chat-dots text-warning"></i>
                            <div class="fw-semibold small">Messages</div>
                        </a>
                    </div>
                    <?php if ($buyerSystem->hasPermission('request_quotes')): ?>
                    <div class="col-lg-2 col-md-4 col-6">
                        <a href="<?php echo APP_URL; ?>/buyer/purchase-requests.php" class="quick-action-btn">
                            <i class="bi bi-file-text text-purple"></i>
                            <div class="fw-semibold small">Request Quote</div>
                        </a>
                    </div>
                    <?php endif; ?>
                    <div class="col-lg-2 col-md-4 col-6">
                        <a href="<?php echo APP_URL; ?>/buyer/suppliers.php" class="quick-action-btn">
                            <i class="bi bi-people text-danger"></i>
                            <div class="fw-semibold small">Suppliers</div>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Left Column -->
    <div class="col-lg-8">
        <!-- Recent Orders -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-0 py-3 d-flex justify-content-between align-items-center">
                <h5 class="mb-0 fw-bold"><i class="bi bi-clock-history text-primary me-2"></i>Recent Orders</h5>
                <a href="<?php echo APP_URL; ?>/buyer/orders.php" class="btn btn-sm btn-outline-primary">
                    View All <i class="bi bi-arrow-right ms-1"></i>
                </a>
            </div>
            <div class="card-body">
                <?php if (empty($recentOrders)): ?>
                    <div class="text-center py-5">
                        <i class="bi bi-cart text-muted" style="font-size: 4rem;"></i>
                        <h6 class="mt-3 text-muted">No orders yet</h6>
                        <p class="text-muted small">Start shopping in the marketplace</p>
                        <a href="<?php echo APP_URL; ?>/marketplace/" class="btn btn-primary mt-2">
                            <i class="bi bi-shop me-2"></i>Browse Products
                        </a>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th>Order #</th>
                                    <th>Product</th>
                                    <th>Seller</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Date</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($recentOrders as $order): ?>
                                <tr>
                                    <td><strong><?php echo htmlspecialchars($order['order_number']); ?></strong></td>
                                    <td><?php echo htmlspecialchars($order['product_name']); ?></td>
                                    <td><?php echo htmlspecialchars($order['seller_name']); ?></td>
                                    <td><strong><?php echo formatCurrency($order['total_amount']); ?></strong></td>
                                    <td><?php echo getOrderStatusBadge($order['status']); ?></td>
                                    <td><small><?php echo timeAgo($order['created_at']); ?></small></td>
                                    <td>
                                        <a href="<?php echo APP_URL; ?>/buyer/order-details.php?id=<?php echo $order['id']; ?>" class="btn btn-sm btn-outline-primary">
                                            <i class="bi bi-eye"></i>
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Trending Products -->
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-0 py-3">
                <h5 class="mb-0 fw-bold"><i class="bi bi-fire text-danger me-2"></i>Trending Products</h5>
            </div>
            <div class="card-body">
                <?php if (empty($trendingProducts)): ?>
                    <div class="text-center py-4">
                        <i class="bi bi-box text-muted" style="font-size: 3rem;"></i>
                        <p class="text-muted small mb-0 mt-2">No trending products available</p>
                    </div>
                <?php else: ?>
                    <div class="row g-3">
                        <?php foreach ($trendingProducts as $product): ?>
                        <div class="col-md-4 col-sm-6">
                            <div class="product-card">
                                <?php
                                // Get product image - handle both array and JSON formats
                                $productImage = getProductImage($product['images']);
                                ?>
                                <img src="<?php echo $productImage; ?>" 
                                     class="product-img" 
                                     alt="<?php echo htmlspecialchars($product['product_name']); ?>"
                                     onerror="this.src='<?php echo APP_URL; ?>/assets/images/placeholder-product.jpg'">
                                <div class="p-3">
                                    <h6 class="mb-1"><?php echo truncateText($product['product_name'], 30); ?></h6>
                                    <p class="text-muted small mb-2">
                                        <i class="bi bi-person me-1"></i><?php echo htmlspecialchars($product['seller_name']); ?>
                                    </p>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <span class="text-success fw-bold"><?php echo formatCurrency($product['price_per_unit']); ?></span>
                                        <a href="<?php echo APP_URL; ?>/marketplace/product-details.php?id=<?php echo $product['id']; ?>" class="btn btn-sm btn-primary">
                                            View
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Right Column -->
    <div class="col-lg-4">
        <!-- Top Suppliers -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-0 py-3 d-flex justify-content-between align-items-center">
                <h5 class="mb-0 fw-bold"><i class="bi bi-star text-warning me-2"></i>Top Suppliers</h5>
                <?php if (!empty($topSuppliers)): ?>
                <a href="<?php echo APP_URL; ?>/buyer/suppliers.php" class="btn btn-sm btn-outline-primary">
                    View All
                </a>
                <?php endif; ?>
            </div>
            <div class="card-body">
                <?php if (empty($topSuppliers)): ?>
                    <div class="text-center py-4">
                        <i class="bi bi-people text-muted" style="font-size: 3rem;"></i>
                        <p class="text-muted small mb-0 mt-2">No suppliers yet</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($topSuppliers as $supplier): ?>
                    <div class="supplier-item">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <h6 class="mb-1"><?php echo htmlspecialchars($supplier['full_name']); ?></h6>
                                <p class="mb-1 small text-muted">
                                    <i class="bi bi-geo-alt me-1"></i><?php echo htmlspecialchars($supplier['district_name'] ?? 'N/A'); ?>
                                </p>
                                <div class="mb-1">
                                    <?php echo getRatingStars($supplier['avg_rating']); ?>
                                </div>
                                <div class="d-flex gap-2 small">
                                    <span class="text-muted">
                                        <i class="bi bi-cart me-1"></i><?php echo $supplier['total_orders']; ?> orders
                                    </span>
                                    <span class="text-muted">
                                        <i class="bi bi-cash me-1"></i><?php echo formatCurrency($supplier['total_spent']); ?>
                                    </span>
                                </div>
                            </div>
                            <a href="<?php echo APP_URL; ?>/chat/?user=<?php echo $supplier['id']; ?>" class="btn btn-sm btn-outline-primary">
                                <i class="bi bi-chat"></i>
                            </a>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <!-- Recent Activity -->
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-0 py-3">
                <h5 class="mb-0 fw-bold"><i class="bi bi-activity text-info me-2"></i>Recent Activity</h5>
            </div>
            <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                <?php if (empty($recentActivity)): ?>
                    <div class="text-center py-4">
                        <i class="bi bi-activity text-muted" style="font-size: 3rem;"></i>
                        <p class="text-muted small mb-0 mt-2">No recent activity</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($recentActivity as $activity): ?>
                    <div class="activity-item">
                        <?php if ($activity['activity_type'] === 'order_placed'): ?>
                            <div class="d-flex align-items-start">
                                <div class="me-2">
                                    <i class="bi bi-cart-check text-success"></i>
                                </div>
                                <div class="flex-grow-1">
                                    <p class="mb-1 small"><strong>Order Placed</strong></p>
                                    <p class="mb-1 small text-muted"><?php echo htmlspecialchars($activity['description']); ?></p>
                                    <small class="text-muted"><?php echo timeAgo($activity['timestamp']); ?></small>
                                </div>
                            </div>
                        <?php elseif ($activity['activity_type'] === 'favorite_added'): ?>
                            <div class="d-flex align-items-start">
                                <div class="me-2">
                                    <i class="bi bi-heart text-danger"></i>
                                </div>
                                <div class="flex-grow-1">
                                    <p class="mb-1 small"><strong>Added to Favorites</strong></p>
                                    <p class="mb-1 small text-muted"><?php echo htmlspecialchars($activity['description']); ?></p>
                                    <small class="text-muted"><?php echo timeAgo($activity['timestamp']); ?></small>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php
renderBuyerFooter();
?>