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

include '../src/session_check.php';
checkUserRole(['admin']);

use Goutte\Client;

// Start session to get user ID
session_start();
if (!isset($_SESSION['userId'])) {
    echo json_encode(['status' => 'error', 'message' => 'User not authenticated.']);
    exit;
}

// Check for POST data
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $filamentName = $_POST['productName'] ?? '';
    $amazonUrl = $_POST['productUrl'] ?? '';
    $userId = $_SESSION['userId'];

    // Basic validation
    if (empty($filamentName) || empty($amazonUrl)) {
        echo json_encode(['status' => 'error', 'message' => 'Filament name and URL are required.']);
        exit;
    }

    $client = new Client();
    try {
        // Scrape the Amazon page for initial price and other details
        $crawler = $client->request('GET', $amazonUrl);
        
        // Scrape Price
        $whole = $crawler->filter('.a-price-whole')->count() ? $crawler->filter('.a-price-whole')->text() : '0';
        $fraction = $crawler->filter('.a-price-fraction')->count() ? $crawler->filter('.a-price-fraction')->text() : '00';

        $whole = preg_replace('/[^0-9]/', '', $whole);
        $fraction = preg_replace('/[^0-9]/', '', $fraction);
        $fraction = strlen($fraction) === 1 ? $fraction . '0' : substr($fraction, 0, 2);
        $totalPrice = floatval($whole . '.' . $fraction);

        // Scrape Filament Details from Table
        $details = [];
        $crawler->filter('table.a-normal tr')->each(function ($node) use (&$details) {
            $label = trim($node->filter('td.a-span3')->text());
            $value = trim($node->filter('td.a-span9')->text());
            $details[$label] = $value;
        });


        // Extract details or use default if not found
        $brand = $details['Brand'] ?? 'Unknown';
        $material = $details['Material'] ?? 'Unknown';
        $color = $details['Colour'] ?? 'Unknown';
        $filamentWeight = isset($details['Item weight']) ? preg_replace('/[^0-9.]/', '', $details['Item weight']) : 1;
        if (stripos($details['Item weight'], 'kilograms') !== false || stripos($details['Item weight'], 'kg') !== false) {
            $filamentWeight = $filamentWeight * 1000;  // Convert KG to G
        }
        $itemDiameter = isset($details['Item diameter']) ? preg_replace('/[^0-9.]/', '', $details['Item diameter']) : 1.75;

        // Start a transaction to ensure consistency
        $pdo->beginTransaction();

        // Check if filament already exists
        $stmt = $pdo->prepare("SELECT id FROM filamentTracker WHERE amazonUrl = :amazonUrl");
        $stmt->execute([':amazonUrl' => $amazonUrl]);
        $existingFilament = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($existingFilament) {
            // Filament exists – just update the price history
            $filamentId = $existingFilament['id'];
            $stmt = $pdo->prepare("
                INSERT INTO filamentPriceHistory (filamentId, price) 
                VALUES (:filamentId, :price)
            ");
            $stmt->execute([
                ':filamentId' => $filamentId,
                ':price' => $totalPrice
            ]);
            $message = 'Filament price updated successfully.';
        } else {
            // Insert new filament into filamentTracker
            $stmt = $pdo->prepare("
                INSERT INTO filamentTracker (userId, filamentName, amazonUrl, filamentWeight, brand, material, color, itemDiameter)
                VALUES (:userId, :filamentName, :amazonUrl, :filamentWeight, :brand, :material, :color, :itemDiameter)
            ");
            $stmt->execute([
                ':userId' => $userId,
                ':filamentName' => $filamentName,
                ':amazonUrl' => $amazonUrl,
                ':filamentWeight' => $filamentWeight,
                ':brand' => $brand,
                ':material' => $material,
                ':color' => $color,
                ':itemDiameter' => $itemDiameter
            ]);

            // Get the last inserted filament ID
            $filamentId = $pdo->lastInsertId();

            // Insert initial price into filamentPriceHistory
            $stmt = $pdo->prepare("
                INSERT INTO filamentPriceHistory (filamentId, price) 
                VALUES (:filamentId, :price)
            ");
            $stmt->execute([
                ':filamentId' => $filamentId,
                ':price' => $totalPrice
            ]);

            $message = $filamentName . ' Filament added successfully and price tracked.';
        }

        // Commit the transaction
        $pdo->commit();

        echo json_encode(['status' => 'success', 'message' => $message]);
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['status' => 'error', 'message' => 'Failed to scrape or insert data. Error: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
}
?>
