<?php
/**
 * MJPOS -> MJ ERP Hub: Purchases Endpoint
 * Drop at: api/erp/purchases-list.php inside MJPOS project root
 *
 * GET /api/erp/purchases-list.php?from=2026-07-23&to=2026-07-30
 * Returns each purchase invoice (goods received from suppliers).
 *
 * Response:
 * { "status": "success", "data": [
 *     { "id": 2, "invoice_no": "PUR-20260701-0001", "purchase_date": "2026-07-01",
 *       "supplier_name": "DUM DUM", "total": 85010.93, "paid": 53190.24, "balance": 0.00,
 *       "payment_status": "paid", "status": "received" }
 * ]}
 */

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: `purchases` joined to `suppliers`
    $stmt = erp_pdo()->prepare(
        "SELECT p.id, p.invoice_no, p.purchase_date, s.supplier_name, p.total, p.paid, p.balance, p.payment_status, p.status
         FROM purchases p
         LEFT JOIN suppliers s ON p.supplier_id = s.id
         WHERE p.purchase_date BETWEEN ? AND ?
           AND p.status != 'cancelled'
         ORDER BY p.purchase_date DESC"
    );
    $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);
}
