<?php
/**
 * MJPOS -> MJ ERP Hub: Detailed Expenses Endpoint
 * Drop at: api/erp/expenses-detail.php inside MJPOS project root
 *
 * GET /api/erp/expenses-detail.php?from=2026-07-23&to=2026-07-30
 * Returns the full itemized expense list (not just daily totals - the
 * ERP's Finance > Expenses tab lists each individual expense).
 *
 * Response:
 * { "status": "success", "data": [
 *     { "id": 15, "expense_date": "2026-07-28", "category": "Rent", "title": "KUSSIYA, DUBAI SHOP",
 *       "amount": 45000.00, "reference": "VT/07/32", "note": "KUSSIYA 30000, DUBAI SHOP 15000" }
 * ]}
 */

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: `expenses` joined to `expense_categories`
    $stmt = erp_pdo()->prepare(
        "SELECT e.id, e.expense_date, ec.category_name AS category, e.title, e.amount, e.reference, e.note
         FROM expenses e
         LEFT JOIN expense_categories ec ON e.expense_category_id = ec.id
         WHERE e.expense_date BETWEEN ? AND ?
         ORDER BY e.expense_date DESC, e.id 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);
}
