<?php
/**
 * ============================================================================
 * prices/index.php - Enhanced Market Prices Dashboard
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Market Prices';
$userId = getUserId();

// Initialize database
$database = new Database();
$db = $database->getConnection();
$priceClass = new \App\Price($db);

// Get filters
$productType = $_GET['product'] ?? '';
$location = $_GET['location'] ?? '';
$sortBy = $_GET['sort'] ?? 'date'; // date, price_asc, price_desc
$viewMode = $_GET['view'] ?? 'grid'; // grid or table

// Get prices
$prices = $priceClass->getCurrentPrices($productType, $location);

// Get product types and locations for filters
$productTypes = $priceClass->getProductTypes();
$locations = $priceClass->getMarketLocations();

// Get price statistics
$stats = $priceClass->getStatistics($productType);

// Group and process prices
$pricesByProduct = [];
foreach ($prices as $price) {
    if (!isset($pricesByProduct[$price['product_type']])) {
        $pricesByProduct[$price['product_type']] = [
            'prices' => [],
            'avg_price' => 0,
            'min_price' => PHP_FLOAT_MAX,
            'max_price' => 0,
            'trend' => 'stable'
        ];
    }
    
    $pricesByProduct[$price['product_type']]['prices'][] = $price;
    $pricesByProduct[$price['product_type']]['min_price'] = min(
        $pricesByProduct[$price['product_type']]['min_price'], 
        $price['price']
    );
    $pricesByProduct[$price['product_type']]['max_price'] = max(
        $pricesByProduct[$price['product_type']]['max_price'], 
        $price['price']
    );
}

// Calculate averages
foreach ($pricesByProduct as $product => &$data) {
    $priceSum = array_sum(array_column($data['prices'], 'price'));
    $data['avg_price'] = $priceSum / count($data['prices']);
}

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<style>
.price-card {
    transition: all 0.3s ease;
    border-left: 4px solid #059669;
}

.price-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 30px rgba(0,0,0,0.15);
}

.price-badge {
    font-size: 1.5rem;
    padding: 0.5rem 1rem;
    border-radius: 10px;
}

.trend-up {
    color: #dc2626;
}

.trend-down {
    color: #059669;
}

.trend-stable {
    color: #6b7280;
}

.market-location-badge {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.875rem;
}

.quick-filter-btn {
    border-radius: 20px;
    padding: 0.5rem 1.5rem;
    transition: all 0.3s;
}

.quick-filter-btn:hover {
    transform: scale(1.05);
}

.price-range-indicator {
    height: 8px;
    background: linear-gradient(90deg, #059669 0%, #fbbf24 50%, #dc2626 100%);
    border-radius: 10px;
    position: relative;
}

.price-marker {
    position: absolute;
    top: -4px;
    width: 16px;
    height: 16px;
    background: white;
    border: 3px solid #059669;
    border-radius: 50%;
    transform: translateX(-50%);
}

.stats-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 15px;
    padding: 1.5rem;
    margin-bottom: 1.5rem;
}

.view-toggle {
    background: #f3f4f6;
    border-radius: 10px;
    padding: 0.25rem;
}

.view-toggle .btn {
    border-radius: 8px;
    border: none;
}

.view-toggle .btn.active {
    background: white;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.empty-state {
    padding: 4rem 2rem;
    text-align: center;
}

.empty-state i {
    font-size: 4rem;
    color: #d1d5db;
    margin-bottom: 1rem;
}

@media (max-width: 768px) {
    .price-badge {
        font-size: 1.25rem;
    }
    
    .stats-card {
        margin-bottom: 1rem;
    }
}
</style>

<div class="container-fluid py-4">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                <div>
                    <h2 class="mb-1">
                        <i class="bi bi-graph-up-arrow text-success"></i> Market Prices
                    </h2>
                    <p class="text-muted mb-0">Real-time agricultural product prices across Uganda</p>
                </div>
                <div class="d-flex gap-2">
                    <a href="<?php echo APP_URL; ?>/prices/comparison.php" class="btn btn-outline-primary">
                        <i class="bi bi-arrow-left-right"></i> Compare
                    </a>
                    <a href="<?php echo APP_URL; ?>/prices/trends.php" class="btn btn-outline-info">
                        <i class="bi bi-graph-up"></i> Trends
                    </a>
                    <a href="<?php echo APP_URL; ?>/prices/alerts.php" class="btn btn-primary">
                        <i class="bi bi-bell"></i> My Alerts
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Statistics Summary -->
    <?php if (!empty($stats)): ?>
    <div class="stats-card">
        <div class="row text-center">
            <div class="col-md-3 col-6 mb-3 mb-md-0">
                <h3 class="mb-1"><?php echo count($productTypes); ?></h3>
                <small class="opacity-75">Products Tracked</small>
            </div>
            <div class="col-md-3 col-6 mb-3 mb-md-0">
                <h3 class="mb-1"><?php echo count($locations); ?></h3>
                <small class="opacity-75">Market Locations</small>
            </div>
            <div class="col-md-3 col-6">
                <h3 class="mb-1"><?php echo count($prices); ?></h3>
                <small class="opacity-75">Price Entries</small>
            </div>
            <div class="col-md-3 col-6">
                <h3 class="mb-1">
                    <i class="bi bi-clock-history"></i> Today
                </h3>
                <small class="opacity-75">Last Updated</small>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div class="row">
        <!-- Filters Sidebar -->
        <div class="col-lg-3 mb-4">
            <div class="card border-0 shadow-sm sticky-top" style="top: 20px;">
                <div class="card-header bg-white border-bottom">
                    <h5 class="mb-0">
                        <i class="bi bi-funnel-fill"></i> Filters
                    </h5>
                </div>
                <div class="card-body">
                    <form method="GET" action="" id="filterForm">
                        <!-- Product Type -->
                        <div class="mb-4">
                            <label class="form-label fw-semibold">
                                <i class="bi bi-basket"></i> Product Type
                            </label>
                            <select class="form-select" name="product" id="productFilter">
                                <option value="">All Products</option>
                                <?php foreach ($productTypes as $type): ?>
                                    <option value="<?php echo htmlspecialchars($type['product_type']); ?>" 
                                            <?php echo $productType === $type['product_type'] ? 'selected' : ''; ?>>
                                        <?php echo ucfirst(str_replace('_', ' ', $type['product_type'])); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <!-- Location -->
                        <div class="mb-4">
                            <label class="form-label fw-semibold">
                                <i class="bi bi-geo-alt"></i> Market Location
                            </label>
                            <select class="form-select" name="location" id="locationFilter">
                                <option value="">All Locations</option>
                                <?php foreach ($locations as $loc): ?>
                                    <option value="<?php echo htmlspecialchars($loc); ?>" 
                                            <?php echo $location === $loc ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($loc); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <!-- Sort By -->
                        <div class="mb-4">
                            <label class="form-label fw-semibold">
                                <i class="bi bi-sort-down"></i> Sort By
                            </label>
                            <select class="form-select" name="sort" id="sortFilter">
                                <option value="date" <?php echo $sortBy === 'date' ? 'selected' : ''; ?>>Latest First</option>
                                <option value="price_asc" <?php echo $sortBy === 'price_asc' ? 'selected' : ''; ?>>Price: Low to High</option>
                                <option value="price_desc" <?php echo $sortBy === 'price_desc' ? 'selected' : ''; ?>>Price: High to Low</option>
                                <option value="name" <?php echo $sortBy === 'name' ? 'selected' : ''; ?>>Product Name</option>
                            </select>
                        </div>

                        <!-- View Mode -->
                        <div class="mb-4">
                            <label class="form-label fw-semibold">
                                <i class="bi bi-eye"></i> View Mode
                            </label>
                            <div class="view-toggle btn-group w-100" role="group">
                                <input type="radio" class="btn-check" name="view" value="grid" id="viewGrid" 
                                       <?php echo $viewMode === 'grid' ? 'checked' : ''; ?>>
                                <label class="btn btn-sm" for="viewGrid">
                                    <i class="bi bi-grid-3x3-gap"></i> Grid
                                </label>
                                
                                <input type="radio" class="btn-check" name="view" value="table" id="viewTable"
                                       <?php echo $viewMode === 'table' ? 'checked' : ''; ?>>
                                <label class="btn btn-sm" for="viewTable">
                                    <i class="bi bi-table"></i> Table
                                </label>
                            </div>
                        </div>

                        <!-- Action Buttons -->
                        <div class="d-grid gap-2">
                            <button type="submit" class="btn btn-success">
                                <i class="bi bi-search"></i> Apply Filters
                            </button>
                            <button type="button" class="btn btn-outline-secondary" onclick="resetFilters()">
                                <i class="bi bi-arrow-counterclockwise"></i> Reset
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Quick Actions -->
                <div class="card-footer bg-light">
                    <div class="d-grid gap-2">
                        <a href="<?php echo APP_URL; ?>/prices/set-alert.php" class="btn btn-sm btn-warning">
                            <i class="bi bi-bell-plus"></i> Create Price Alert
                        </a>
                        <a href="<?php echo APP_URL; ?>/prices/history.php" class="btn btn-sm btn-info text-white">
                            <i class="bi bi-clock-history"></i> Price History
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main Content -->
        <div class="col-lg-9">
            <!-- Quick Filter Pills -->
            <div class="mb-4">
                <div class="d-flex flex-wrap gap-2">
                    <span class="text-muted small">Quick filters:</span>
                    <button class="quick-filter-btn btn btn-sm btn-outline-success" onclick="filterByProduct('maize')">
                        🌽 Maize
                    </button>
                    <button class="quick-filter-btn btn btn-sm btn-outline-success" onclick="filterByProduct('sugar_cane')">
                        🎋 Sugar Cane
                    </button>
                    <button class="quick-filter-btn btn btn-sm btn-outline-success" onclick="filterByProduct('vegetables')">
                        🥬 Vegetables
                    </button>
                    <button class="quick-filter-btn btn btn-sm btn-outline-success" onclick="filterByProduct('poultry')">
                        🐔 Poultry
                    </button>
                </div>
            </div>

            <?php if (!empty($pricesByProduct)): ?>
                <?php if ($viewMode === 'grid'): ?>
                    <!-- Grid View -->
                    <?php foreach ($pricesByProduct as $product => $data): ?>
                        <div class="card price-card border-0 shadow-sm mb-4">
                            <div class="card-header bg-white border-bottom">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h5 class="mb-1">
                                            <?php 
                                            // Product icons
                                            $icons = [
                                                'maize' => '🌽',
                                                'sugar_cane' => '🎋',
                                                'vegetables' => '🥬',
                                                'poultry' => '🐔',
                                                'coffee' => '☕',
                                                'beans' => '🫘',
                                                'cassava' => '🥔'
                                            ];
                                            echo $icons[$product] ?? '🌾';
                                            ?>
                                            <?php echo ucfirst(str_replace('_', ' ', $product)); ?>
                                        </h5>
                                        <small class="text-muted">
                                            <?php echo count($data['prices']); ?> market listings
                                        </small>
                                    </div>
                                    <div class="text-end">
                                        <span class="price-badge bg-success bg-opacity-10 text-success">
                                            <?php echo formatCurrency($data['avg_price']); ?>
                                        </span>
                                        <br>
                                        <small class="text-muted">avg. price</small>
                                    </div>
                                </div>
                            </div>

                            <div class="card-body">
                                <!-- Price Range Indicator -->
                                <div class="mb-3">
                                    <div class="d-flex justify-content-between mb-1">
                                        <small class="text-success">
                                            <i class="bi bi-arrow-down"></i> Low: <?php echo formatCurrency($data['min_price']); ?>
                                        </small>
                                        <small class="text-danger">
                                            <i class="bi bi-arrow-up"></i> High: <?php echo formatCurrency($data['max_price']); ?>
                                        </small>
                                    </div>
                                    <div class="price-range-indicator">
                                        <?php
                                        $range = $data['max_price'] - $data['min_price'];
                                        $position = $range > 0 ? (($data['avg_price'] - $data['min_price']) / $range) * 100 : 50;
                                        ?>
                                        <div class="price-marker" style="left: <?php echo $position; ?>%"></div>
                                    </div>
                                </div>

                                <!-- Market Listings -->
                                <div class="row g-3">
                                    <?php foreach (array_slice($data['prices'], 0, 6) as $price): ?>
                                        <div class="col-md-6">
                                            <div class="border rounded p-3 h-100">
                                                <div class="d-flex justify-content-between align-items-start mb-2">
                                                    <div>
                                                        <span class="market-location-badge">
                                                            <i class="bi bi-geo-alt-fill"></i>
                                                            <?php echo htmlspecialchars($price['market_location']); ?>
                                                        </span>
                                                    </div>
                                                    <h4 class="mb-0 text-success">
                                                        <?php echo formatCurrency($price['price']); ?>
                                                    </h4>
                                                </div>
                                                <div class="d-flex justify-content-between text-muted small">
                                                    <span>
                                                        <i class="bi bi-rulers"></i> 
                                                        per <?php echo htmlspecialchars($price['unit']); ?>
                                                    </span>
                                                    <span>
                                                        <i class="bi bi-clock"></i>
                                                        <?php echo timeAgo($price['price_date']); ?>
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>

                                <?php if (count($data['prices']) > 6): ?>
                                    <div class="text-center mt-3">
                                        <a href="<?php echo APP_URL; ?>/prices/product.php?type=<?php echo urlencode($product); ?>" 
                                           class="btn btn-sm btn-outline-primary">
                                            View All <?php echo count($data['prices']); ?> Prices
                                            <i class="bi bi-arrow-right"></i>
                                        </a>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <div class="card-footer bg-light">
                                <div class="d-flex justify-content-between align-items-center">
                                    <a href="<?php echo APP_URL; ?>/prices/comparison.php?product=<?php echo urlencode($product); ?>" 
                                       class="btn btn-sm btn-outline-primary">
                                        <i class="bi bi-arrow-left-right"></i> Compare Markets
                                    </a>
                                    <a href="<?php echo APP_URL; ?>/prices/set-alert.php?product=<?php echo urlencode($product); ?>" 
                                       class="btn btn-sm btn-warning">
                                        <i class="bi bi-bell-plus"></i> Set Alert
                                    </a>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>

                <?php else: ?>
                    <!-- Table View -->
                    <?php foreach ($pricesByProduct as $product => $data): ?>
                        <div class="card border-0 shadow-sm mb-4">
                            <div class="card-header bg-white border-bottom">
                                <h5 class="mb-0">
                                    <?php echo ucfirst(str_replace('_', ' ', $product)); ?>
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover align-middle">
                                        <thead class="table-light">
                                            <tr>
                                                <th>Market Location</th>
                                                <th class="text-end">Price</th>
                                                <th>Unit</th>
                                                <th>Date</th>
                                                <th>Source</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($data['prices'] as $price): ?>
                                                <tr>
                                                    <td>
                                                        <i class="bi bi-geo-alt text-danger"></i>
                                                        <strong><?php echo htmlspecialchars($price['market_location']); ?></strong>
                                                    </td>
                                                    <td class="text-end">
                                                        <span class="badge bg-success fs-6">
                                                            <?php echo formatCurrency($price['price']); ?>
                                                        </span>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($price['unit']); ?></td>
                                                    <td>
                                                        <small class="text-muted">
                                                            <?php echo formatDate($price['price_date']); ?>
                                                        </small>
                                                    </td>
                                                    <td>
                                                        <small class="text-muted">
                                                            <?php echo htmlspecialchars($price['source']); ?>
                                                        </small>
                                                    </td>
                                                    <td>
                                                        <button class="btn btn-sm btn-outline-info" 
                                                                onclick="sharePrice('<?php echo htmlspecialchars($product); ?>', '<?php echo htmlspecialchars($price['market_location']); ?>', <?php echo $price['price']; ?>)">
                                                            <i class="bi bi-share"></i>
                                                        </button>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>

            <?php else: ?>
                <!-- Empty State -->
                <div class="card border-0 shadow-sm">
                    <div class="card-body empty-state">
                        <i class="bi bi-inbox"></i>
                        <h4 class="mt-3">No Prices Found</h4>
                        <p class="text-muted">
                            <?php if ($productType || $location): ?>
                                Try adjusting your filters to see more results
                            <?php else: ?>
                                Price information will be updated regularly
                            <?php endif; ?>
                        </p>
                        <?php if ($productType || $location): ?>
                            <button class="btn btn-primary" onclick="resetFilters()">
                                <i class="bi bi-arrow-counterclockwise"></i> Clear Filters
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
// Auto-submit on filter change
document.querySelectorAll('#productFilter, #locationFilter, #sortFilter, input[name="view"]').forEach(element => {
    element.addEventListener('change', function() {
        document.getElementById('filterForm').submit();
    });
});

// Quick product filter
function filterByProduct(product) {
    document.getElementById('productFilter').value = product;
    document.getElementById('filterForm').submit();
}

// Reset filters
function resetFilters() {
    window.location.href = '<?php echo APP_URL; ?>/prices/';
}

// Share price function
function sharePrice(product, location, price) {
    const message = `${product} price at ${location}: ${formatCurrency(price)}`;
    
    if (navigator.share) {
        navigator.share({
            title: 'Market Price',
            text: message,
            url: window.location.href
        }).catch(err => console.log('Error sharing:', err));
    } else {
        // Fallback - copy to clipboard
        navigator.clipboard.writeText(message).then(() => {
            showToast('Price info copied to clipboard!', 'success');
        });
    }
}

// Format currency for JS
function formatCurrency(amount) {
    return 'UGX ' + parseFloat(amount).toLocaleString();
}
</script>

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