<?php

require_once DOL_DOCUMENT_ROOT.'/custom/ntak/class/ntaklog.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';

class NtakLogger
{
    public const LOG_FILE_PREFIX = '_ntak';
    
    private static ?NtakLogger $instance = null;
    private User $user;
    public DoliDb $db;

    /**
     * 
     */
    public function __construct()
    {
        global $db;

        $this->db = $db;

        $this->user = new User($this->db);
        $this->user->fetch(1);
    }
    /**
     * 
     */
    public static function getInstance(): NtakLogger
    {
        if (self::$instance === null) {
            self::$instance = new NtakLogger;
        }

        return self::$instance;
    }
    /**
     * 
     */
    public function logIntoFile(string $msg, int $level): void
    {
        dol_syslog($msg, $level, 0, self::LOG_FILE_PREFIX);
    }
    /**
     * 
     */
    public function logIntoDb(int $invoiceId, int $status, string $errorMsg = null, string $data, string $ntakId = null): void
    {
        $log = new NtakLog($this->db);
        $log->ref = bin2hex(random_bytes(20));
        $log->status = $status;
        $log->error_msg = $errorMsg;
        $log->sent_data = $data;
        $log->fk_facture = $invoiceId;
        $log->ntak_id = $ntakId;
        if ($log->create($this->user) < 1) {
            $this->logIntoFile('Cannot save NTAK log data into DB', LOG_ALERT);
        }
    }
    /**
     * 
     */
    public function massDbLogByInvoiceRef(array $refs, int $status, string $errorMsg = null, string $data, string $ntakId = null): void
    {
        foreach ($refs as $ref) {
            $invoice = new Facture($this->db);
            if ($invoice->fetch(0, $ref) > 0) {
                $this->logIntoDb($invoice->id, $status, $errorMsg, $data, $ntakId);
            }            
        }
    }
    /**
     * 
     */
    public function getOrigSentData(string $ntakId): array
    {
        $data = [];

        $sql = "
            SELECT sent_data FROM public.llx_ntak_ntaklog
            WHERE ntak_id ILIKE '{$ntakId}'
            ORDER BY rowid ASC
            LIMIT 1
        ";

        $rows = $this->db->query($sql);
        if ($rows) {
            while ($row = $this->db->fetch_row($rows)) {
                $data = json_decode(reset($row), true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    unset($data['feldolgozasAzonositok']);
                } else {
                    $data = [];
                }
            }
        }

        return $data;
    }
}