<?php
/** POST /api/reconcile/run — trigger reconciliation for a date */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
Kernel::handle(['auth' => 'admin', 'public' => false]);
require_once __DIR__ . '/../../engine/Logger.php';
require_once __DIR__ . '/../../engine/ReconciliationEngine.php';
require_once __DIR__ . '/../../engine/BankAdapter.php';

if ($_SERVER['REQUEST_METHOD']!=='POST'){http_response_code(405);die(json_encode(['error'=>'method_not_allowed']));}

// Admin only
// session managed by Kernel::handle
if (empty($_SESSION['admin'])){http_response_code(401);die(json_encode(['error'=>'unauthorized']));}

$data = json_decode(file_get_contents('php://input'),true) ?: [];
$date = trim($data['date'] ?? date('Y-m-d', strtotime('yesterday')));

$result = ReconciliationEngine::run($date);
http_response_code($result['passed'] ? 200 : 422);
echo json_encode($result, JSON_UNESCAPED_UNICODE);
