<?php
declare(strict_types=1);
require_once __DIR__ . '/../helpers.php';
require_post();
$userId = as_int(get_post('user_id'));
$user = require_write_user($userId);
$saleId = as_int(get_post('sale_id'));
if ($saleId <= 0) {
    respond(['success' => false, 'message' => 'Sale ID is required.'], 400);
}
$conn = db();
$statusSelect = sales_status_select_sql('sales') . ' AS sale_status';
$notesSelect = table_has_column('sales', 'notes') ? ', notes' : '';
$statusReasonSelect = table_has_column('sales', 'status_reason') ? ', status_reason' : '';
$stmt = $conn->prepare("SELECT receipt_no, {$statusSelect}{$statusReasonSelect}{$notesSelect} FROM sales WHERE id = ? LIMIT 1");
$stmt->bind_param('i', $saleId);
$stmt->execute();
$sale = $stmt->get_result()->fetch_assoc();
if (!$sale) {
    respond(['success' => false, 'message' => 'Receipt not found.'], 404);
}
$statusPayload = sale_status_payload_from_row($sale);
if (($statusPayload['sale_status'] ?? 'active') !== 'active') {
    respond(['success' => false, 'message' => 'Only active receipts can be reprinted.'], 409);
}
log_activity($userId, 'REPRINT_RECEIPT', "Receipt {$sale['receipt_no']} reprinted by {$user['full_name']}");
respond(['success' => true, 'message' => 'Receipt reprint logged']);
