<?php
/**
 * printnode_print.php
 * Put this file in the SAME folder as planner.php:
 *   /rooms/modules/payments/printnode_print.php
 *
 * Used by planner.php for PrintNode raw ESC/POS thermal printing.
 */

/*
   CONFIGURE THIS:
   Put your PrintNode API key here.
   PrintNode Dashboard -> API Keys

   IMPORTANT:
   Do not leave the placeholder value below.
*/
if (!defined('PRINTNODE_API_KEY')) {
    define('PRINTNODE_API_KEY', 'eGbNOVIA7Ig8mRO1vq-SfUZ40tuQIWPTBXMi_iIKP68');
}

/**
 * Send raw ESC/POS bytes to a PrintNode printer.
 *
 * @param int    $printerId PrintNode printer ID, e.g. 75588290
 * @param string $rawBytes  ESC/POS bytes
 * @param string $title     Job title shown in PrintNode
 * @return array            ['ok'=>bool, 'job_id'=>mixed|null, 'error'=>string|null, 'response'=>mixed]
 */
function printnode_send_raw(int $printerId, string $rawBytes, string $title = 'Restaurant Print Job'): array
{
    if ($printerId <= 0) {
        return [
            'ok' => false,
            'job_id' => null,
            'error' => 'Invalid PrintNode printer ID.',
            'response' => null,
        ];
    }

    /*
       FIX:
       Only reject blank or placeholder API keys.
       Do NOT compare against your real API key, otherwise the system will
       always say "PrintNode API key is not configured".
    */
    $apiKey = trim((string)PRINTNODE_API_KEY);

    if ($apiKey === '' || $apiKey === 'PASTE_YOUR_PRINTNODE_API_KEY_HERE' || $apiKey === 'PUT_YOUR_PRINTNODE_API_KEY_HERE') {
        return [
            'ok' => false,
            'job_id' => null,
            'error' => 'PrintNode API key is not configured in printnode_print.php.',
            'response' => null,
        ];
    }

    if ($rawBytes === '') {
        return [
            'ok' => false,
            'job_id' => null,
            'error' => 'Empty print payload.',
            'response' => null,
        ];
    }

    if (!function_exists('curl_init')) {
        return [
            'ok' => false,
            'job_id' => null,
            'error' => 'PHP cURL extension is not enabled on this server.',
            'response' => null,
        ];
    }

    $payload = [
        'printerId'   => $printerId,
        'title'       => $title !== '' ? $title : 'Restaurant Print Job',
        'contentType' => 'raw_base64',
        'content'     => base64_encode($rawBytes),
        'source'      => 'Pure Africa Restaurant Planner',
    ];

    $ch = curl_init('https://api.printnode.com/printjobs');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_HTTPAUTH       => CURLAUTH_BASIC,
        CURLOPT_USERPWD        => $apiKey . ':',
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
        ],
        CURLOPT_POSTFIELDS     => json_encode($payload),
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_CONNECTTIMEOUT => 10,
    ]);

    $body = curl_exec($ch);
    $curlError = curl_error($ch);
    $httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($body === false) {
        return [
            'ok' => false,
            'job_id' => null,
            'error' => 'PrintNode cURL error: ' . $curlError,
            'response' => null,
        ];
    }

    $decoded = json_decode($body, true);

    if ($httpCode >= 200 && $httpCode < 300) {
        return [
            'ok' => true,
            'job_id' => is_array($decoded) ? ($decoded['id'] ?? $decoded) : $body,
            'error' => null,
            'response' => $decoded ?: $body,
        ];
    }

    $err = 'PrintNode HTTP ' . $httpCode;
    if (is_array($decoded)) {
        if (isset($decoded['message'])) {
            $err .= ': ' . $decoded['message'];
        } elseif (isset($decoded['error'])) {
            $err .= ': ' . $decoded['error'];
        } else {
            $err .= ': ' . json_encode($decoded);
        }
    } else {
        $err .= ': ' . $body;
    }

    return [
        'ok' => false,
        'job_id' => null,
        'error' => $err,
        'response' => $decoded ?: $body,
    ];
}

/**
 * Optional plain-text helper for simple tests.
 */
function printnode_send_text(int $printerId, string $text, string $title = 'Restaurant Text Print'): array
{
    $bytes = "\x1B\x40";      // init
    $bytes .= $text;
    $bytes .= "\n\n\n\n";
    $bytes .= "\x1D\x56\x42\x00"; // cut

    return printnode_send_raw($printerId, $bytes, $title);
}
?>