<?php
/**
 * MJPOS -> MJ ERP Hub: Detailed Sales List Endpoint
 * Drop at: api/erp/sales-detail.php inside MJPOS project root
 *
 * GET /api/erp/sales-detail.php?from=2026-07-23&to=2026-07-30
 * Returns each individual sale transaction (not just daily totals) - the
 * ERP's Sales > Sales List tab lists every invoice.
 *
 * Response:
 * { "status": "success", "data": [
 *     { "id": 42, "invoice_no": "INV-0042", "sale_date": "2026-07-28 14:32:10",
 *       "customer_name": "Walk-in", "customer_phone": null, "total": 1250.00,
 *       "paid": 1250.00, "balance": 0.00, "payment_status": "paid", "status": "completed" }
 * ]}
 */

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: `sales` joined to `customers` (nullable - walk-in sales have no customer_id)
    $stmt = erp_pdo()->prepare(
        "SELECT s.id, s.invoice_no, s.sale_date,
                COALESCE(c.customer_name, s.customer_phone, 'Walk-in') AS customer_name,
                s.customer_phone, s.total, s.paid, s.balance, s.payment_status, s.status
         FROM sales s
         LEFT JOIN customers c ON s.customer_id = c.id
         WHERE DATE(s.sale_date) BETWEEN ? AND ?
           AND s.status != 'cancelled'
         ORDER BY s.sale_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);
}
