<?php
require_once __DIR__ . '/../app/bootstrap.php';
use App\Core\Auth; use App\Core\PosService; use App\Core\Database; use App\Core\Response; use App\Core\Security;
PosService::requireAccess('public/login.php');
$vendorId = (int)(PosService::resolveVendorId((int)($_GET['vendor_id'] ?? $_POST['vendor_id'] ?? 0)) ?? 0);
if ($vendorId < 1) Response::json(['ok'=>false,'message'=>'No approved vendor is assigned to this POS session.'],403);
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    Response::json(['ok'=>true,'settings'=>Database::fetchAll('SELECT setting_key,setting_value,setting_group FROM pos_settings WHERE vendor_id=? OR vendor_id IS NULL ORDER BY setting_group,setting_key', [$vendorId]),'registers'=>PosService::registers($vendorId)]);
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !verify_csrf()) Response::json(['ok'=>false,'message'=>'Invalid request.'], 419);
if (!PosService::can('pos.settings')) Response::json(['ok'=>false,'message'=>'No POS settings permission.'], 403);
$allowedKeys = ['pos_enabled','default_payment_methods','allow_offline_queue','receipt_auto_print','barcode_camera_enabled','low_stock_warning'];
$changes = 0;
foreach ($_POST as $key=>$value) {
    if (in_array($key, ['csrf_token','vendor_id'], true) || !in_array($key,$allowedKeys,true)) continue;
    $value = mb_substr(is_array($value) ? implode(',',array_map('strval',$value)) : (string)$value,0,1000);
    Database::execute('INSERT INTO pos_settings (vendor_id,setting_key,setting_value,setting_group,updated_at) VALUES (?,?,?,?,NOW()) ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value),updated_at=NOW()', [$vendorId,$key,$value,'general']);
    $changes++;
}
Security::logActivity(Auth::id(),'pos_settings_updated',['vendor_id'=>$vendorId,'changes'=>$changes]);
Response::json(['ok'=>true,'message'=>'POS settings saved.']);
