<?php
/**
 * MJPOS -> MJ ERP Hub: Stock Movements Endpoint
 * Drop at: api/erp/stock-movements.php inside MJPOS project root
 *
 * GET /api/erp/stock-movements.php?from=2026-07-23&to=2026-07-30
 * Returns the stock movement ledger (purchases, sales, adjustments, transfers,
 * damaged stock) for the requested date range.
 *
 * Response:
 * { "status": "success", "data": [
 *     { "id": 44, "product_id": 57, "product_name": "SOME PRODUCT", "movement_type": "purchase",
 *       "quantity_in": 12.00, "quantity_out": 0.00, "stock_after": 12.00,
 *       "reference_no": "PUR-20260701-0001", "note": "Purchase: PUR-20260701-0001",
 *       "movement_date": "2026-07-01 12:52:05" }
 * ]}
 */

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

erp_require_auth();
list($from, $to) = erp_get_date_range();

try {
    // Confirmed against MJPOS schema: `stock_movements` joined to `products` for the name
    $stmt = erp_pdo()->prepare(
        "SELECT sm.id, sm.product_id, p.product_name, sm.movement_type, sm.quantity_in, sm.quantity_out,
                sm.stock_after, sm.reference_no, sm.note, sm.created_at AS movement_date
         FROM stock_movements sm
         LEFT JOIN products p ON sm.product_id = p.id
         WHERE DATE(sm.created_at) BETWEEN ? AND ?
         ORDER BY sm.created_at DESC
         LIMIT 1000"
    );
    $stmt->execute([$from, $to]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    erp_json_success($rows);

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