beginTransaction(); // 1. Fetch Invoice & Company $stmt = $db->prepare(" SELECT i.*, c.name as company_name, c.tax_identification_number as company_tin, c.address as company_address, c.jofotara_client_id_encrypted, c.jofotara_secret_key_encrypted FROM invoices i JOIN companies c ON i.company_id = c.id WHERE i.id = ? FOR UPDATE "); $stmt->execute([$id]); $invoice = $stmt->fetch(); if (!$invoice) json_error('Invoice not found', 404); if ($invoice['status'] === 'approved') json_error('Already approved', 400); // 2. Fetch Line Items $stmtLines = $db->prepare("SELECT * FROM invoice_lines WHERE invoice_id = ?"); $stmtLines->execute([$id]); $invoice['items'] = $stmtLines->fetchAll(); // 3. Decrypt Company Keys for JoFotara $clientId = \App\Core\Encryption::decrypt($invoice['jofotara_client_id_encrypted']); $secretKey = \App\Core\Encryption::decrypt($invoice['jofotara_secret_key_encrypted']); if (!$clientId || !$secretKey) { throw new \Exception("JoFotara credentials missing for company: " . $invoice['company_name']); } // Decrypt Buyer Info $invoice['buyer_name'] = \App\Core\Encryption::decrypt($invoice['buyer_name']) ?: ''; $invoice['buyer_tin'] = \App\Core\Encryption::decrypt($invoice['buyer_tin']) ?: ''; // 4. Initialize JoFotara Service $jofotara = new JoFotara(); // 5. Generate UBL 2.1 XML $companyData = [ 'name' => $invoice['company_name'], 'tax_identification_number' => $invoice['company_tin'], 'address' => $invoice['company_address'] ]; $xmlContent = $jofotara->generateXML($invoice, $companyData); // 6. Submit to JoFotara API $apiResponse = $jofotara->submitInvoice($xmlContent, $clientId, $secretKey); // 7. Record Submission (Audit Log) $submissionId = \App\Core\Database::generateUuid(); $stmtSub = $db->prepare(" INSERT INTO jofotara_submissions (id, invoice_id, company_id, tenant_id, xml_payload, xml_hash, jofotara_uuid, qr_code_raw, response_code, response_body, status, submitted_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW()) "); $status = $apiResponse['success'] ? 'accepted' : 'rejected'; $stmtSub->execute([ $submissionId, $id, $invoice['company_id'], $invoice['tenant_id'], $xmlContent, hash('sha256', $xmlContent), $apiResponse['uuid'] ?? null, $apiResponse['qrCode'] ?? null, $apiResponse['_http_code'] ?? '0', json_encode($apiResponse['raw'] ?? []), $status ]); if (!$apiResponse['success']) { throw new \Exception("JoFotara Rejection: " . ($apiResponse['error'] ?? 'Unknown Error')); } // 8. Update Invoice $updateStmt = $db->prepare(" UPDATE invoices SET status = 'approved', jofotara_uuid = ?, qr_code = ?, updated_at = NOW() WHERE id = ? "); $updateStmt->execute([$apiResponse['uuid'], $apiResponse['qrCode'], $id]); $db->commit(); json_success([ 'message' => 'Approved and submitted to JoFotara.', 'uuid' => $apiResponse['uuid'], 'qr_code' => $apiResponse['qrCode'] ]); } catch (\Exception $e) { $db->rollBack(); error_log("JoFotara Approve Error: " . $e->getMessage()); json_error('Failed to approve invoice: ' . $e->getMessage(), 500); }