<?php
session_start();

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/SystemSettings.php';
require_once __DIR__ . '/../../includes/payment_options.php';

if (!isset($_SESSION['user_id']) || !isset($_SESSION['username']) || !isset($_SESSION['role'])) {
    header('Location: /IMS/login.php');
    exit();
}

$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);

if (
    !$auth->isSalesAssistant($_SESSION['user_id']) &&
    !$auth->isBranchManager($_SESSION['user_id']) &&
    !$auth->isWarehousePersonnel($_SESSION['user_id']) &&
    ($_SESSION['role'] ?? '') !== 'super_admin'
) {
    die("Access denied.");
}

$branchId = $auth->getUserBranch($_SESSION['user_id']);
if (!$branchId) {
    die("Error: You are not assigned to any branch.");
}

$transactionId = trim($_GET['transaction_id'] ?? '');
if ($transactionId === '') {
    header('Location: create_sale.php');
    exit();
}

$stmt = $conn->prepare("
    SELECT
        si.sale_id,
        si.transaction_id,
        si.branch_id,
        si.unique_code,
        si.unit_price,
        si.total_price,
        si.sold_at,
        si.customer_name,
        si.customer_phone,
        si.customer_id,
        si.vat_relief,
        si.buyer_tin,
        si.eis_transaction_type,
        si.buyer_authorization_code,
        si.vat5_certificate_number,
        si.vat5_certificate_details,
        si.payment_method,
        si.original_unit_price,
        si.discount_amount,
        i.item_name,
        i.item_details
    FROM sold_items si
    LEFT JOIN items i ON si.item_id = i.item_id
    WHERE si.transaction_id = :transaction_id
      AND si.branch_id = :branch_id
    ORDER BY si.sale_id ASC
");
$stmt->execute([
    ':transaction_id' => $transactionId,
    ':branch_id'      => (int)$branchId,
]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($rows)) {
    $_SESSION['pos_flash_error'] = 'Receipt not found or you do not have access to this transaction.';
    header('Location: create_sale.php');
    exit();
}

$first       = $rows[0];
$uniqueCodes = array_column($rows, 'unique_code');
$itemNames   = array_map(static fn($r) => trim((string)($r['item_name'] ?? $r['unique_code'])), $rows);
$itemDetails = array_map(static fn($r) => trim((string)($r['item_details'] ?? '')), $rows);
$prices      = array_map(static fn($r) => round((float)$r['total_price'], 2), $rows);
$discounts   = array_map(static fn($r) => round((float)($r['discount_amount'] ?? 0), 2), $rows);

$total         = round(array_sum($prices), 2);
$totalDiscount = round(array_sum($discounts), 2);
$originalTotal = round($total + $totalDiscount, 2);
$vatRelief     = (bool)(int)($first['vat_relief'] ?? 0);
$paymentMethod = $first['payment_method'] ?? 'cash';
$saleDate      = $first['sold_at'];
$eisTransType  = strtoupper(trim((string)($first['eis_transaction_type'] ?? 'B2C')));
if (!in_array($eisTransType, ['B2C', 'B2B'], true)) {
    $eisTransType = 'B2C';
}

$systemSettings = new SystemSettings();
$vatRate        = $systemSettings->vatRate();

$noVat    = $vatRelief;
$subtotal = $noVat ? $total : round($total / (1 + $vatRate), 2);
$vatAmt   = $noVat ? 0.0 : round($total - $subtotal, 2);

// Fetch EIS outbox record for this transaction
$eisData = [];
try {
    $outboxStmt = $conn->prepare("
        SELECT status, validation_url, payload_json, local_audit_json
        FROM mra_eis_outbox
        WHERE entity_type = 'sale'
          AND source_key  = :txn
          AND branch_id   = :branch_id
        ORDER BY id DESC
        LIMIT 1
    ");
    $outboxStmt->execute([
        ':txn'       => $transactionId,
        ':branch_id' => (int)$branchId,
    ]);
    $eisData = $outboxStmt->fetch(PDO::FETCH_ASSOC) ?: [];
} catch (Throwable $e) {
    error_log('view_sale_receipt: EIS fetch failed: ' . $e->getMessage());
}

$saleData = [
    'transaction_id'           => $transactionId,
    'sale_date'                => $saleDate,
    'sale_time'                => (new DateTimeImmutable($saleDate))->format('H:i:s'),
    'quantity'                 => count($rows),
    'unique_codes'             => $uniqueCodes,
    'item_names'               => $itemNames,
    'item_details'             => $itemDetails,
    'prices'                   => $prices,
    'original_total'           => $originalTotal,
    'subtotal'                 => $subtotal,
    'include_vat'              => !$vatRelief,
    'vat_relief'               => $vatRelief,
    'buyer_tin'                => $first['buyer_tin'],
    'eis_transaction_type'     => $eisTransType,
    'buyer_authorization_code' => $first['buyer_authorization_code'],
    'vat5_certificate_number'  => $first['vat5_certificate_number'],
    'vat5_project_number'      => !empty($first['vat5_certificate_details'])
        ? (json_decode((string)$first['vat5_certificate_details'], true)['projectNumber'] ?? null)
        : null,
    'is_vat_registered'        => null,
    'vat_amount'               => $vatAmt,
    'total'                    => $total,
    'amount_paid'              => $total,
    'payment_method'           => $paymentMethod,
    'payment_method_label'     => paymentMethodLabel($paymentMethod),
    'change_due'               => 0,
    'discount'                 => $totalDiscount,
    'discount_percentage'      => $originalTotal > 0 ? round(($totalDiscount / $originalTotal) * 100, 1) : 0,
    'discount_type'            => $totalDiscount > 0 ? 'fixed' : 'none',
    'discount_value'           => $totalDiscount,
    'sale_mode'                => 'cash',
    'credit_balance'           => 0,
    'customer_id'              => $first['customer_id'],
    'customer_name'            => $first['customer_name'],
    'customer_phone'           => $first['customer_phone'],
];

if (!empty($eisData)) {
    $outboxPayload = json_decode((string)($eisData['payload_json'] ?? ''), true);
    $outboxAudit   = json_decode((string)($eisData['local_audit_json'] ?? ''), true);

    if (is_array($outboxAudit) && array_key_exists('is_vat_registered', $outboxAudit)) {
        $saleData['is_vat_registered'] = $outboxAudit['is_vat_registered'];
    }

    $offlineSig = trim((string)(is_array($outboxPayload) ? ($outboxPayload['invoiceSummary']['offlineSignature'] ?? '') : ''));
    if ($offlineSig !== '' && strtolower((string)($eisData['status'] ?? '')) !== 'submitted') {
        $saleData['eis_status']          = 'offline';
        $saleData['eis_offline_qr_data'] = is_array($outboxAudit) ? ($outboxAudit['offline_receipt_data'] ?? null) : null;
        $saleData['eis_message']         = 'Signed offline B2C invoice queued for MRA EIS submission.';
    } else {
        $saleData['eis_status']  = $eisData['status'] ?? null;
        $saleData['eis_message'] = '';
    }

    $saleData['eis_validation_url'] = $eisData['validation_url'] ?? null;
    $saleData['eis_acknowledged']   = strtolower((string)($eisData['status'] ?? '')) === 'submitted'
        && filter_var($eisData['validation_url'] ?? '', FILTER_VALIDATE_URL) !== false;
}

$_SESSION['sale_data'] = $saleData;
header('Location: sale_receipt.php?view=1');
exit();
