<?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' || !verify_csrf()) Response::json(['ok'=>false,'message'=>'Invalid request.'], 419);
$input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
$vendorId = (int)(PosService::resolveVendorId((int)($input['vendor_id'] ?? 0)) ?? 0);
if ($vendorId < 1) Response::json(['ok'=>false,'message'=>'No approved vendor is assigned to this POS session.'],403);
$registerId = (int)($input['register_id'] ?? 0);
if ($registerId > 0 && !Database::safeFetchOne('SELECT id FROM pos_registers WHERE id=? AND vendor_id=? LIMIT 1',[$registerId,$vendorId])) Response::json(['ok'=>false,'message'=>'Invalid POS register.'],422);
$productId = (int)($input['matched_product_id'] ?? 0);
if ($productId > 0 && !Database::safeFetchOne('SELECT id FROM products WHERE id=? AND vendor_id=? LIMIT 1',[$productId,$vendorId])) $productId = 0;
$scanValue = mb_substr(trim((string)($input['scan_value'] ?? '')),0,190);
if ($scanValue === '') Response::json(['ok'=>false,'message'=>'Scan value is required.'],422);
Database::execute('INSERT INTO pos_scanner_events (vendor_id,register_id,cashier_id,scan_value,scan_type,matched_product_id,status,created_at) VALUES (?,?,?,?,?,?,?,NOW())', [$vendorId,$registerId ?: null,(int)Auth::id(),$scanValue,mb_substr((string)($input['scan_type'] ?? 'hardware'),0,40),$productId ?: null,mb_substr((string)($input['status'] ?? 'matched'),0,30)]);
Response::json(['ok'=>true,'message'=>'Scan logged.']);
