<?php
/**
 * ============================================================================
 * prices/comparison.php - Interactive Price Comparison
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Price Comparison';

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

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

// Get selected product
$selectedProduct = $_GET['product'] ?? '';

// Get comparison data
$comparisonData = [];
$hasData = false;

if ($selectedProduct) {
    $comparisonData = $priceClass->comparePrices($selectedProduct);
    $hasData = !empty($comparisonData) && !empty($comparisonData['markets']);
}

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

<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-arrow-left-right text-primary"></i> Price Comparison
                    </h2>
                    <p class="text-muted mb-0">Compare prices across different markets</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>

    <!-- Product Selector -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <form method="GET" id="compareForm">
                        <label class="form-label fw-semibold">Select Product to Compare</label>
                        <div class="row g-3">
                            <div class="col-md-8">
                                <select class="form-select form-select-lg" 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>
                            <div class="col-md-4">
                                <button type="submit" class="btn btn-primary btn-lg w-100">
                                    <i class="bi bi-search"></i> Compare Prices
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <?php if ($selectedProduct && $hasData): ?>
        <!-- Price Statistics -->
        <div class="row mb-4">
            <div class="col-md-4 mb-3">
                <div class="card border-0 shadow-sm bg-success bg-opacity-10 h-100">
                    <div class="card-body text-center">
                        <div class="d-flex justify-content-center align-items-center mb-2">
                            <i class="bi bi-arrow-down-circle text-success fs-1 me-2"></i>
                            <div class="text-start">
                                <h6 class="text-muted mb-1">Lowest Price</h6>
                                <h3 class="text-success mb-0"><?php echo formatCurrency($comparisonData['min_price'] ?? 0); ?></h3>
                                <small class="text-muted">per <?php echo htmlspecialchars($comparisonData['unit'] ?? 'unit'); ?></small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4 mb-3">
                <div class="card border-0 shadow-sm bg-primary bg-opacity-10 h-100">
                    <div class="card-body text-center">
                        <div class="d-flex justify-content-center align-items-center mb-2">
                            <i class="bi bi-graph-up text-primary fs-1 me-2"></i>
                            <div class="text-start">
                                <h6 class="text-muted mb-1">Average Price</h6>
                                <h3 class="text-primary mb-0"><?php echo formatCurrency($comparisonData['avg_price'] ?? 0); ?></h3>
                                <small class="text-muted">per <?php echo htmlspecialchars($comparisonData['unit'] ?? 'unit'); ?></small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4 mb-3">
                <div class="card border-0 shadow-sm bg-danger bg-opacity-10 h-100">
                    <div class="card-body text-center">
                        <div class="d-flex justify-content-center align-items-center mb-2">
                            <i class="bi bi-arrow-up-circle text-danger fs-1 me-2"></i>
                            <div class="text-start">
                                <h6 class="text-muted mb-1">Highest Price</h6>
                                <h3 class="text-danger mb-0"><?php echo formatCurrency($comparisonData['max_price'] ?? 0); ?></h3>
                                <small class="text-muted">per <?php echo htmlspecialchars($comparisonData['unit'] ?? 'unit'); ?></small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Market Comparison Table -->
        <div class="row mb-4">
            <div class="col-12">
                <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> Market Prices for <?php echo ucwords(str_replace('_', ' ', $selectedProduct)); ?>
                        </h5>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($comparisonData['markets'])): ?>
                            <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 per <?php echo htmlspecialchars($comparisonData['unit']); ?></th>
                                            <th class="text-center">vs. Average</th>
                                            <th>Last Updated</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $avgPrice = $comparisonData['avg_price'];
                                        foreach ($comparisonData['markets'] as $market): 
                                            $diff = $market['price'] - $avgPrice;
                                            $diffPercent = $avgPrice > 0 ? ($diff / $avgPrice * 100) : 0;
                                        ?>
                                            <tr>
                                                <td>
                                                    <i class="bi bi-geo-alt text-danger"></i>
                                                    <strong><?php echo htmlspecialchars($market['location']); ?></strong>
                                                </td>
                                                <td class="text-end">
                                                    <h5 class="mb-0">
                                                        <?php echo formatCurrency($market['price']); ?>
                                                    </h5>
                                                </td>
                                                <td class="text-center">
                                                    <?php if (abs($diff) < 100): ?>
                                                        <span class="badge bg-secondary">
                                                            <i class="bi bi-dash"></i> Average
                                                        </span>
                                                    <?php elseif ($diff > 0): ?>
                                                        <span class="badge bg-danger">
                                                            <i class="bi bi-arrow-up"></i>
                                                            +<?php echo formatCurrency(abs($diff)); ?>
                                                            (<?php echo number_format(abs($diffPercent), 1); ?>%)
                                                        </span>
                                                    <?php else: ?>
                                                        <span class="badge bg-success">
                                                            <i class="bi bi-arrow-down"></i>
                                                            -<?php echo formatCurrency(abs($diff)); ?>
                                                            (<?php echo number_format(abs($diffPercent), 1); ?>%)
                                                        </span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <small class="text-muted">
                                                        <i class="bi bi-clock"></i>
                                                        <?php echo timeAgo($market['recorded_date']); ?>
                                                    </small>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>

                            <!-- Price Range Visualization -->
                            <div class="mt-4 p-3 bg-light rounded">
                                <h6 class="mb-3"><i class="bi bi-bar-chart"></i> Price Range Visualization</h6>
                                <div class="d-flex align-items-center gap-3">
                                    <small class="text-success fw-bold">Low<br><?php echo formatCurrency($comparisonData['min_price']); ?></small>
                                    <div class="flex-grow-1">
                                        <div class="progress" style="height: 30px;">
                                            <?php
                                            $range = $comparisonData['max_price'] - $comparisonData['min_price'];
                                            if ($range > 0):
                                                foreach ($comparisonData['markets'] as $market):
                                                    $position = (($market['price'] - $comparisonData['min_price']) / $range) * 100;
                                                    $color = $market['price'] <= $avgPrice ? 'success' : 'danger';
                                            ?>
                                                <div class="progress-bar bg-<?php echo $color; ?>" 
                                                     style="width: <?php echo number_format($position, 2); ?>%"
                                                     data-bs-toggle="tooltip"
                                                     title="<?php echo htmlspecialchars($market['location']); ?>: <?php echo formatCurrency($market['price']); ?>">
                                                </div>
                                            <?php 
                                                endforeach;
                                            endif;
                                            ?>
                                        </div>
                                        <div class="d-flex justify-content-between mt-1">
                                            <small class="text-success">Best Deal</small>
                                            <small class="text-primary">Average: <?php echo formatCurrency($avgPrice); ?></small>
                                            <small class="text-danger">Expensive</small>
                                        </div>
                                    </div>
                                    <small class="text-danger fw-bold">High<br><?php echo formatCurrency($comparisonData['max_price']); ?></small>
                                </div>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-5">
                                <i class="bi bi-inbox text-muted" style="font-size: 4rem;"></i>
                                <h5 class="mt-3">No Market Data Available</h5>
                                <p class="text-muted">No recent price data for comparison</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Set Alert CTA -->
        <div class="row">
            <div class="col-12">
                <div class="card border-0 shadow-sm bg-gradient" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                    <div class="card-body text-white text-center p-4">
                        <h4 class="mb-2"><i class="bi bi-bell-fill"></i> Want Price Alerts?</h4>
                        <p class="mb-3">Get notified when <?php echo ucwords(str_replace('_', ' ', $selectedProduct)); ?> prices meet your target</p>
                        <a href="<?php echo APP_URL; ?>/prices/set-alert.php?product=<?php echo urlencode($selectedProduct); ?>" 
                           class="btn btn-light btn-lg">
                            <i class="bi bi-bell-plus"></i> Set Price Alert Now
                        </a>
                    </div>
                </div>
            </div>
        </div>

    <?php elseif ($selectedProduct && !$hasData): ?>
        <!-- No Data Message -->
        <div class="row">
            <div class="col-12">
                <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 Price Data Available</h4>
                        <p class="text-muted">
                            We don't have recent price data for <?php echo ucwords(str_replace('_', ' ', $selectedProduct)); ?>.
                            <br>Please check back later or try another product.
                        </p>
                        <a href="<?php echo APP_URL; ?>/prices/" class="btn btn-primary mt-3">
                            View All Prices
                        </a>
                    </div>
                </div>
            </div>
        </div>
        
    <?php else: ?>
        <!-- Initial State -->
        <div class="row">
            <div class="col-12">
                <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 Compare Prices</h4>
                        <p class="text-muted">Choose a product from the dropdown above to see price comparisons across markets</p>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
// Auto-submit on selection
document.getElementById('productSelect').addEventListener('change', function() {
    if (this.value) {
        document.getElementById('compareForm').submit();
    }
});

// Initialize tooltips
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    return new bootstrap.Tooltip(tooltipTriggerEl);
});
</script>

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