<?php


//$url = "https://sandbox.zatca.gov.sa/e-invoicing/simplified-invoice/reporting";
$url = 'https://gw-fatoora.zatca.gov.sa/e-invoicing/developer-portal/invoices/reporting/single';



$data = [

    /* =========================
     * SELLER / COMPANY
     * ========================= */
    "company" => [
        "seller_name"       => "Maximum Speed Tech Supply LTD",
        "seller_name_ar"    => "شركة توريد التكنولوجيا بأقصى سرعة المحدودة",
        "vat_number"        => "399999999900003",
        "cr_number"         => "1010010000",
        "street"            => "Prince Sultan",
        "city"              => "Riyadh",
        "postal_code"       => "23333",
        "country"           => "SA"
    ],

    /* =========================
     * INVOICE HEADER
     * ========================= */
    "invoice" => [
        "invoice_number"    => "SME00010",
        "uuid"              => "8e6000cf-1a98-4174-b3e7-b5d5954bc10d",
        "invoice_type"      => "SIMPLIFIED",          // ZATCA 388
        "issue_date"        => "2025-06-02",
        "issue_time"        => "17:41:08",
        "currency"          => "SAR",
        "icv"               => 10,
        "previous_hash"     => "NWZlY2ViNjZmZmM4NmYzOGQ5NTI3ODZjNmQ2OTZjNzljMmRiYzIzOWRkNGU5MWI0NjcyOWQ3M2EyN2ZiNTdlOQ==",
        "payment_method"    => "CASH"                 // PaymentMeansCode = 10
    ],

    /* =========================
     * BUYER (B2C – OPTIONAL)
     * ========================= */
    "customer" => [
        "name"              => "Fatoora Samples LTD",
        "vat_number"        => "399999999800003",
        "street"            => "Salah Al-Din",
        "city"              => "Riyadh",
        "postal_code"       => "12222",
        "country"           => "SA"
    ],

    /* =========================
     * ITEMS
     * ========================= */
    "items" => [
        [
            "item_code"      => "ITEM001",
            "description"    => "كتاب",
            "quantity"       => 33,
            "unit"           => "PCE",
            "unit_price"     => 3.00,
            "vat_rate"       => 15,
            "vat_category"   => "S"
        ],
        [
            "item_code"      => "ITEM002",
            "description"    => "قلم",
            "quantity"       => 3,
            "unit"           => "PCE",
            "unit_price"     => 34.00,
            "vat_rate"       => 15,
            "vat_category"   => "S"
        ]
    ],

    /* =========================
     * TOTALS (CALCULATED)
     * ========================= */
    "totals" => [
        "total_exclusive_vat" => 201.00,
        "total_vat"           => 30.15,
        "total_inclusive_vat" => 231.15,
        "payable_amount"      => 231.15
    ]
];



/* =========================
 * NAMESPACES
 * ========================= */
define('INV_NS', 'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2');
define('CBC_NS', 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2');
define('CAC_NS', 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2');

/* =========================
 * CREATE XML
 * ========================= */
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;

/* Root Invoice */
$invoice = $dom->createElementNS(INV_NS, 'Invoice');
$invoice->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:cbc', CBC_NS);
$invoice->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:cac', CAC_NS);
$dom->appendChild($invoice);

/* =========================
 * INVOICE HEADER
 * ========================= */
$invoice->appendChild(
    $dom->createElementNS(CBC_NS, 'cbc:ID', $data['invoice']['invoice_number'])
);

$invoice->appendChild(
    $dom->createElementNS(CBC_NS, 'cbc:IssueDate', $data['invoice']['issue_date'])
);

$invoice->appendChild(
    $dom->createElementNS(CBC_NS, 'cbc:IssueTime', $data['invoice']['issue_time'])
);

$invoice->appendChild(
    $dom->createElementNS(CBC_NS, 'cbc:DocumentCurrencyCode', $data['invoice']['currency'])
);

/* =========================
 * SUPPLIER (SELLER)
 * ========================= */
$supplier = $dom->createElementNS(CAC_NS, 'cac:AccountingSupplierParty');
$party = $dom->createElementNS(CAC_NS, 'cac:Party');

$partyName = $dom->createElementNS(CAC_NS, 'cac:PartyName');
$partyName->appendChild(
    $dom->createElementNS(CBC_NS, 'cbc:Name', $data['company']['seller_name'])
);

$party->appendChild($partyName);

$taxScheme = $dom->createElementNS(CAC_NS, 'cac:PartyTaxScheme');
$taxScheme->appendChild(
    $dom->createElementNS(CBC_NS, 'cbc:CompanyID', $data['company']['vat_number'])
);

$party->appendChild($taxScheme);
$supplier->appendChild($party);
$invoice->appendChild($supplier);

/* =========================
 * INVOICE LINES
 * ========================= */
$lineId = 1;

foreach ($data['items'] as $item) {
    $line = $dom->createElementNS(CAC_NS, 'cac:InvoiceLine');

    $line->appendChild(
        $dom->createElementNS(CBC_NS, 'cbc:ID', $lineId++)
    );

    $line->appendChild(
        $dom->createElementNS(CBC_NS, 'cbc:InvoicedQuantity', $item['quantity'])
    );

    $line->appendChild(
        $dom->createElementNS(CBC_NS, 'cbc:LineExtensionAmount',
            number_format($item['quantity'] * $item['unit_price'], 2, '.', '')
        )
    );

    $itemNode = $dom->createElementNS(CAC_NS, 'cac:Item');
    $itemNode->appendChild(
        $dom->createElementNS(CBC_NS, 'cbc:Name', $item['description'])
    );

    $price = $dom->createElementNS(CAC_NS, 'cac:Price');
    $price->appendChild(
        $dom->createElementNS(CBC_NS, 'cbc:PriceAmount', number_format($item['unit_price'], 2, '.', ''))
    );

    $line->appendChild($itemNode);
    $line->appendChild($price);

    $invoice->appendChild($line);
}

/* =========================
 * TOTALS
 * ========================= */
$monetaryTotal = $dom->createElementNS(CAC_NS, 'cac:LegalMonetaryTotal');

$monetaryTotal->appendChild(
    $dom->createElementNS(CBC_NS, 'cbc:TaxExclusiveAmount', $data['totals']['total_exclusive_vat'])
);

$monetaryTotal->appendChild(
    $dom->createElementNS(CBC_NS, 'cbc:TaxInclusiveAmount', $data['totals']['payable_amount'])
);

$monetaryTotal->appendChild(
    $dom->createElementNS(CBC_NS, 'cbc:PayableAmount', $data['totals']['payable_amount'])
);

$invoice->appendChild($monetaryTotal);


/* =========================
 * FINAL XML
 * ========================= */
$xml = $dom->saveXML();

/* =========================
 * HASH + BASE64
 * ========================= */
$invoiceHash = base64_encode(hash('sha256', $xml, true));
$invoiceBase64 = base64_encode($xml);
$uuid   = $data['invoice']['uuid'];   // Invoice UUID
$csid   = 'YOUR_ZATCA_CSID';           // From ZATCA
$secret = 'YOUR_ZATCA_CLIENT_SECRET';  // From ZATCA


// $signedXml = $xml; 
 $ch = curl_init($url);
// $invoiceHash = base64_encode(hash('sha256', $signedXml, true));
// $invoiceBase64 = base64_encode($signedXml);

$payload = [
    "invoiceHash" => $invoiceHash,
    "uuid"        => $uuid,
    "invoice"     => $invoiceBase64
];


$headers = [
    "Content-Type: application/json",
    "Accept-Version: V2",
    "Authorization: Basic " . base64_encode($csid . ":" . $secret)
];

/* Only for STANDARD (B2B) invoices */
// if (!$isSimplified) {
//     $headers[] = "Clearance-Status: 1";
// }

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_HTTPHEADER     => $headers,
    CURLOPT_POSTFIELDS     => json_encode($payload, JSON_UNESCAPED_SLASHES),
    CURLOPT_CONNECTTIMEOUT => 30,
    CURLOPT_TIMEOUT        => 60,
    CURLOPT_SSL_VERIFYPEER => true,
]);

$response = curl_exec($ch);

if ($response === false) {
    echo "cURL Error: " . curl_error($ch);
} else {
    echo $response;
}

curl_close($ch);
file_put_contents('debug_payload.json', json_encode($payload, JSON_PRETTY_PRINT));




