<?php
// /api/sync.php
require_once __DIR__ . '/middleware.php';
require_once __DIR__ . '/../_Core/Helpers.php';

$input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
header('Content-Type: application/json');

$user = api_authenticate_or_die(); // any sync action must be authenticated

$path = $input['path'] ?? '';
$method = strtoupper($input['method'] ?? 'POST');
$body = $input['body'] ?? [];

if (!$path) { echo json_encode(['status'=>0,'error'=>'missing_path']); exit; }

// Only allow internal endpoints under /api/ (basic safety)
if (strpos($path, '/api/') !== 0 && strpos($path, 'api/') !== 0) {
    echo json_encode(['status'=>0,'error'=>'invalid_sync_path']); exit;
}

// Normalize path to local script path
$local = $_SERVER['DOCUMENT_ROOT'] . '/' . ltrim($path, '/');

// If local file exists, include and simulate a request by setting php://input temporarily
if (!file_exists($local)) {
    echo json_encode(['status'=>0,'error'=>'sync_target_not_found','path'=>$local]); exit;
}

// For safety, only allow POST/PUT/DELETE (no GET)
if (!in_array($method, ['POST','PUT','DELETE'])) {
    echo json_encode(['status'=>0,'error'=>'invalid_method']); exit;
}

// A simple exec: include the file and buffer output (the included API should read php://input JSON as usual)
$backup_input = fopen('php://temp','r+');
fwrite($backup_input, json_encode($body));
rewind($backup_input);

// Temporarily swap php://input by using a stream wrapper is non-trivial in PHP without extensions.
// Instead, we will call the controller directly if it exists for known routes (common ones)
$response = ['status'=>0, 'error'=>'sync_not_implemented_for_path'];
// Fallback simple handling for known patterns:
if (strpos($path, '/api/followups.php') !== false) {
    // call followups controller
    require_once __DIR__ . '/../Controllers/FollowupController.php';
    $c = new Controllers\FollowupController();
    // map body.action to controller method
    $act = $body['action'] ?? 'create';
    if ($act === 'create') $response = $c->create($body, $user);
    elseif ($act === 'update') $response = $c->update($body['id'] ?? null, $body, $user);
}
elseif (strpos($path, '/api/customers.php') !== false) {
    require_once __DIR__ . '/../Controllers/CustomerController.php';
    $c = new Controllers\CustomerController();
    $act = $body['action'] ?? 'create';
    if ($act === 'create') $response = $c->create($body, $user);
}
// Add more handlers if needed

echo json_encode($response);
?>