<?php
/**
 * ============================================================================
 * dashboard/farmer-dashboard.php (Updated with Widgets)
 * ============================================================================
 */

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

// Get user information
$userId = getUserId();
$userName = getUserName();
$userPhone = getUserPhone();

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

// Fetch dashboard statistics
$stats = [];

// Total Products
$sql = "SELECT COUNT(*) as total FROM products WHERE seller_id = ?";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$stats['total_products'] = $stmt->fetch()['total'] ?? 0;

// Active Products
$sql = "SELECT COUNT(*) as total FROM products WHERE seller_id = ? AND status = 'available'";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$stats['active_products'] = $stmt->fetch()['total'] ?? 0;

// Total Sales (this month)
$sql = "SELECT COUNT(*) as total, COALESCE(SUM(price_per_unit * quantity), 0) as revenue 
        FROM products 
        WHERE seller_id = ? AND status = 'sold' 
        AND MONTH(updated_at) = MONTH(CURRENT_DATE())
        AND YEAR(updated_at) = YEAR(CURRENT_DATE())";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$salesData = $stmt->fetch();
$stats['sales_count'] = $salesData['total'] ?? 0;
$stats['revenue'] = $salesData['revenue'] ?? 0;

// Unread Messages
$sql = "SELECT COUNT(DISTINCT m.chat_id) as unread_chats
        FROM messages m
        JOIN chat_members cm ON m.chat_id = cm.chat_id
        WHERE cm.user_id = ? AND m.sender_id != ? 
        AND m.created_at > COALESCE(cm.last_read_at, '2000-01-01')";
$stmt = $db->prepare($sql);
$stmt->execute([$userId, $userId]);
$stats['unread_chats'] = $stmt->fetch()['unread_chats'] ?? 0;

// Farm Statistics
$sql = "SELECT COUNT(*) as total_farms, COALESCE(SUM(total_acres), 0) as total_acres 
        FROM farms WHERE user_id = ?";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$farmStats = $stmt->fetch();
$stats['total_farms'] = $farmStats['total_farms'] ?? 0;
$stats['total_acres'] = $farmStats['total_acres'] ?? 0;

// Enterprises Count
$sql = "SELECT COUNT(*) as total FROM enterprises 
        WHERE farm_id IN (SELECT id FROM farms WHERE user_id = ?)";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$stats['total_enterprises'] = $stmt->fetch()['total'] ?? 0;

// Recent Products
$sql = "SELECT * FROM products WHERE seller_id = ? ORDER BY created_at DESC LIMIT 5";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$recentProducts = $stmt->fetchAll();

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

<style>
    .welcome-banner {
        background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-light) 100%);
        border-radius: 15px;
        color: white;
    }
    
    @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="welcome-banner shadow-sm">
                <div class="p-4">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h3 class="mb-2 fw-bold">Welcome back, <?php echo htmlspecialchars($userName); ?>! 👋</h3>
                            <p class="mb-0 opacity-90">Here's what's happening with your farm today</p>
                        </div>
                        <div class="col-md-4 text-md-end mt-3 mt-md-0">
                            <p class="mb-1"><i class="bi bi-calendar3 me-2"></i><?php echo date('l, F j, Y'); ?></p>
                            <p class="mb-0"><i class="bi bi-clock me-2"></i><?php echo date('g:i A'); ?></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-lg-3 col-md-6 mb-3">
            <?php 
            require_once 'widgets/stats-card.php';
            renderStatCard('Total Products', $stats['total_products'], 'box-seam', 'primary', $stats['active_products'] . ' active');
            ?>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <?php 
            renderStatCard('Monthly Sales', $stats['sales_count'], 'graph-up-arrow', 'success', 'UGX ' . number_format($stats['revenue']));
            ?>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <?php 
            renderStatCard('Farm Size', number_format($stats['total_acres'], 1) . ' acres', 'tree', 'warning', $stats['total_enterprises'] . ' enterprises');
            ?>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <?php 
            renderStatCard('Messages', $stats['unread_chats'], 'chat-dots', 'info', 'unread chats');
            ?>
        </div>
    </div>

    <div class="row">
        <!-- Main Content Column -->
        <div class="col-lg-8">
            <!-- Quick Actions Widget -->
            <div class="mb-4">
                <?php require_once 'widgets/quick-actions.php'; ?>
            </div>

            <!-- Sales Chart Widget -->
            <div class="mb-4">
                <?php require_once 'widgets/sales-chart.php'; ?>
            </div>

            <!-- Recent Products -->
            <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-box-seam text-primary me-2"></i>Recent Products
                    </h5>
                    <a href="<?php echo APP_URL; ?>/marketplace/my-products.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($recentProducts)): ?>
                        <div class="text-center py-5">
                            <i class="bi bi-inbox text-muted" style="font-size: 4rem;"></i>
                            <h6 class="mt-3 text-muted">No products yet</h6>
                            <p class="text-muted small">Start by adding your first product to the marketplace</p>
                            <a href="<?php echo APP_URL; ?>/marketplace/add-product.php" class="btn btn-primary mt-2">
                                <i class="bi bi-plus-circle me-2"></i>Add Product
                            </a>
                        </div>
                    <?php else: ?>
                        <div class="list-group list-group-flush">
                            <?php foreach ($recentProducts as $product): ?>
                            <div class="list-group-item px-0">
                                <div class="row align-items-center">
                                    <div class="col-auto">
                                        <?php 
                                        $productIcon = '📦';
                                        if ($product['category'] == 'sugar_cane') $productIcon = '🌾';
                                        elseif ($product['category'] == 'poultry') $productIcon = '🐔';
                                        elseif ($product['category'] == 'vegetables') $productIcon = '🥬';
                                        elseif ($product['category'] == 'maize') $productIcon = '🌽';
                                        ?>
                                        <div class="bg-light rounded p-2" style="font-size: 2rem;">
                                            <?php echo $productIcon; ?>
                                        </div>
                                    </div>
                                    <div class="col">
                                        <h6 class="mb-1"><?php echo htmlspecialchars($product['product_name']); ?></h6>
                                        <p class="mb-0 small text-muted">
                                            <?php echo $product['quantity']; ?> <?php echo $product['unit']; ?> • 
                                            UGX <?php echo number_format($product['price_per_unit']); ?>
                                        </p>
                                    </div>
                                    <div class="col-auto">
                                        <span class="badge <?php echo getStatusBadgeClass($product['status']); ?>">
                                            <?php echo ucfirst($product['status']); ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Sidebar Column -->
        <div class="col-lg-4">
            <!-- Weather Widget -->
            <div class="mb-4">
                <?php require_once 'widgets/weather-widget.php'; ?>
            </div>

            <!-- Notifications Widget -->
            <div class="mb-4">
                <?php require_once 'widgets/notifications-widget.php'; ?>
            </div>

            <!-- Recent Activity Widget -->
            <div class="mb-4">
                <?php require_once 'widgets/recent-activity.php'; ?>
            </div>

            <!-- Farming Tips Widget -->
            <?php require_once 'widgets/farming-tips.php'; ?>
        </div>
    </div>
</div>

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