<?php
/**
 * ============================================================================
 * prices/trends.php - Price Trends & Analysis
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Price Trends';

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

// Get product types
$productTypes = $priceClass->getProductTypes();

// Get selected product and timeframe
$selectedProduct = $_GET['product'] ?? '';
$timeframe = $_GET['timeframe'] ?? '30'; // days

// Get trend data
$trendData = [];
if ($selectedProduct) {
    $trendData = $priceClass->getPriceTrends($selectedProduct, $timeframe);
}

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

<style>
.chart-container {
    position: relative;
    height: 400px;
    margin-bottom: 2rem;
}

.trend-indicator {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 1rem;
    border-radius: 20px;
    font-weight: 600;
}

.trend-up {
    background: #fee2e2;
    color: #dc2626;
}

.trend-down {
    background: #d1fae5;
    color: #059669;
}

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

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

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

.timeframe-btn.active {
    background: #059669;
    color: white;
}
</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 text-primary"></i> Price Trends & Analysis
                    </h2>
                    <p class="text-muted mb-0">Historical price patterns and market insights</p>
                </div>
                <a href="<?php echo APP_URL; ?>/prices/" class="btn btn-outline-primary">
                    <i class="bi bi-arrow-left"></i> Back to Prices
                </a>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Product Selector -->
        <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-sliders"></i> Analysis Settings
                    </h5>
                </div>
                <div class="card-body">
                    <form method="GET" id="trendForm">
                        <!-- Product Selection -->
                        <div class="mb-4">
                            <label class="form-label fw-semibold">Select Product</label>
                            <select class="form-select" name="product" id="productSelect" required>
                                <option value="">Choose a product...</option>
                                <?php foreach ($productTypes as $type): ?>
                                    <option value="<?php echo htmlspecialchars($type['product_type']); ?>"
                                            <?php echo $selectedProduct === $type['product_type'] ? 'selected' : ''; ?>>
                                        <?php echo ucwords(str_replace('_', ' ', $type['product_type'])); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <!-- Timeframe Selection -->
                        <div class="mb-4">
                            <label class="form-label fw-semibold">Time Period</label>
                            <div class="btn-group-vertical w-100" role="group">
                                <input type="radio" class="btn-check" name="timeframe" value="7" id="days7"
                                       <?php echo $timeframe == '7' ? 'checked' : ''; ?>>
                                <label class="btn btn-outline-primary" for="days7">Last 7 Days</label>

                                <input type="radio" class="btn-check" name="timeframe" value="30" id="days30"
                                       <?php echo $timeframe == '30' ? 'checked' : ''; ?>>
                                <label class="btn btn-outline-primary" for="days30">Last 30 Days</label>

                                <input type="radio" class="btn-check" name="timeframe" value="90" id="days90"
                                       <?php echo $timeframe == '90' ? 'checked' : ''; ?>>
                                <label class="btn btn-outline-primary" for="days90">Last 90 Days</label>

                                <input type="radio" class="btn-check" name="timeframe" value="180" id="days180"
                                       <?php echo $timeframe == '180' ? 'checked' : ''; ?>>
                                <label class="btn btn-outline-primary" for="days180">Last 6 Months</label>

                                <input type="radio" class="btn-check" name="timeframe" value="365" id="days365"
                                       <?php echo $timeframe == '365' ? 'checked' : ''; ?>>
                                <label class="btn btn-outline-primary" for="days365">Last Year</label>
                            </div>
                        </div>

                        <button type="submit" class="btn btn-success w-100">
                            <i class="bi bi-graph-up"></i> Analyze Trends
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Main Content -->
        <div class="col-lg-9">
            <?php if ($selectedProduct && !empty($trendData)): ?>
                <?php
                // Calculate trend statistics
                $prices = array_column($trendData, 'average_price');
                $firstPrice = reset($prices);
                $lastPrice = end($prices);
                $priceChange = $lastPrice - $firstPrice;
                $percentChange = ($firstPrice > 0) ? (($priceChange / $firstPrice) * 100) : 0;
                $trend = $percentChange > 2 ? 'up' : ($percentChange < -2 ? 'down' : 'stable');
                ?>

                <!-- Trend Summary -->
                <div class="row mb-4">
                    <div class="col-md-4 mb-3">
                        <div class="card border-0 shadow-sm h-100">
                            <div class="card-body text-center">
                                <h6 class="text-muted mb-2">Current Average</h6>
                                <h2 class="text-success mb-0"><?php echo formatCurrency($lastPrice); ?></h2>
                                <small class="text-muted">per unit</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <div class="card border-0 shadow-sm h-100">
                            <div class="card-body text-center">
                                <h6 class="text-muted mb-2">Price Change</h6>
                                <h2 class="mb-0 <?php echo $trend === 'up' ? 'text-danger' : 'text-success'; ?>">
                                    <?php echo $priceChange > 0 ? '+' : ''; ?>
                                    <?php echo formatCurrency(abs($priceChange)); ?>
                                </h2>
                                <small class="text-muted">
                                    <?php echo number_format(abs($percentChange), 1); ?>%
                                    <?php echo $trend === 'up' ? 'increase' : 'decrease'; ?>
                                </small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <div class="card border-0 shadow-sm h-100">
                            <div class="card-body text-center">
                                <h6 class="text-muted mb-2">Market Trend</h6>
                                <div class="trend-indicator trend-<?php echo $trend; ?> d-inline-flex">
                                    <?php if ($trend === 'up'): ?>
                                        <i class="bi bi-arrow-up-circle-fill"></i> Rising
                                    <?php elseif ($trend === 'down'): ?>
                                        <i class="bi bi-arrow-down-circle-fill"></i> Falling
                                    <?php else: ?>
                                        <i class="bi bi-dash-circle-fill"></i> Stable
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Price Chart -->
                <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> Price Trend Chart
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="priceChart"></canvas>
                        </div>
                    </div>
                </div>

                <!-- Market Insights -->
                <div class="insight-card mb-4">
                    <h5 class="mb-3">
                        <i class="bi bi-lightbulb"></i> Market Insights
                    </h5>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <h6>Price Volatility</h6>
                            <p class="mb-0 opacity-75">
                                <?php
                                $volatility = max($prices) - min($prices);
                                if ($volatility < 1000) {
                                    echo "Low volatility - stable market conditions";
                                } elseif ($volatility < 3000) {
                                    echo "Moderate volatility - normal market fluctuations";
                                } else {
                                    echo "High volatility - significant price variations";
                                }
                                ?>
                            </p>
                        </div>
                        <div class="col-md-6 mb-3">
                            <h6>Best Time to Buy</h6>
                            <p class="mb-0 opacity-75">
                                <?php
                                if ($trend === 'down') {
                                    echo "Current - prices are falling";
                                } elseif ($trend === 'up') {
                                    echo "Wait - prices are rising";
                                } else {
                                    echo "Any time - prices are stable";
                                }
                                ?>
                            </p>
                        </div>
                        <div class="col-md-6">
                            <h6>Market Recommendation</h6>
                            <p class="mb-0 opacity-75">
                                <?php
                                if ($trend === 'up' && $percentChange > 10) {
                                    echo "Sellers should consider selling now";
                                } elseif ($trend === 'down' && abs($percentChange) > 10) {
                                    echo "Buyers should consider purchasing soon";
                                } else {
                                    echo "Normal market activity - monitor trends";
                                }
                                ?>
                            </p>
                        </div>
                        <div class="col-md-6">
                            <h6>Price Range</h6>
                            <p class="mb-0 opacity-75">
                                Low: <?php echo formatCurrency(min($prices)); ?> - 
                                High: <?php echo formatCurrency(max($prices)); ?>
                            </p>
                        </div>
                    </div>
                </div>

                <!-- Historical Data Table -->
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-white border-bottom">
                        <h5 class="mb-0">
                            <i class="bi bi-table"></i> Historical Price Data
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover align-middle">
                                <thead class="table-light">
                                    <tr>
                                        <th>Date</th>
                                        <th class="text-end">Average Price</th>
                                        <th class="text-end">Low</th>
                                        <th class="text-end">High</th>
                                        <th class="text-center">Change</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $prevPrice = null;
                                    foreach (array_reverse($trendData) as $data): 
                                        $change = $prevPrice ? $data['average_price'] - $prevPrice : 0;
                                        $prevPrice = $data['average_price'];
                                    ?>
                                        <tr>
                                            <td><?php echo formatDate($data['price_date']); ?></td>
                                            <td class="text-end fw-bold"><?php echo formatCurrency($data['average_price']); ?></td>
                                            <td class="text-end text-success"><?php echo formatCurrency($data['min_price']); ?></td>
                                            <td class="text-end text-danger"><?php echo formatCurrency($data['max_price']); ?></td>
                                            <td class="text-center">
                                                <?php if ($change != 0): ?>
                                                    <span class="badge bg-<?php echo $change > 0 ? 'danger' : 'success'; ?>">
                                                        <?php echo $change > 0 ? '+' : ''; ?>
                                                        <?php echo formatCurrency(abs($change)); ?>
                                                    </span>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

            <?php elseif ($selectedProduct): ?>
                <div class="card border-0 shadow-sm">
                    <div class="card-body text-center py-5">
                        <i class="bi bi-exclamation-triangle text-warning" style="font-size: 4rem;"></i>
                        <h4 class="mt-3">No Trend Data Available</h4>
                        <p class="text-muted">
                            We don't have enough historical data for <?php echo ucwords(str_replace('_', ' ', $selectedProduct)); ?>.
                        </p>
                    </div>
                </div>

            <?php else: ?>
                <div class="card border-0 shadow-sm">
                    <div class="card-body text-center py-5">
                        <i class="bi bi-graph-up text-muted" style="font-size: 4rem;"></i>
                        <h4 class="mt-3">Select a Product to View Trends</h4>
                        <p class="text-muted">Choose a product from the left sidebar to analyze price trends</p>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php if ($selectedProduct && !empty($trendData)): ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
// Prepare chart data
const chartData = {
    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
        },
        {
            label: 'Low Price',
            data: <?php echo json_encode(array_column($trendData, 'min_price')); ?>,
            borderColor: '#10b981',
            borderDash: [5, 5],
            fill: false,
            tension: 0.4
        },
        {
            label: 'High Price',
            data: <?php echo json_encode(array_column($trendData, 'max_price')); ?>,
            borderColor: '#dc2626',
            borderDash: [5, 5],
            fill: false,
            tension: 0.4
        }
    ]
};

// Create chart
const ctx = document.getElementById('priceChart').getContext('2d');
new Chart(ctx, {
    type: 'line',
    data: chartData,
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'top',
            },
            tooltip: {
                callbacks: {
                    label: function(context) {
                        return context.dataset.label + ': UGX ' + context.parsed.y.toLocaleString();
                    }
                }
            }
        },
        scales: {
            y: {
                beginAtZero: false,
                ticks: {
                    callback: function(value) {
                        return 'UGX ' + value.toLocaleString();
                    }
                }
            }
        }
    }
});

// Auto-submit on change
document.querySelectorAll('input[name="timeframe"]').forEach(radio => {
    radio.addEventListener('change', function() {
        document.getElementById('trendForm').submit();
    });
});

document.getElementById('productSelect').addEventListener('change', function() {
    if (this.value) {
        document.getElementById('trendForm').submit();
    }
});
</script>
<?php endif; ?>

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