<?php
/**
 * MJPOS -> MJ ERP Hub: Products & Stock Endpoint
 * Drop at: api/erp/products-list.php inside MJPOS project root
 *
 * GET /api/erp/products-list.php
 * Returns the full CURRENT product catalog with stock levels (snapshot,
 * not date-filtered - stock is a point-in-time state).
 *
 * Response:
 * { "status": "success", "data": [
 *     { "id": 11, "product_code": "KU-110005", "barcode": null, "product_name": "RICE COOKER KAWASHI 1L",
 *       "category": "ELECTRIC ITEMS", "brand": "KAWASHI", "unit": "Piece", "cost_price": 3900.00,
 *       "selling_price": 5100.00, "current_stock": 1.00, "reorder_level": 2, "has_expiry": 0,
 *       "expiry_date": null, "status": "active" }
 * ]}
 */

require_once __DIR__ . '/erp_auth.php';
require_once __DIR__ . '/../../mjpos/config/config.php';

erp_require_auth();

try {
    // Confirmed against MJPOS schema: `products` joined to categories/brands/units
    $stmt = erp_pdo()->query(
        "SELECT p.id, p.product_code, p.barcode, p.product_name,
                c.category_name AS category, b.brand_name AS brand, u.short_name AS unit,
                p.cost_price, p.selling_price, p.current_stock, p.reorder_level,
                p.has_expiry, p.expiry_date, p.status
         FROM products p
         LEFT JOIN categories c ON p.category_id = c.id
         LEFT JOIN brands b ON p.brand_id = b.id
         LEFT JOIN units u ON p.unit_id = u.id
         WHERE p.status = 'active'
         ORDER BY p.product_name"
    );
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    erp_json_success($rows);

} catch (Exception $e) {
    erp_json_error('Query failed: ' . $e->getMessage(), 500);
}
