<?php
/**
 * MJPOS -> MJ ERP Hub: Sales Summary Endpoint
 * Drop at: api/erp/sales-summary.php inside MJPOS project root
 *
 * GET /api/erp/sales-summary.php?from=2026-07-23&to=2026-07-30
 * Header:    X-API-Key: <matches Settings > MJPOS > API Key in ERP>
 *
 * Response format expected by MJ ERP Hub (do not change the shape):
 * {
 *   "status": "success",
 *   "data": [
 *     { "period_date": "2026-07-23", "total_sales": 125000.50, "total_transactions": 42 },
 *     ...
 *   ]
 * }
 */

require_once __DIR__ . '/erp_auth.php';

// Adjust this path if MJPOS's config.php lives somewhere else.
// Exposes DB_HOST/DB_NAME/DB_USER/DB_PASS constants (erp_pdo() in erp_auth.php uses these).
require_once __DIR__ . '/../../mjpos/config/config.php'; // MJPOS app lives in the 'mjpos' subfolder

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

try {
    // Confirmed against MJPOS schema: `sales` table, columns `sale_date`, `total`, `status`.
    // Only 'completed' sales count as revenue - 'held' (unfinished), 'cancelled', and
    // 'returned' (fully refunded) are excluded so this matches actual recognized revenue.
    $stmt = erp_pdo()->prepare(
        "SELECT DATE(sale_date) AS period_date,
                SUM(total) AS total_sales,
                COUNT(*) AS total_transactions
         FROM sales
         WHERE DATE(sale_date) BETWEEN ? AND ?
           AND status = 'completed'
         GROUP BY DATE(sale_date)
         ORDER BY period_date"
    );
    $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);
}
