<?php
declare(strict_types=1);
require_once __DIR__ . '/../helpers.php';
require_post();
$userId = as_int(get_post('user_id'));
$user = require_write_user($userId);
if (is_admin_role($user)) {
    respond(['success' => false, 'message' => 'Admin can void purchases directly.'], 403);
}
ensure_void_request_table();
$saleId = as_int(get_post('sale_id'));
$reason = get_post('reason');
if ($saleId <= 0) {
    respond(['success' => false, 'message' => 'Sale ID is required.'], 400);
}
if ($reason === '') {
    respond(['success' => false, 'message' => 'Reason is required.'], 400);
}
$conn = db();
$saleStmt = $conn->prepare('SELECT id, receipt_no, total_amount, ' . sales_status_select_sql('sales') . ' AS sale_status FROM sales WHERE id = ? LIMIT 1');
$saleStmt->bind_param('i', $saleId);
$saleStmt->execute();
$sale = $saleStmt->get_result()->fetch_assoc();
if (!$sale) {
    respond(['success' => false, 'message' => 'Receipt not found.'], 404);
}
if (strtolower((string)($sale['sale_status'] ?? 'active')) !== 'active') {
    respond(['success' => false, 'message' => 'Only active receipts can be requested for void.'], 400);
}
$pendingStmt = $conn->prepare("SELECT id FROM sale_void_requests WHERE sale_id = ? AND request_status = 'pending' LIMIT 1");
$pendingStmt->bind_param('i', $saleId);
$pendingStmt->execute();
if ($pendingStmt->get_result()->fetch_assoc()) {
    respond(['success' => false, 'message' => 'A pending void request already exists for this receipt.'], 409);
}
$insert = $conn->prepare("INSERT INTO sale_void_requests (sale_id, requested_by, request_reason, request_status, created_at) VALUES (?, ?, ?, 'pending', NOW())");
$insert->bind_param('iis', $saleId, $userId, $reason);
if (!$insert->execute()) {
    respond(['success' => false, 'message' => 'Unable to create void request.'], 500);
}
log_activity($userId, 'VOID_REQUEST', "{$user['full_name']} requested void for receipt {$sale['receipt_no']} | reason: {$reason}");
respond(['success' => true, 'message' => 'Void request sent to admin.']);
