<?php
/**
 * MJPOS -> MJ ERP Hub: Credit Book Endpoint
 * Drop at: api/erp/credit-book.php inside MJPOS project root
 *
 * GET /api/erp/credit-book.php
 * Returns customers who owe money (current_balance > 0 = they owe us) and
 * suppliers we owe money to (current_balance > 0 = outstanding payable).
 * Only non-zero balances are returned - a settled account doesn't need tracking.
 *
 * Response shape is DIFFERENT from other endpoints - "data" is an object
 * with two keys, not a flat array:
 * { "status": "success", "data": {
 *     "customers": [ { "id": 2, "party_name": "H M WENURADA SAMPATH BANDARA", "phone": "0767450808", "current_balance": 0.00 } ],
 *     "suppliers": [ { "id": 19, "party_name": "M.R.M.ASKAR", "phone": null, "current_balance": 111320.63 } ]
 * }}
 */

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

erp_require_auth();

try {
    // Confirmed against MJPOS schema: `customers.current_balance` (positive = customer owes us)
    $customerStmt = erp_pdo()->query(
        "SELECT id, customer_name AS party_name, phone, current_balance
         FROM customers
         WHERE current_balance <> 0 AND status = 'active'
         ORDER BY current_balance DESC"
    );
    $customers = $customerStmt->fetchAll(PDO::FETCH_ASSOC);

    // Confirmed against MJPOS schema: `suppliers.current_balance` (positive = outstanding payable, we owe them)
    $supplierStmt = erp_pdo()->query(
        "SELECT id, supplier_name AS party_name, phone, current_balance
         FROM suppliers
         WHERE current_balance <> 0 AND status = 'active'
         ORDER BY current_balance DESC"
    );
    $suppliers = $supplierStmt->fetchAll(PDO::FETCH_ASSOC);

    erp_json_success([
        'customers' => $customers,
        'suppliers' => $suppliers,
    ]);

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