<?php
require '/mnt/www-live/TechOdyssey_Designs_Dashboard/vendor/autoload.php';

use Goutte\Client;

function scrapeAmazonData($url) {
    $client = new Client();

    try {
        $crawler = $client->request('GET', $url);

        // Filter by `centerCol`
        $centerCol = $crawler->filter('#centerCol');

        // Scrape price
        $whole = $centerCol->filter('.a-price-whole')->count() ? $centerCol->filter('.a-price-whole')->text() : '0';
        $fraction = $centerCol->filter('.a-price-fraction')->count() ? $centerCol->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 discount
        $discount = $centerCol->filter('.savingsPercentage')->count() 
            ? preg_replace('/[^0-9]/', '', $centerCol->filter('.savingsPercentage')->text()) 
            : 0;

        // Scrape voucher
        $voucherText = '';
        $centerCol->filter('.promoPriceBlockMessage')->each(function ($node) use (&$voucherText) {
            $text = $node->text();
            if (preg_match('/Apply (\d+%|£\d+) voucher/', $text, $voucherMatch)) {
                $voucherText = $voucherMatch[1];
            }
        });

        // Parse voucher
        $voucherValue = 0;
        $voucherType = null;
        if (!empty($voucherText)) {
            if (strpos($voucherText, '%') !== false) {
                $voucherValue = (int) preg_replace('/[^0-9]/', '', $voucherText); // Extract percentage
                $voucherType = 'percentage';
            } elseif (strpos($voucherText, '£') !== false) {
                $voucherValue = (float) preg_replace('/[^0-9.]/', '', $voucherText); // Extract £ value
                $voucherType = 'fixed';
            }
        }

        return [
            'price' => $totalPrice,
            'currentDiscount' => [
                'discount' => [
                    'value' => $discount,
                    'type' => 'percentage'
                ],
                'voucher' => [
                    'value' => $voucherValue,
                    'type' => $voucherType
                ]
            ],
            'details' => [] // Placeholder for additional details if needed
        ];
    } catch (Exception $e) {
        return null; // Return null if scraping fails
    }
}
