<?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');
$requestedVendor = (int)($_GET['vendor_id'] ?? $_POST['vendor_id'] ?? 0);
$vendorId = (int)(PosService::resolveVendorId($requestedVendor) ?? 0);
if ($vendorId < 1) Response::json(['ok'=>false,'message'=>'No approved vendor is assigned to this POS session.'], 403);

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $id = (int)($_GET['id'] ?? 0);
    if ($id) Response::json(['ok'=>true,'held'=>Database::fetchOne('SELECT * FROM pos_held_sales WHERE id=? AND vendor_id=? LIMIT 1', [$id,$vendorId])]);
    Response::json(['ok'=>true,'held'=>Database::fetchAll('SELECT * FROM pos_held_sales WHERE vendor_id=? AND status="held" ORDER BY id DESC LIMIT 100', [$vendorId])]);
}
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;
$action = (string)($input['action'] ?? 'hold');
$userId = (int)Auth::id();

if ($action === 'hold') {
    if (!PosService::can('pos.hold')) Response::json(['ok'=>false,'message'=>'No permission to hold sales.'], 403);
    $items = $input['items'] ?? [];
    if (!is_array($items) || !$items || count($items) > 200) Response::json(['ok'=>false,'message'=>'The held cart is empty or too large.'], 422);
    $registerId = (int)($input['register_id'] ?? 0);
    if ($registerId > 0 && !Database::safeFetchOne('SELECT id FROM pos_registers WHERE id=? AND vendor_id=? AND status="active" LIMIT 1', [$registerId,$vendorId])) {
        Response::json(['ok'=>false,'message'=>'The selected register does not belong to this vendor.'], 422);
    }
    $holdNo = 'HOLD-' . date('Ymd-His') . '-' . random_int(100,999);
    $cartJson = json_encode(array_slice($items,0,200), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    if ($cartJson === false || strlen($cartJson) > 1000000) Response::json(['ok'=>false,'message'=>'The held cart payload is too large.'], 422);
    Database::execute('INSERT INTO pos_held_sales (hold_no,vendor_id,register_id,shift_id,cashier_id,customer_name,cart_json,total_amount,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,? ,"held",NOW(),NOW())', [
        $holdNo,$vendorId,$registerId ?: null,(int)($input['shift_id'] ?? 0) ?: null,$userId,mb_substr((string)($input['customer_name'] ?? ''),0,150),$cartJson,max(0,round((float)($input['total_amount'] ?? 0),2))
    ]);
    Security::logActivity($userId, 'pos_sale_held', ['hold_no'=>$holdNo,'vendor_id'=>$vendorId]);
    Response::json(['ok'=>true,'hold_no'=>$holdNo,'id'=>Database::lastInsertId()]);
}
if ($action === 'delete') {
    if (!PosService::can('pos.hold')) Response::json(['ok'=>false,'message'=>'No permission to manage held sales.'], 403);
    $id = (int)($input['id'] ?? 0);
    Database::execute('UPDATE pos_held_sales SET status="deleted",updated_at=NOW() WHERE id=? AND vendor_id=?', [$id,$vendorId]);
    Security::logActivity($userId, 'pos_held_sale_deleted', ['id'=>$id,'vendor_id'=>$vendorId]);
    Response::json(['ok'=>true,'message'=>'Held sale deleted.']);
}
Response::json(['ok'=>false,'message'=>'Unsupported hold action.'], 422);
