<?php
/**
 * ============================================================================
 * prices/product.php - Single Product Price Overview
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

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

// Get product type from URL
$productType = $_GET['type'] ?? '';

if (!$productType) {
    redirect('/prices/', 'Please select a product', 'error');
}

$pageTitle = ucwords(str_replace('_', ' ', $productType)) . ' Prices';

// Get all prices for this product
$prices = $priceClass->getCurrentPrices($productType);

// Get comparison data
$comparisonData = $priceClass->comparePrices($productType);

// Get trend data for last 7 days
$trendData = $priceClass->getPriceTrends($productType, 7);

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

<style>
.product-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 3rem 0;
    margin-bottom: 2rem;
    border-radius: 15px;
}

.market-card {
    transition: all 0.3s ease;
    border-left: 4px solid #059669;
}

.market-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}

.price-comparison-bar {
    height: 30px;
    background: #e5e7eb;
    border-radius: 15px;
    overflow: hidden;
    position: relative;
}

.price-level {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: bold;
    font-size: 0.875rem;
}

.price-level.low {
    background: linear-gradient(90deg, #059669, #10b981);
}

.price-level.medium {
    background: linear-gradient(90deg, #f59e0b, #fbbf24);
}

.price-level.high {
    background: linear-gradient(90deg, #dc2626, #ef4444);
}

.mini-chart {
    height: 60px;
}

.best-deal-badge {
    position: absolute;
    top: 10px;
    right: 10px;
    background: #059669;
    color: white;
    padding: 0.5rem 1rem;
    border-radius: 20px;
    font-size: 0.875rem;
    font-weight: bold;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
</style>

<div class="container-fluid py-4">
    <!-- Product Header -->
    <div class="product-header text-center">
        <div class="container">
            <h1 class="display-4 mb-3">
                <?php 
                $icons = [
                    'maize' => '🌽',
                    'sugar_cane' => '🎋',
                    'vegetables' => '🥬',
                    'poultry' => '🐔',
                    'coffee' => '☕',
                    'beans' => '🫘',
                    'cassava' => '🥔'
                ];
                echo $icons[$productType] ?? '🌾';
                ?>
                <?php echo ucwords(str_replace('_', ' ', $productType)); ?> Prices
            </h1>
            <p class="lead mb-0">Comprehensive price information across all markets</p>
        </div>
    </div>

    <div class="container">
        <!-- Quick Stats -->
        <?php if (!empty($comparisonData)): ?>
        <div class="row mb-4">
            <div class="col-md-3 mb-3">
                <div class="card border-0 shadow-sm text-center h-100">
                    <div class="card-body">
                        <i class="bi bi-arrow-down-circle text-success fs-1"></i>
                        <h4 class="mt-2 mb-1 text-success"><?php echo formatCurrency($comparisonData['min_price']); ?></h4>
                        <small class="text-muted">Lowest Price</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="card border-0 shadow-sm text-center h-100">
                    <div class="card-body">
                        <i class="bi bi-graph-up text-primary fs-1"></i>
                        <h4 class="mt-2 mb-1 text-primary"><?php echo formatCurrency($comparisonData['avg_price']); ?></h4>
                        <small class="text-muted">Average Price</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="card border-0 shadow-sm text-center h-100">
                    <div class="card-body">
                        <i class="bi bi-arrow-up-circle text-danger fs-1"></i>
                        <h4 class="mt-2 mb-1 text-danger"><?php echo formatCurrency($comparisonData['max_price']); ?></h4>
                        <small class="text-muted">Highest Price</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="card border-0 shadow-sm text-center h-100">
                    <div class="card-body">
                        <i class="bi bi-geo-alt text-info fs-1"></i>
                        <h4 class="mt-2 mb-1"><?php echo count($comparisonData['markets']); ?></h4>
                        <small class="text-muted">Markets Listed</small>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- 7-Day Price Trend -->
        <?php if (!empty($trendData)): ?>
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-bottom">
                <h5 class="mb-0">
                    <i class="bi bi-graph-up"></i> 7-Day Price Trend
                </h5>
            </div>
            <div class="card-body">
                <canvas id="miniTrendChart" class="mini-chart"></canvas>
            </div>
        </div>
        <?php endif; ?>

        <!-- Market Prices -->
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4>
                <i class="bi bi-shop"></i> All Market Prices
            </h4>
            <div class="btn-group" role="group">
                <button class="btn btn-sm btn-outline-primary active" onclick="sortPrices('price_asc')">
                    <i class="bi bi-sort-numeric-down"></i> Lowest First
                </button>
                <button class="btn btn-sm btn-outline-primary" onclick="sortPrices('price_desc')">
                    <i class="bi bi-sort-numeric-down-alt"></i> Highest First
                </button>
                <button class="btn btn-sm btn-outline-primary" onclick="sortPrices('location')">
                    <i class="bi bi-geo-alt"></i> By Location
                </button>
            </div>
        </div>

        <div class="row" id="marketPrices">
            <?php 
            if (!empty($comparisonData['markets'])):
                $minPrice = $comparisonData['min_price'];
                $maxPrice = $comparisonData['max_price'];
                $avgPrice = $comparisonData['avg_price'];
                $range = $maxPrice - $minPrice;
                
                foreach ($comparisonData['markets'] as $index => $market): 
                    // Calculate price level
                    $priceLevel = 'medium';
                    if ($market['price'] <= $minPrice + ($range * 0.33)) {
                        $priceLevel = 'low';
                    } elseif ($market['price'] >= $minPrice + ($range * 0.67)) {
                        $priceLevel = 'high';
                    }
                    
                    // Calculate bar width
                    $barWidth = $range > 0 ? (($market['price'] - $minPrice) / $range) * 100 : 50;
                    $isBestDeal = $market['price'] == $minPrice;
            ?>
                <div class="col-md-6 col-lg-4 mb-4 market-item" 
                     data-price="<?php echo $market['price']; ?>"
                     data-location="<?php echo htmlspecialchars($market['location']); ?>">
                    <div class="card market-card border-0 shadow-sm h-100">
                        <?php if ($isBestDeal): ?>
                            <div class="best-deal-badge">
                                <i class="bi bi-star-fill"></i> Best Deal
                            </div>
                        <?php endif; ?>
                        
                        <div class="card-body">
                            <h5 class="mb-3">
                                <i class="bi bi-geo-alt text-danger"></i>
                                <?php echo htmlspecialchars($market['location']); ?>
                            </h5>
                            
                            <div class="mb-3">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <span class="text-muted">Price per <?php echo htmlspecialchars($market['unit']); ?></span>
                                    <h3 class="mb-0 text-<?php echo $priceLevel === 'low' ? 'success' : ($priceLevel === 'high' ? 'danger' : 'warning'); ?>">
                                        <?php echo formatCurrency($market['price']); ?>
                                    </h3>
                                </div>
                                
                                <!-- Price comparison bar -->
                                <div class="price-comparison-bar">
                                    <div class="price-level <?php echo $priceLevel; ?>" style="width: <?php echo $barWidth; ?>%">
                                        <?php 
                                        $diff = $market['price'] - $avgPrice;
                                        if (abs($diff) < 100) {
                                            echo 'Average';
                                        } elseif ($diff > 0) {
                                            echo '+' . formatCurrency(abs($diff));
                                        } else {
                                            echo '-' . formatCurrency(abs($diff));
                                        }
                                        ?>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-flex justify-content-between text-muted small">
                                <span>
                                    <i class="bi bi-clock"></i>
                                    <?php echo timeAgo($market['recorded_date']); ?>
                                </span>
                                <span>
                                    <?php 
                                    $percentDiff = ($avgPrice > 0) ? (($market['price'] - $avgPrice) / $avgPrice * 100) : 0;
                                    ?>
                                    <span class="badge bg-<?php echo $percentDiff > 0 ? 'danger' : ($percentDiff < 0 ? 'success' : 'secondary'); ?>">
                                        <?php echo $percentDiff > 0 ? '+' : ''; ?>
                                        <?php echo number_format($percentDiff, 1); ?>%
                                    </span>
                                </span>
                            </div>
                        </div>
                        
                        <div class="card-footer bg-light border-top-0">
                            <div class="d-grid gap-2">
                                <button class="btn btn-sm btn-outline-primary" onclick="getDirections('<?php echo htmlspecialchars($market['location']); ?>')">
                                    <i class="bi bi-map"></i> Get Directions
                                </button>
                                <button class="btn btn-sm btn-outline-success" onclick="sharePrice('<?php echo htmlspecialchars($market['location']); ?>', <?php echo $market['price']; ?>)">
                                    <i class="bi bi-share"></i> Share Price
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            <?php 
                endforeach;
            else:
            ?>
                <div class="col-12">
                    <div class="card border-0 shadow-sm">
                        <div class="card-body text-center py-5">
                            <i class="bi bi-inbox text-muted" style="font-size: 4rem;"></i>
                            <h4 class="mt-3">No Price Data Available</h4>
                            <p class="text-muted">No recent prices found for this product</p>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- Action Buttons -->
        <div class="row mt-4">
            <div class="col-md-6 mb-3">
                <a href="<?php echo APP_URL; ?>/prices/comparison.php?product=<?php echo urlencode($productType); ?>" 
                   class="btn btn-outline-primary btn-lg w-100">
                    <i class="bi bi-arrow-left-right"></i> Compare All Markets
                </a>
            </div>
            <div class="col-md-6 mb-3">
                <a href="<?php echo APP_URL; ?>/prices/set-alert.php?product=<?php echo urlencode($productType); ?>" 
                   class="btn btn-warning btn-lg w-100">
                    <i class="bi bi-bell-plus"></i> Set Price Alert
                </a>
            </div>
        </div>
    </div>
</div>

<?php if (!empty($trendData)): ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
// Mini trend chart
const miniCtx = document.getElementById('miniTrendChart').getContext('2d');
new Chart(miniCtx, {
    type: 'line',
    data: {
        labels: <?php echo json_encode(array_map(function($d) { return date('M d', strtotime($d['price_date'])); }, $trendData)); ?>,
        datasets: [{
            label: 'Average Price',
            data: <?php echo json_encode(array_column($trendData, 'average_price')); ?>,
            borderColor: '#059669',
            backgroundColor: 'rgba(5, 150, 105, 0.1)',
            fill: true,
            tension: 0.4
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: false
            }
        },
        scales: {
            y: {
                ticks: {
                    callback: function(value) {
                        return 'UGX ' + value.toLocaleString();
                    }
                }
            }
        }
    }
});
</script>
<?php endif; ?>

<script>
function sortPrices(sortBy) {
    const container = document.getElementById('marketPrices');
    const items = Array.from(container.querySelectorAll('.market-item'));
    
    items.sort((a, b) => {
        if (sortBy === 'price_asc') {
            return parseFloat(a.dataset.price) - parseFloat(b.dataset.price);
        } else if (sortBy === 'price_desc') {
            return parseFloat(b.dataset.price) - parseFloat(a.dataset.price);
        } else if (sortBy === 'location') {
            return a.dataset.location.localeCompare(b.dataset.location);
        }
    });
    
    items.forEach(item => container.appendChild(item));
    
    // Update active button
    document.querySelectorAll('.btn-group .btn').forEach(btn => btn.classList.remove('active'));
    event.target.classList.add('active');
}

function getDirections(location) {
    const encodedLocation = encodeURIComponent(location);
    window.open(`https://www.google.com/maps/search/${encodedLocation}`, '_blank');
}

function sharePrice(location, price) {
    const message = `<?php echo ucwords(str_replace('_', ' ', $productType)); ?> price at ${location}: UGX ${parseFloat(price).toLocaleString()}`;
    
    if (navigator.share) {
        navigator.share({
            title: 'Market Price',
            text: message,
            url: window.location.href
        }).catch(err => console.log('Error sharing:', err));
    } else {
        navigator.clipboard.writeText(message).then(() => {
            showToast('Price info copied to clipboard!', 'success');
        });
    }
}
</script>

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