<?php
/**
 * Product API - Quick view data
 */
header('Content-Type: application/json');
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/functions.php';

$id   = (int)($_GET['id'] ?? 0);
$slug = trim($_GET['slug'] ?? '');

try {
    // Note: product.php is a GET request usually, but let's be safe. 
    // Usually we don't verify CSRF on GET for data fetching, but we'll wrap in try-catch.
    
    if ($id) {
        $product = Database::fetchOne(
            "SELECT p.*, c.name as category_name FROM products p LEFT JOIN categories c ON p.category_id=c.id WHERE p.id=? AND p.is_active=1",
            [$id]
        );
    } elseif ($slug) {
        $product = Database::fetchOne(
            "SELECT p.*, c.name as category_name FROM products p LEFT JOIN categories c ON p.category_id=c.id WHERE p.slug=? AND p.is_active=1",
            [$slug]
        );
    } else {
        echo json_encode(['error' => 'Product not found.']);
        exit;
    }

    if (!$product) {
        echo json_encode(['error' => 'Product not found.']);
        exit;
    }

    // Increment views
    Database::execute("UPDATE products SET views=views+1 WHERE id=?", [$product['id']]);

    // Parse specifications
    if ($product['specifications']) {
        $specs = json_decode($product['specifications'], true);
        if (!$specs) $specs = $product['specifications']; // plain text fallback
        $product['specs_parsed'] = $specs;
    }

    // Gallery
    $product['gallery_parsed'] = $product['gallery'] ? json_decode($product['gallery'], true) : [];

    echo json_encode($product);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'API Error: ' . $e->getMessage()]);
}
