<?php
/**
 * ICYLAB OS - API para Ficha de Producto (Popup)
 */
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';
require_once '../../core/permissions.php'; // Agrega esto en los require

require_login();
require_permission('module.products'); // Agrega este candado

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$pdo = db();

$stmt = $pdo->prepare("
    SELECT p.*, c.name as category_name 
    FROM products p 
    LEFT JOIN product_categories c ON p.category_id = c.id 
    WHERE p.id = ? LIMIT 1
");
$stmt->execute([$id]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$product) {
    echo json_encode(['success' => false, 'message' => 'Producto no encontrado']);
    exit;
}

$price = (float)$product['price'];
$cost = (float)$product['cost'];
$marginAbs = $price - $cost;
$marginPct = $price > 0 ? ($marginAbs / $price) * 100 : 0;

echo json_encode([
    'success' => true,
    'product' => $product,
    'calculated' => [
        'price_formatted' => '$' . number_format($price, 0, ',', '.'),
        'cost_formatted' => '$' . number_format($cost, 0, ',', '.'),
        'margin_abs_formatted' => '$' . number_format($marginAbs, 0, ',', '.'),
        'margin_pct_formatted' => number_format($marginPct, 1, ',', '.') . '%',
        'margin_abs' => $marginAbs,
        'margin_pct' => $marginPct
    ]
]);