<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require '../../vendor/autoload.php';
require '../db.php';
require_once '../envLoader.php';
require 'scraper.php'; // Include the scraper file
loadEnv(__DIR__ . '/../../.env');

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

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

// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $filamentName = $_POST['productName'] ?? '';
    $amazonUrl = $_POST['productUrl'] ?? '';
    $userId = $_SESSION['userId'];

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

    try {
        // Scrape data from Amazon
        $scrapedData = scrapeAmazonData($amazonUrl);
        if (!$scrapedData) {
            throw new Exception('Scraping failed for the provided URL.');
        }

        $price = $scrapedData['price'];
        $currentDiscount = json_encode($scrapedData['currentDiscount']); // Convert discount to JSON
        $details = $scrapedData['details'] ?? [];

        // Extract details or use defaults
        $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 *= 1000; // Convert KG to G
        }
        $itemDiameter = isset($details['Item diameter']) ? preg_replace('/[^0-9.]/', '', $details['Item diameter']) : 1.75;

        // Begin transaction for database operations
        $pdo->beginTransaction();

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

        if ($existingFilament) {
            // If the filament exists, update the price and discount
            $filamentId = $existingFilament['id'];
            $stmt = $pdo->prepare("
                INSERT INTO filamentPriceHistory (filamentId, price, currentDiscount) 
                VALUES (:filamentId, :price, :currentDiscount)
            ");
            $stmt->execute([
                ':filamentId' => $filamentId,
                ':price' => $price,
                ':currentDiscount' => $currentDiscount
            ]);
            $message = 'Filament price and discount updated successfully.';
        } else {
            // If the filament does not exist, insert it 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 ID of the newly inserted filament
            $filamentId = $pdo->lastInsertId();

            // Insert the initial price and discount into filamentPriceHistory
            $stmt = $pdo->prepare("
                INSERT INTO filamentPriceHistory (filamentId, price, currentDiscount) 
                VALUES (:filamentId, :price, :currentDiscount)
            ");
            $stmt->execute([
                ':filamentId' => $filamentId,
                ':price' => $price,
                ':currentDiscount' => $currentDiscount
            ]);
            $message = "$filamentName added successfully and price with discount tracked.";
        }

        // Commit the transaction
        $pdo->commit();
        echo json_encode(['status' => 'success', 'message' => $message]);
    } catch (Exception $e) {
        // Rollback transaction if any exception occurs
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
}
?>
