<?php
/**
 * MJ ERP HUB - Webhook Receiver (real-time push sync)
 *
 * MJPOS / DriveLink SL call this immediately after a sale, expense, or
 * employee record changes. Instead of trusting numbers sent in the
 * webhook body, this just triggers an INSTANT targeted re-pull of that
 * one day via the existing, already-verified sync_engine + api/erp/*.php
 * endpoints. Single source of truth stays the source system's own DB.
 *
 * POST https://erp.yourdomain.com/api/webhook/receive.php
 * Headers: X-API-Key: <same key as that system's Settings > API Key>
 * Body (JSON): { "system": "mjpos", "type": "sales", "date": "2026-07-30" }
 *   - "type" can be: sales | finance | employees | all
 *   - "date" optional, defaults to today (Asia/Colombo)
 */

require_once __DIR__ . '/../../config/config.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Method not allowed - use POST']);
    exit;
}

$raw = file_get_contents('php://input');
$body = json_decode($raw, true);

if (!is_array($body) || empty($body['system'])) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Missing required field: system']);
    exit;
}

$systemCode = trim($body['system']);
$type = $body['type'] ?? 'all';
$date = $body['date'] ?? date('Y-m-d');

if (!strtotime($date)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid date format, expected YYYY-MM-DD']);
    exit;
}
$date = date('Y-m-d', strtotime($date));

$validTypes = array_merge(SyncEngine::TYPES, ['all']);
if (!in_array($type, $validTypes, true)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid type - must be one of: ' . implode(', ', $validTypes)]);
    exit;
}

// ---- Authenticate: API key must match the system's stored key ----
$headers = function_exists('getallheaders') ? getallheaders() : [];
$apiKey = $headers['X-Api-Key'] ?? $headers['X-API-Key'] ?? $_SERVER['HTTP_X_API_KEY'] ?? null;

$db = getDB();
$stmt = $db->prepare("SELECT * FROM source_systems WHERE system_code = ? AND status = 'active'");
$stmt->execute([$systemCode]);
$system = $stmt->fetch();

if (!$system) {
    http_response_code(404);
    echo json_encode(['status' => 'error', 'message' => "Unknown or inactive system: {$systemCode}"]);
    exit;
}

if (!$apiKey || !hash_equals($system['api_key'], $apiKey)) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized - invalid API key']);
    exit;
}

// ---- Trigger targeted single-day sync for the requested type(s) ----
$typesToSync = ($type === 'all') ? SyncEngine::TYPES : [$type];
$results = [];

foreach ($typesToSync as $t) {
    $results[] = SyncEngine::syncOne($system, $t, $date, $date);
}

$stmt = $db->prepare("UPDATE source_systems SET last_synced_at = NOW() WHERE id = ?");
$stmt->execute([$system['id']]);

echo json_encode(['status' => 'success', 'date' => $date, 'results' => $results]);