<?php
/**
 * Verify Proforma QR payload (ZATCA Phase-1 TLV Base64)
 * GET/POST: payload=BASE64  OR  id=INVOICE_ID (rebuilds & validates)
 */
require_once __DIR__ . '/config.php';
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

function zatca_tlv_byte($tag, $value) {
    $value = (string)$value;
    if (strlen($value) > 255) $value = substr($value, 0, 255);
    return chr((int)$tag) . chr(strlen($value)) . $value;
}
function proforma_qr_payload($sellerName, $vatNo, $timestamp, $totalWithVat, $vatTotal) {
    $tlv = zatca_tlv_byte(1, $sellerName)
         . zatca_tlv_byte(2, $vatNo)
         . zatca_tlv_byte(3, $timestamp)
         . zatca_tlv_byte(4, number_format((float)$totalWithVat, 2, '.', ''))
         . zatca_tlv_byte(5, number_format((float)$vatTotal, 2, '.', ''));
    return base64_encode($tlv);
}
function validate_proforma_qr($base64, $expected = null) {
    $result = ['valid' => false, 'errors' => [], 'fields' => []];
    $base64 = trim((string)$base64);
    if ($base64 === '') { $result['errors'][] = 'Empty QR payload'; return $result; }
    $bin = base64_decode($base64, true);
    if ($bin === false || $bin === '') { $result['errors'][] = 'Invalid Base64 encoding'; return $result; }
    $len = strlen($bin); $pos = 0; $fields = [];
    while ($pos + 2 <= $len) {
        $tag = ord($bin[$pos]); $tlen = ord($bin[$pos + 1]); $pos += 2;
        if ($pos + $tlen > $len) { $result['errors'][] = "Truncated TLV for tag $tag"; return $result; }
        $fields[$tag] = substr($bin, $pos, $tlen); $pos += $tlen;
    }
    if ($pos !== $len) $result['errors'][] = 'Trailing bytes after TLV';
    foreach ([1,2,3,4,5] as $req) {
        if (!isset($fields[$req]) || $fields[$req] === '') $result['errors'][] = "Missing required tag $req";
    }
    if (isset($fields[2]) && !preg_match('/^[0-9]{10,15}$/', $fields[2])) $result['errors'][] = 'VAT number format invalid (tag 2)';
    if (isset($fields[3]) && strtotime($fields[3]) === false) $result['errors'][] = 'Timestamp format invalid (tag 3)';
    if (isset($fields[4]) && !is_numeric($fields[4])) $result['errors'][] = 'Invoice total must be numeric (tag 4)';
    if (isset($fields[5]) && !is_numeric($fields[5])) $result['errors'][] = 'VAT amount must be numeric (tag 5)';
    if (is_array($expected) && empty($result['errors'])) {
        if (isset($expected['seller_vat']) && isset($fields[2]) && $fields[2] !== $expected['seller_vat'])
            $result['errors'][] = 'VAT number does not match invoice';
        if (isset($expected['grand_total']) && isset($fields[4]) && abs((float)$fields[4] - (float)$expected['grand_total']) > 0.009)
            $result['errors'][] = 'Grand total does not match invoice';
        if (isset($expected['vat_amount']) && isset($fields[5]) && abs((float)$fields[5] - (float)$expected['vat_amount']) > 0.009)
            $result['errors'][] = 'VAT amount does not match invoice';
    }
    $result['fields'] = [
        'seller_name' => $fields[1] ?? null,
        'seller_vat'  => $fields[2] ?? null,
        'timestamp'   => $fields[3] ?? null,
        'grand_total' => $fields[4] ?? null,
        'vat_amount'  => $fields[5] ?? null,
    ];
    $result['valid'] = empty($result['errors']);
    return $result;
}

$payload = $_GET['payload'] ?? $_POST['payload'] ?? '';
$id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
$out = ['ok' => false];

try {
    if ($id > 0) {
        $pdo = new PDO(
            'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4',
            DB_USER, DB_PASS,
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
        );
        $stmt = $pdo->prepare("SELECT * FROM proforma_invoices WHERE id = ?");
        $stmt->execute([$id]);
        $inv = $stmt->fetch();
        if (!$inv) {
            echo json_encode(['ok' => false, 'error' => 'Invoice not found']); exit;
        }
        $items = $pdo->prepare("SELECT amount FROM proforma_items WHERE invoice_id = ?");
        $items->execute([$id]);
        $sub = 0.0;
        foreach ($items->fetchAll() as $r) $sub += (float)$r['amount'];
        $vatRate = (float)($inv['vat_rate'] ?? 15);
        $vatAmt = round($sub * $vatRate / 100, 2);
        $grand = round($sub + $vatAmt, 2);
        $sellerName = $inv['seller_name'] ?: 'IYAADTEC SOLUTIONS LLC';
        $sellerVat = preg_replace('/\s+/', '', $inv['seller_vat'] ?: '313104808500003');
        $ts = date('c', strtotime(($inv['invoice_date'] ?: date('Y-m-d')) . ' 12:00:00'));
        $payload = proforma_qr_payload($sellerName, $sellerVat, $ts, $grand, $vatAmt);
        $check = validate_proforma_qr($payload, [
            'seller_vat' => $sellerVat,
            'grand_total' => $grand,
            'vat_amount' => $vatAmt,
        ]);
        echo json_encode([
            'ok' => true,
            'invoice_id' => $id,
            'invoice_no' => $inv['invoice_no'],
            'payload' => $payload,
            'validation' => $check,
        ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        exit;
    }

    if ($payload === '') {
        echo json_encode(['ok' => false, 'error' => 'Provide payload= or id=']); exit;
    }
    $check = validate_proforma_qr($payload);
    echo json_encode([
        'ok' => true,
        'validation' => $check,
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
