<?php
/**
 * ============================================================================
 * dashboard/buyer-dashboard.php
 * Simple Buyer Dashboard - Redirects to buyer portal if profile exists
 * ============================================================================
 */

if (!defined('AIMS_ACCESS')) {
    die('Direct access not permitted');
}

$userId = getUserId();
$userName = getUserName();

$database = new Database();
$db = $database->getConnection();

// Check if buyer has a buyer profile
$sql = "SELECT * FROM buyer_profiles WHERE user_id = ?";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$buyerProfile = $stmt->fetch(PDO::FETCH_ASSOC);

// If buyer has a profile, redirect to buyer portal
if ($buyerProfile) {
    header('Location: ' . APP_URL . '/buyer/');
    exit();
}

// Otherwise, show simple buyer dashboard (for buyers without business profile)

// Buyer Statistics
$stats = [];

// Total Orders
$sql = "SELECT COUNT(*) as total FROM orders WHERE buyer_id = ?";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$stats['total_orders'] = $stmt->fetch()['total'] ?? 0;

// Pending Orders
$sql = "SELECT COUNT(*) as total FROM orders WHERE buyer_id = ? AND status IN ('pending', 'confirmed', 'processing')";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$stats['pending_orders'] = $stmt->fetch()['total'] ?? 0;

// Completed Orders
$sql = "SELECT COUNT(*) as total FROM orders WHERE buyer_id = ? AND status = 'completed'";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$stats['completed_orders'] = $stmt->fetch()['total'] ?? 0;

// Total Spent
$sql = "SELECT COALESCE(SUM(total_amount), 0) as total FROM orders WHERE buyer_id = ? AND status != 'cancelled'";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$stats['total_spent'] = $stmt->fetch()['total'] ?? 0;

// Recent Orders
$sql = "SELECT o.*, p.product_name, p.category, u.full_name as seller_name 
        FROM orders o
        JOIN products p ON o.product_id = p.id
        JOIN users u ON o.seller_id = u.id
        WHERE o.buyer_id = ?
        ORDER BY o.created_at DESC LIMIT 5";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$recentOrders = $stmt->fetchAll();

// Favorites
$sql = "SELECT p.*, u.full_name as seller_name 
        FROM favorites f
        JOIN products p ON f.product_id = p.id
        JOIN users u ON p.seller_id = u.id
        WHERE f.user_id = ? AND p.status = 'available'
        ORDER BY f.created_at DESC LIMIT 5";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$favorites = $stmt->fetchAll();

$pageTitle = 'Buyer Dashboard - AIMS';
require_once '../includes/meta.php';
?>

<style>
    .stat-card {
        border-radius: 15px;
        transition: all 0.3s ease;
        border: none;
        background: white;
    }
    
    .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;
    }
    
    .product-card {
        border-radius: 12px;
        overflow: hidden;
        transition: all 0.3s ease;
        border: 1px solid #e5e7eb;
    }
    
    .product-card:hover {
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        transform: translateY(-3px);
    }
    
    .welcome-banner {
        background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
        border-radius: 15px;
    }
    
    @media (max-width: 768px) {
        body {
            padding-bottom: 100px;
        }
    }
</style>
</head>
<body>

<?php require_once '../includes/header.php'; ?>

<div class="container-fluid py-4">
    <!-- Welcome Banner -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm welcome-banner">
                <div class="card-body text-white p-4">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h3 class="mb-2 fw-bold">Welcome, <?php echo htmlspecialchars($userName); ?>! 🛒</h3>
                            <p class="mb-0 opacity-90">Discover fresh agricultural products from local farmers</p>
                        </div>
                        <div class="col-md-4 text-md-end mt-3 mt-md-0">
                            <a href="<?php echo APP_URL; ?>/buyer/complete-profile.php" class="btn btn-light btn-lg">
                                <i class="bi bi-briefcase me-2"></i> Setup Business Profile
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Info Alert -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="alert alert-info alert-dismissible fade show" role="alert">
                <i class="bi bi-info-circle me-2"></i>
                <strong>Upgrade to Business Buyer!</strong> Set up your business profile to unlock bulk purchasing, quote requests, and contract farming features.
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        </div>
    </div>

    <!-- Statistics -->
    <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 $stats['total_orders']; ?></h3>
                        </div>
                        <div class="stat-icon bg-primary bg-opacity-10 text-primary">
                            <i class="bi bi-cart"></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 $stats['pending_orders']; ?></h3>
                        </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">Completed</p>
                            <h3 class="mb-0 fw-bold"><?php echo $stats['completed_orders']; ?></h3>
                        </div>
                        <div class="stat-icon bg-success bg-opacity-10 text-success">
                            <i class="bi bi-check-circle"></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">UGX <?php echo number_format($stats['total_spent']); ?></h3>
                        </div>
                        <div class="stat-icon bg-info bg-opacity-10 text-info">
                            <i class="bi bi-wallet2"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Main Content -->
        <div class="col-lg-8">
            <!-- Quick Actions -->
            <div class="card border-0 shadow-sm mb-4">
                <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-md-4">
                            <a href="<?php echo APP_URL; ?>/marketplace/" class="btn btn-outline-primary w-100 py-3">
                                <i class="bi bi-shop fs-4 d-block mb-2"></i>
                                <span class="fw-semibold">Browse Products</span>
                            </a>
                        </div>
                        <div class="col-md-4">
                            <a href="<?php echo APP_URL; ?>/prices/" class="btn btn-outline-success w-100 py-3">
                                <i class="bi bi-graph-up fs-4 d-block mb-2"></i>
                                <span class="fw-semibold">Market Prices</span>
                            </a>
                        </div>
                        <div class="col-md-4">
                            <a href="<?php echo APP_URL; ?>/chat/" class="btn btn-outline-info w-100 py-3">
                                <i class="bi bi-chat-dots fs-4 d-block mb-2"></i>
                                <span class="fw-semibold">Chat with Sellers</span>
                            </a>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Recent Orders -->
            <div class="card border-0 shadow-sm">
                <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; ?>/orders/" 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="list-group list-group-flush">
                            <?php foreach ($recentOrders as $order): ?>
                            <div class="list-group-item px-0">
                                <div class="row align-items-center">
                                    <div class="col-md-6">
                                        <h6 class="mb-1"><?php echo htmlspecialchars($order['product_name']); ?></h6>
                                        <p class="mb-0 small text-muted">
                                            <i class="bi bi-person me-1"></i>Seller: <?php echo htmlspecialchars($order['seller_name']); ?>
                                        </p>
                                        <small class="text-muted">
                                            <i class="bi bi-clock me-1"></i><?php echo timeAgo($order['created_at']); ?>
                                        </small>
                                    </div>
                                    <div class="col-md-3 mt-2 mt-md-0">
                                        <span class="badge <?php echo getStatusBadgeClass($order['status']); ?>">
                                            <?php echo ucfirst($order['status']); ?>
                                        </span>
                                    </div>
                                    <div class="col-md-3 text-md-end mt-2 mt-md-0">
                                        <p class="mb-0 fw-bold">UGX <?php echo number_format($order['total_amount']); ?></p>
                                        <a href="<?php echo APP_URL; ?>/orders/view.php?id=<?php echo $order['id']; ?>" class="btn btn-sm btn-outline-primary mt-1">
                                            <i class="bi bi-eye"></i> View
                                        </a>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Sidebar -->
        <div class="col-lg-4">
            <!-- Favorites -->
            <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-heart text-danger me-2"></i>Favorites</h5>
                    <a href="<?php echo APP_URL; ?>/favorites/" class="btn btn-sm btn-outline-danger">
                        View All
                    </a>
                </div>
                <div class="card-body">
                    <?php if (empty($favorites)): ?>
                        <div class="text-center py-4">
                            <i class="bi bi-heart text-muted" style="font-size: 3rem;"></i>
                            <p class="text-muted small mb-0 mt-2">No favorites yet</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($favorites as $product): ?>
                        <div class="d-flex align-items-center mb-3 pb-3 border-bottom">
                            <div class="flex-grow-1">
                                <h6 class="mb-1"><?php echo htmlspecialchars($product['product_name']); ?></h6>
                                <p class="mb-0 small text-muted">
                                    <i class="bi bi-person me-1"></i><?php echo htmlspecialchars($product['seller_name']); ?>
                                </p>
                                <p class="mb-0 fw-bold text-success">UGX <?php echo number_format($product['price_per_unit']); ?></p>
                            </div>
                            <a href="<?php echo APP_URL; ?>/marketplace/product-details.php?id=<?php echo $product['id']; ?>" class="btn btn-sm btn-outline-primary">
                                <i class="bi bi-eye"></i>
                            </a>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Market Tips -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-0 py-3">
                    <h5 class="mb-0 fw-bold"><i class="bi bi-lightbulb text-warning me-2"></i>Buying Tips</h5>
                </div>
                <div class="card-body">
                    <div class="alert alert-info mb-0">
                        <h6 class="alert-heading"><i class="bi bi-info-circle me-2"></i>Smart Shopping</h6>
                        <ul class="mb-0 small ps-3">
                            <li>Compare prices from different sellers</li>
                            <li>Check seller ratings and reviews</li>
                            <li>Contact seller before placing orders</li>
                            <li>Use price alerts for best deals</li>
                        </ul>
                    </div>
                </div>
            </div>

            <!-- Upgrade CTA -->
            <div class="card border-0 shadow-sm" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
                <div class="card-body text-white text-center p-4">
                    <i class="bi bi-star-fill fs-1 mb-3 d-block"></i>
                    <h5 class="fw-bold mb-2">Upgrade to Business Buyer</h5>
                    <p class="small opacity-90 mb-3">Unlock bulk purchasing, contract farming, and advanced features</p>
                    <a href="<?php echo APP_URL; ?>/buyer/complete-profile.php" class="btn btn-light btn-sm">
                        <i class="bi bi-arrow-right me-2"></i>Get Started
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

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