<?php
require '../../vendor/autoload.php';
require '../db.php';
require_once '../envLoader.php';
loadEnv(__DIR__ . '/../../.env');

include '../src/session_check.php';

header('Content-Type: application/json');

try {
    // Query 1: Fetch filament details and price history
    $stmt1 = $pdo->query("
        SELECT ft.id AS filamentId, 
               ft.filamentName, 
               ft.brand,
               ft.material,
               ft.color,
               ft.amazonUrl,
               fp.price,
               fp.recordedAt
        FROM filamentTracker ft
        JOIN filamentPriceHistory fp ON ft.id = fp.filamentId
        ORDER BY ft.filamentName ASC, fp.recordedAt ASC;
    ");
    $filaments = $stmt1->fetchAll(PDO::FETCH_ASSOC);

    // Query 2: Fetch the latest discount for each filament
    $stmt2 = $pdo->query("
        SELECT filamentId, 
               JSON_OBJECT(
                   'discount', JSON_OBJECT('value', MAX(JSON_EXTRACT(currentDiscount, '$.discount.value')), 'type', 'percentage'),
                   'voucher', JSON_OBJECT('value', MAX(JSON_EXTRACT(currentDiscount, '$.voucher.value')), 'type', MAX(JSON_UNQUOTE(JSON_EXTRACT(currentDiscount, '$.voucher.type'))))
               ) AS currentDiscount
        FROM filamentPriceHistory
        GROUP BY filamentId;
    ");
    $discounts = $stmt2->fetchAll(PDO::FETCH_ASSOC);

    // Create a mapping of filamentId to discounts
    $discountMap = [];
    foreach ($discounts as $discount) {
        $discountMap[$discount['filamentId']] = json_decode($discount['currentDiscount'], true);
    }

    // Format data for response
    $result = [];
    foreach ($filaments as $filament) {
        $name = $filament['filamentName'];

        if (!isset($result[$name])) {
            $result[$name] = [
                'brand' => $filament['brand'],
                'material' => $filament['material'],
                'color' => $filament['color'],
                'amazonUrl' => $filament['amazonUrl'],
                'prices' => [],
                'currentDiscount' => $discountMap[$filament['filamentId']] ?? [
                    'discount' => ['value' => 0, 'type' => 'none'],
                    'voucher' => ['value' => 0, 'type' => 'none']
                ]
            ];
        }

        $result[$name]['prices'][] = [
            'price' => (float)$filament['price'],
            'recordedAt' => $filament['recordedAt']
        ];
    }

    // Return as JSON
    echo json_encode([
        'status' => 'success',
        'data' => $result
    ], JSON_PRETTY_PRINT);
} catch (PDOException $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Failed to fetch filament prices: ' . $e->getMessage()
    ]);
}
?>
