<?php
/**
 * Trigger ESO Sync — Calls the Mac Studio sync listener via ngrok tunnel.
 * The listener runs the Snowflake Python script locally on the Mac Studio.
 */
require_once __DIR__ . '/../config/auth.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['error' => 'POST only'], 405);
}

$user = requireLogin();
requireRole('captain');
validateCsrf();

$date = $_POST['date'] ?? date('Y-m-d', strtotime('-1 day'));

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
    jsonResponse(['error' => 'Invalid date format'], 400);
}

// Call Mac Studio sync listener via ngrok
$syncUrl = env('SYNC_LISTENER_URL', 'https://unslung-idiosyncratically-cinderella.ngrok-free.dev');
$syncSecret = 'cfd-snowflake-sync-2026';

$ch = curl_init($syncUrl);
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => json_encode(['date' => $date]),
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'X-Sync-Secret: ' . $syncSecret,
        'ngrok-skip-browser-warning: true',
    ],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 15,
    CURLOPT_SSL_VERIFYPEER => false,
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

if ($error) {
    jsonResponse(['error' => 'Cannot reach Mac Studio: ' . $error, 'hint' => 'Is the sync listener running?'], 502);
}

$result = json_decode($response, true);
if (!$result) {
    jsonResponse(['error' => 'Invalid response from sync listener', 'raw' => substr($response, 0, 200)], 502);
}

if (isset($result['error'])) {
    jsonResponse($result, 400);
}

auditLog('eso_sync_triggered', $user['id'], "Date: $date via ngrok");
setSetting('eso_last_sync', date('c'));
setSetting('eso_last_sync_date', $date);

jsonResponse($result);
