<?php
namespace platyFramework;

class ptyAppErrorModel
{
    var $tableName = "t_platy_error_logs";

    public function __construct()
    {
        $this->_checkTableExistsAndCreate();
    }

    function _checkTableExistsAndCreate()
    {
        GLOBAL $platyFramework;
        $this->db = $platyFramework->db;

        if (!$this->db->sql_result("SHOW TABLES LIKE '$this->tableName'")) {
            $this->db->sql_query("
			CREATE TABLE IF NOT EXISTS `{$this->tableName}` (
			`id` int(11) NOT NULL AUTO_INCREMENT,
            `regDateTime` datetime NULL,
            `ip` varchar(64) COLLATE utf8mb4_unicode_ci NULL,
            `userAgent` varchar(128) COLLATE utf8mb4_unicode_ci NULL,
            `errorType` varchar(32) COLLATE utf8mb4_unicode_ci NULL,
            `errorMessage` longtext COLLATE utf8mb4_unicode_ci NULL,
            `errorFileName` varchar(128) COLLATE utf8mb4_unicode_ci NULL,
            `errorLine` varchar(32) COLLATE utf8mb4_unicode_ci NULL,
            
			PRIMARY KEY (`id`)
			) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci AUTO_INCREMENT=1;
		");
        }

        if (!$this->db->sql_result("SHOW COLUMNS FROM `{$this->tableName}` LIKE 'requestUrl'")) {
            $this->db->sql_query("ALTER TABLE `{$this->tableName}` ADD `requestUrl` longtext null;");
        }
    }

    public function insert($num, $str, $file, $line)
    {
        $fullUrl = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

        $str = ptyCutLength($str, 2000);
        GLOBAL $platyFramework;
        $n = $platyFramework->db->query("INSERT INTO {$this->tableName} (regDateTime, ip, userAgent, errorType, errorMessage, errorFileName, errorLine, requestUrl) VALUES
      (NOW(), '{$_SERVER['REMOTE_ADDR']}', '{$_SERVER['HTTP_USER_AGENT']}',
      '" . addslashes($num) . "', 
      '" . addslashes($str) . "', 
      '" . addslashes($file) . "', 
      '" . addslashes($line) . "',
      '" . addslashes(ptyCutLength($fullUrl, 65000)) . "'
      )");

        if ($n)
            echo "error reported.<br>";
        else
            echo "error cannot reported.<br>";

    }
}

?>
