<?php
/**
 * ============================================================================
 * prices/history.php - Price History & Archive
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Price History';

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

// Get filters
$productType = $_GET['product'] ?? '';
$location = $_GET['location'] ?? '';
$dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
$dateTo = $_GET['date_to'] ?? date('Y-m-d');

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

// Get historical prices
$sql = "SELECT * FROM market_prices WHERE 1=1";
$params = [];

if ($productType) {
    $sql .= " AND product_type = ?";
    $params[] = $productType;
}

if ($location) {
    $sql .= " AND market_location = ?";
    $params[] = $location;
}

$sql .= " AND price_date BETWEEN ? AND ?";
$params[] = $dateFrom;
$params[] = $dateTo;

$sql .= " ORDER BY price_date DESC, product_type, market_location";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$historicalPrices = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate statistics
$stats = [
    'total_entries' => count($historicalPrices),
    'avg_price' => 0,
    'min_price' => 0,
    'max_price' => 0,
    'products_tracked' => 0
];

if (!empty($historicalPrices)) {
    $prices = array_column($historicalPrices, 'price');
    $stats['avg_price'] = array_sum($prices) / count($prices);
    $stats['min_price'] = min($prices);
    $stats['max_price'] = max($prices);
    $stats['products_tracked'] = count(array_unique(array_column($historicalPrices, 'product_type')));
}

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

<style>
.history-card {
    transition: all 0.3s ease;
}

.history-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.timeline {
    position: relative;
    padding-left: 30px;
}

.timeline::before {
    content: '';
    position: absolute;
    left: 10px;
    top: 0;
    bottom: 0;
    width: 2px;
    background: #e5e7eb;
}

.timeline-item {
    position: relative;
    padding-bottom: 1.5rem;
}

.timeline-item::before {
    content: '';
    position: absolute;
    left: -24px;
    top: 8px;
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background: white;
    border: 3px solid #059669;
}

.price-change-badge {
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.875rem;
    font-weight: 600;
}

.date-badge {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 0.5rem 1rem;
    border-radius: 10px;
    display: inline-block;
    margin-bottom: 1rem;
}

.export-btn {
    background: #059669;
    color: white;
    transition: all 0.3s;
}

.export-btn:hover {
    background: #047857;
    transform: scale(1.05);
}
</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-clock-history text-info"></i> Price History
                    </h2>
                    <p class="text-muted mb-0">View historical price data and trends</p>
                </div>
                <div class="d-flex gap-2">
                    <button class="btn export-btn" onclick="exportToCSV()">
                        <i class="bi bi-download"></i> Export CSV
                    </button>
                    <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>

    <div class="row">
        <!-- Filters -->
        <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"></i> Filters
                    </h5>
                </div>
                <div class="card-body">
                    <form method="GET" id="filterForm">
                        <!-- Product Type -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Product</label>
                            <select class="form-select" name="product">
                                <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 ucwords(str_replace('_', ' ', $type['product_type'])); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <!-- Location -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Location</label>
                            <select class="form-select" name="location">
                                <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>

                        <!-- Date Range -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">From Date</label>
                            <input type="date" class="form-control" name="date_from" 
                                   value="<?php echo htmlspecialchars($dateFrom); ?>">
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-semibold">To Date</label>
                            <input type="date" class="form-control" name="date_to" 
                                   value="<?php echo htmlspecialchars($dateTo); ?>">
                        </div>

                        <!-- Quick Date Filters -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Quick Select</label>
                            <div class="d-grid gap-2">
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setDateRange(7)">
                                    Last 7 Days
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setDateRange(30)">
                                    Last 30 Days
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setDateRange(90)">
                                    Last 90 Days
                                </button>
                            </div>
                        </div>

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

                <!-- Statistics -->
                <div class="card-footer bg-light">
                    <h6 class="mb-3">Statistics</h6>
                    <div class="mb-2">
                        <small class="text-muted">Total Entries</small>
                        <div class="fw-bold"><?php echo $stats['total_entries']; ?></div>
                    </div>
                    <?php if ($stats['total_entries'] > 0): ?>
                    <div class="mb-2">
                        <small class="text-muted">Average Price</small>
                        <div class="fw-bold text-primary"><?php echo formatCurrency($stats['avg_price']); ?></div>
                    </div>
                    <div class="mb-2">
                        <small class="text-muted">Price Range</small>
                        <div class="fw-bold">
                            <?php echo formatCurrency($stats['min_price']); ?> - 
                            <?php echo formatCurrency($stats['max_price']); ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- History Timeline -->
        <div class="col-lg-9">
            <?php if (!empty($historicalPrices)): ?>
                <?php
                // Group by date
                $pricesByDate = [];
                foreach ($historicalPrices as $price) {
                    $date = $price['price_date'];
                    if (!isset($pricesByDate[$date])) {
                        $pricesByDate[$date] = [];
                    }
                    $pricesByDate[$date][] = $price;
                }
                ?>

                <!-- View Toggle -->
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5>
                        <i class="bi bi-list-ul"></i> 
                        Showing <?php echo count($historicalPrices); ?> entries
                    </h5>
                    <div class="btn-group" role="group">
                        <input type="radio" class="btn-check" name="viewMode" id="timelineView" checked>
                        <label class="btn btn-outline-primary" for="timelineView">
                            <i class="bi bi-clock-history"></i> Timeline
                        </label>
                        <input type="radio" class="btn-check" name="viewMode" id="tableView">
                        <label class="btn btn-outline-primary" for="tableView">
                            <i class="bi bi-table"></i> Table
                        </label>
                    </div>
                </div>

                <!-- Timeline View -->
                <div id="timelineContent">
                    <?php foreach ($pricesByDate as $date => $dayPrices): ?>
                        <div class="mb-4">
                            <div class="date-badge">
                                <i class="bi bi-calendar3"></i>
                                <?php echo date('l, F j, Y', strtotime($date)); ?>
                            </div>

                            <div class="timeline">
                                <?php foreach ($dayPrices as $price): ?>
                                    <div class="timeline-item">
                                        <div class="card history-card border-0 shadow-sm">
                                            <div class="card-body">
                                                <div class="row align-items-center">
                                                    <div class="col-md-4">
                                                        <h6 class="mb-1">
                                                            <?php echo ucwords(str_replace('_', ' ', $price['product_type'])); ?>
                                                        </h6>
                                                        <small class="text-muted">
                                                            <i class="bi bi-geo-alt"></i>
                                                            <?php echo htmlspecialchars($price['market_location']); ?>
                                                        </small>
                                                    </div>
                                                    <div class="col-md-3 text-center">
                                                        <h4 class="mb-0 text-success">
                                                            <?php echo formatCurrency($price['price']); ?>
                                                        </h4>
                                                        <small class="text-muted">per <?php echo htmlspecialchars($price['unit']); ?></small>
                                                    </div>
                                                    <div class="col-md-3">
                                                        <small class="text-muted d-block">Source</small>
                                                        <span class="badge bg-info">
                                                            <?php echo htmlspecialchars($price['source']); ?>
                                                        </span>
                                                    </div>
                                                    <div class="col-md-2 text-end">
                                                        <button class="btn btn-sm btn-outline-primary" 
                                                                onclick="viewPriceDetails(<?php echo $price['id']; ?>)">
                                                            <i class="bi bi-eye"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

                <!-- Table View -->
                <div id="tableContent" style="display: none;">
                    <div class="card border-0 shadow-sm">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover align-middle" id="historyTable">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Date</th>
                                            <th>Product</th>
                                            <th>Location</th>
                                            <th class="text-end">Price</th>
                                            <th>Unit</th>
                                            <th>Source</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($historicalPrices as $price): ?>
                                            <tr>
                                                <td><?php echo formatDate($price['price_date']); ?></td>
                                                <td><?php echo ucwords(str_replace('_', ' ', $price['product_type'])); ?></td>
                                                <td>
                                                    <i class="bi bi-geo-alt text-danger"></i>
                                                    <?php echo htmlspecialchars($price['market_location']); ?>
                                                </td>
                                                <td class="text-end">
                                                    <strong><?php echo formatCurrency($price['price']); ?></strong>
                                                </td>
                                                <td><?php echo htmlspecialchars($price['unit']); ?></td>
                                                <td>
                                                    <span class="badge bg-info">
                                                        <?php echo htmlspecialchars($price['source']); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <button class="btn btn-sm btn-outline-primary" 
                                                            onclick="viewPriceDetails(<?php echo $price['id']; ?>)">
                                                        <i class="bi bi-eye"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

            <?php else: ?>
                <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 Historical Data Found</h4>
                        <p class="text-muted">
                            No price records found for the selected filters.<br>
                            Try adjusting your date range or filters.
                        </p>
                        <button class="btn btn-primary" onclick="resetFilters()">
                            <i class="bi bi-arrow-counterclockwise"></i> Reset Filters
                        </button>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
// View mode toggle
document.querySelectorAll('input[name="viewMode"]').forEach(radio => {
    radio.addEventListener('change', function() {
        if (this.id === 'timelineView') {
            document.getElementById('timelineContent').style.display = 'block';
            document.getElementById('tableContent').style.display = 'none';
        } else {
            document.getElementById('timelineContent').style.display = 'none';
            document.getElementById('tableContent').style.display = 'block';
        }
    });
});

// Set date range
function setDateRange(days) {
    const today = new Date();
    const fromDate = new Date(today);
    fromDate.setDate(fromDate.getDate() - days);
    
    document.querySelector('input[name="date_from"]').value = fromDate.toISOString().split('T')[0];
    document.querySelector('input[name="date_to"]').value = today.toISOString().split('T')[0];
}

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

// View price details
function viewPriceDetails(priceId) {
    // You can implement a modal or redirect to details page
    showToast('Price details feature coming soon!', 'info');
}

// Export to CSV
function exportToCSV() {
    const table = document.getElementById('historyTable');
    if (!table) {
        showToast('No data to export', 'warning');
        return;
    }
    
    let csv = [];
    const rows = table.querySelectorAll('tr');
    
    for (let row of rows) {
        const cols = row.querySelectorAll('td, th');
        const csvRow = [];
        for (let col of cols) {
            if (col.querySelector('.btn')) continue; // Skip action column
            csvRow.push('"' + col.textContent.trim().replace(/"/g, '""') + '"');
        }
        csv.push(csvRow.join(','));
    }
    
    const csvContent = csv.join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'price_history_' + new Date().toISOString().split('T')[0] + '.csv';
    a.click();
    window.URL.revokeObjectURL(url);
    
    showToast('Price history exported successfully!', 'success');
}
</script>

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