<?php
/**
 * MJPOS -> MJ ERP Hub: Finance Summary Endpoint
 * Drop at: api/erp/finance-summary.php inside MJPOS project root
 *
 * GET /api/erp/finance-summary.php?from=2026-07-23&to=2026-07-30
 * Header: X-API-Key: <matches ERP Settings>
 *
 * Response:
 * { "status": "success", "data": [
 *     { "period_date": "2026-07-23", "revenue": 125000.50, "expenses": 34000.00, "net_profit": 91000.50 }
 * ]}
 */

require_once __DIR__ . '/erp_auth.php';
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 {
    // Revenue: `sales` table, completed sales only (same logic as sales-summary.php)
    $revenueStmt = erp_pdo()->prepare(
        "SELECT DATE(sale_date) AS period_date, SUM(total) AS revenue
         FROM sales
         WHERE DATE(sale_date) BETWEEN ? AND ? AND status = 'completed'
         GROUP BY DATE(sale_date)"
    );
    $revenueStmt->execute([$from, $to]);
    $revenueByDate = [];
    foreach ($revenueStmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
        $revenueByDate[$r['period_date']] = (float)$r['revenue'];
    }

    // Expenses: `expenses` table (Rent, Salaries, Electricity, etc. via expense_categories)
    $expenseStmt = erp_pdo()->prepare(
        "SELECT expense_date AS period_date, SUM(amount) AS expenses
         FROM expenses
         WHERE expense_date BETWEEN ? AND ?
         GROUP BY expense_date"
    );
    $expenseStmt->execute([$from, $to]);
    $expensesByDate = [];
    foreach ($expenseStmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
        $expensesByDate[$r['period_date']] = (float)$r['expenses'];
    }

    $allDates = array_unique(array_merge(array_keys($revenueByDate), array_keys($expensesByDate)));
    sort($allDates);

    $rows = [];
    foreach ($allDates as $date) {
        $revenue = $revenueByDate[$date] ?? 0;
        $expenses = $expensesByDate[$date] ?? 0;
        $rows[] = [
            'period_date' => $date,
            'revenue' => $revenue,
            'expenses' => $expenses,
            'net_profit' => $revenue - $expenses,
        ];
    }

    erp_json_success($rows);

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