<?php
declare(strict_types=1);
require_once __DIR__ . '/../helpers.php';
require_post();
$adminUserId = as_int(get_post('admin_user_id'));
$admin = require_admin($adminUserId);
ensure_void_request_table();
$requestId = as_int(get_post('request_id'));
$action = strtolower(get_post('action'));
$adminNote = get_post('admin_note');
if ($requestId <= 0) {
    respond(['success' => false, 'message' => 'Request ID is required.'], 400);
}
if (!in_array($action, ['approve', 'reject'], true)) {
    respond(['success' => false, 'message' => 'Invalid action.'], 400);
}
$conn = db();
$conn->begin_transaction();
try {
    $requestStmt = $conn->prepare("SELECT vr.*, s.receipt_no, s.total_amount FROM sale_void_requests vr INNER JOIN sales s ON s.id = vr.sale_id WHERE vr.id = ? FOR UPDATE");
    $requestStmt->bind_param('i', $requestId);
    $requestStmt->execute();
    $request = $requestStmt->get_result()->fetch_assoc();
    if (!$request) {
        throw new Exception('Void request not found.');
    }
    if (($request['request_status'] ?? 'pending') !== 'pending') {
        throw new Exception('This void request was already processed.');
    }

    if ($action === 'reject') {
        $update = $conn->prepare("UPDATE sale_void_requests SET request_status = 'rejected', admin_note = ?, processed_by = ?, processed_at = NOW() WHERE id = ?");
        $update->bind_param('sii', $adminNote, $adminUserId, $requestId);
        $update->execute();
        $conn->commit();
        log_activity($adminUserId, 'VOID_REQUEST_REJECTED', "Admin {$admin['full_name']} rejected void request for receipt {$request['receipt_no']}");
        respond(['success' => true, 'message' => 'Void request rejected.']);
    }

    $saleId = (int)$request['sale_id'];
    $saleStmt = $conn->prepare('SELECT id, receipt_no, total_amount, notes, ' . sales_status_select_sql('sales') . ' AS sale_status' . (table_has_column('sales', 'status_reason') ? ', status_reason' : '') . ' FROM sales WHERE id = ? FOR UPDATE');
    $saleStmt->bind_param('i', $saleId);
    $saleStmt->execute();
    $sale = $saleStmt->get_result()->fetch_assoc();
    if (!$sale) {
        throw new Exception('Receipt not found.');
    }
    $statusPayload = sale_status_payload_from_row($sale);
    if (($statusPayload['sale_status'] ?? 'active') !== 'active') {
        throw new Exception('Only active purchases can be voided.');
    }

    $itemsStmt = $conn->prepare('SELECT item_id, quantity FROM sale_items WHERE sale_id = ? FOR UPDATE');
    $itemsStmt->bind_param('i', $saleId);
    $itemsStmt->execute();
    $itemsResult = $itemsStmt->get_result();
    $totalQty = 0;
    while ($row = $itemsResult->fetch_assoc()) {
        $itemId = (int)$row['item_id'];
        $qty = (int)$row['quantity'];
        $totalQty += $qty;
        $stockStmt = $conn->prepare('UPDATE items SET quantity = quantity + ?, updated_at = NOW() WHERE id = ?');
        $stockStmt->bind_param('ii', $qty, $itemId);
        $stockStmt->execute();
    }

    $reason = trim((string)$request['request_reason']);
    if ($adminNote !== '') {
        $reason .= ' | Admin note: ' . $adminNote;
    }

    if (table_has_column('sales', 'sale_status')) {
        $updateSale = $conn->prepare(build_sales_status_update_sql('voided'));
        bind_sales_status_update($updateSale, $reason, $adminUserId, $saleId);
        $updateSale->execute();
        if ($updateSale->affected_rows < 1) {
            throw new Exception('Purchase was not voided.');
        }
    } else {
        $statusNote = build_sale_status_note('voided', $reason, $sale['notes'] ?? null);
        $updateSale = $conn->prepare('UPDATE sales SET notes = ? WHERE id = ?');
        $updateSale->bind_param('si', $statusNote, $saleId);
        $updateSale->execute();
        if ($updateSale->affected_rows < 1) {
            throw new Exception('Purchase was not voided.');
        }
    }

    $updateReq = $conn->prepare("UPDATE sale_void_requests SET request_status = 'approved', admin_note = ?, processed_by = ?, processed_at = NOW() WHERE id = ?");
    $updateReq->bind_param('sii', $adminNote, $adminUserId, $requestId);
    $updateReq->execute();

    $conn->commit();
    $amount = number_format((float)$sale['total_amount'], 2, '.', '');
    log_activity($adminUserId, 'VOID_REQUEST_APPROVED', "Admin {$admin['full_name']} approved void request for receipt {$sale['receipt_no']} | reverted qty: {$totalQty} | reverted amount: {$amount}");
    respond(['success' => true, 'message' => 'Void request approved. Purchase voided successfully.']);
} catch (Throwable $e) {
    $conn->rollback();
    respond(['success' => false, 'message' => $e->getMessage()], 400);
}
