<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require 'db_config.php';
header('Content-Type: application/json');

try {
    $stmt = $pdo->query("SELECT * FROM products ORDER BY id DESC");
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Convert numeric strings to numbers
    foreach ($products as &$p) {
        $p['id'] = (int)$p['id'];
        $p['purchase_price'] = (double)$p['purchase_price'];
        $p['wholesale_price'] = (double)$p['wholesale_price'];
        $p['retail_price'] = (double)$p['retail_price'];
        // image_path comes directly from DB (e.g., "uploads/prod_123.jpg")
    }

    echo json_encode(['status' => 'success', 'data' => $products]);
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => 'DB Error: ' . $e->getMessage()]);
}
?>