<?php
/**
 * MJ ERP HUB - Real-Time Push Notifier (drop into MJPOS)
 * Drop at: includes/erp_push.php inside MJPOS project root (or wherever
 * shared helper files live - adjust the require path in your sale-save
 * code to match).
 *
 * USAGE - add this ONE line right after a sale/expense/employee record
 * is successfully saved:
 *
 *   require_once __DIR__ . '/../includes/erp_push.php'; // adjust path
 *   erp_notify_change('sales');       // after a sale is saved
 *   erp_notify_change('finance');     // after an expense is saved (affects P&L)
 *   erp_notify_change('employees');   // after an employee/payroll record changes
 *
 * This does NOT send your actual sales data - it just tells the ERP Hub
 * "hey, sales changed for today, go re-check". The ERP Hub then pulls the
 * real numbers itself via the existing api/erp/*.php endpoints (same ones
 * already tested). If this call fails or times out, nothing breaks - the
 * regular cron sync will still catch it up within its interval.
 */

// ---- Configure these two values ----
define('ERP_WEBHOOK_URL', 'https://kussiya.mjpos.live/api/webhook/receive.php'); // TODO: set your real ERP Hub domain
define('ERP_WEBHOOK_API_KEY', ''Kx9mP2vLq8wR4tZ7nB3jF6hD1yG5sA0c'); // TODO: must match Settings > MJPOS > API Key AND api/erp/erp_auth.php's ERP_API_KEY

/**
 * Fire a best-effort, short-timeout notification to the ERP Hub.
 * Never throws - a slow/broken ERP Hub must never break the MJPOS sale flow.
 *
 * @param string $type 'sales' | 'finance' | 'employees' | 'all'
 * @param string|null $date defaults to today
 */
function erp_notify_change(string $type, ?string $date = null): void {
    $date = $date ?? date('Y-m-d');

    $payload = json_encode([
        'system' => 'mjpos',
        'type' => $type,
        'date' => $date,
    ]);

    $ch = curl_init(ERP_WEBHOOK_URL);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'X-API-Key: ' . ERP_WEBHOOK_API_KEY,
        ],
        // Short timeouts - this must never noticeably slow down a sale being saved.
        // If the ERP Hub is slow/down, we give up fast and let the cron catch up later.
        CURLOPT_CONNECTTIMEOUT => 2,
        CURLOPT_TIMEOUT => 3,
    ]);

    // Best-effort only - swallow all errors silently, never let this break the caller.
    try {
        @curl_exec($ch);
    } catch (Throwable $e) {
        // intentionally ignored
    } finally {
        curl_close($ch);
    }
}
