<?php
require_once __DIR__ . '/../app/bootstrap.php';
use App\Core\Auth; use App\Core\PosService; use App\Core\Database; use App\Core\Response;
PosService::requireAccess('public/login.php');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') Response::json(['ok'=>false,'message'=>'POST required.'], 405);
if (!verify_csrf()) Response::json(['ok'=>false,'message'=>'Invalid security token.'], 419);
$input = json_decode(file_get_contents('php://input'), true) ?: [];
$uuid = (string)($input['uuid'] ?? ('sync-' . time()));
$exists = Database::fetchOne('SELECT id,status FROM pos_sync_queue WHERE client_uuid=? LIMIT 1', [$uuid]);
if ($exists && $exists['status'] === 'synced') Response::json(['ok'=>true,'message'=>'Already synced.']);
if (!$exists) Database::execute('INSERT INTO pos_sync_queue (client_uuid,user_id,payload_json,status,created_at) VALUES (?,?,?,"pending",NOW())', [$uuid,(int)Auth::id(),json_encode($input['payload'] ?? [])]);
$res = PosService::createSale($input['payload'] ?? []);
Database::execute('UPDATE pos_sync_queue SET status=?, response_json=?, synced_at=NOW() WHERE client_uuid=?', [$res['ok'] ? 'synced' : 'failed', json_encode($res), $uuid]);
Response::json($res, $res['ok'] ? 200 : 422);
