<?php

/**
 * String functions
 */
function allowedChars($str, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-')
{
	return preg_match('/^[' . $chars . ']+$/', $str);
}

function sanitizeFilename($filename, $allowedExtensions = [])
{
	// Rozdelenie názvu a prípony
	$pathInfo = pathinfo($filename);
	$name = $pathInfo['filename'] ?? 'file';
	$extension = strtolower($pathInfo['extension'] ?? '');
	// Odstránenie nebezpečných znakov z názvu
	$name = preg_replace('/[^a-zA-Z0-9_-]/', '_', $name);
	$name = substr($name, 0, 100); // voliteľné obmedzenie dĺžky
	// Validácia prípony, ak je zoznam povolený
	if (
		$allowedExtensions
		&& count($allowedExtensions) > 0
		&& !in_array($extension, $allowedExtensions)
	) {
		$extension = 'bin'; // fallback ak prípona nie je povolená
	}
	return $name . '.' . $extension;
}

/**
 * Check database
 */
function dbCheck()
{
	global $db;
	$db_version = option('version');
	if ($db_version === null) {
		$db->create('options', [
			'key' => [
				'VARCHAR(64)',
				'NOT NULL',
				'UNIQUE'
			],
			'value' => [
				'TEXT',
				'NOT NULL'
			],
			'created_at' => [
				'DATETIME',
				'DEFAULT CURRENT_TIMESTAMP'
			]
		]);
		option('version', '0');
		$db_version = '0';
	}
	if ($db_version === '0') {
		$db->create('reports', [
			'report_id' => [
				'INTEGER',
				'PRIMARY KEY',
				'AUTOINCREMENT'
			],
			'report_title' => [
				'VARCHAR(255)',
				'DEFAULT NULL'
			],
			'report_description' => [
				'TEXT',
				'DEFAULT NULL'
			],
			'report_status' => [
				'INTEGER',
				'DEFAULT 0'
			],
			'report_group' => [
				'VARCHAR(255)',
				'DEFAULT NULL'
			],
			'report_priority' => [
				'INTEGER',
				'DEFAULT 0'
			],
			'created_dt' => [
				'DATETIME',
				'DEFAULT NULL'
			],
		]);
		option('version', '1');
		$db_version = '1';
	}
	if ($db_version === '1') {
		$db->create('attachments', [
			'attachment_id' => [
				'INTEGER',
				'PRIMARY KEY',
				'AUTOINCREMENT'
			],
			'report_id' => [
				'INTEGER',
				'NOT NULL'
			],
			'attachment_type' => [
				'VARCHAR(255)',
				'DEFAULT NULL'
			],
			'attachment_content' => [
				'TEXT',
				'DEFAULT NULL'
			],
			'created_dt' => [
				'DATETIME',
				'DEFAULT NULL'
			],
			'updated_dt' => [
				'DATETIME',
				'DEFAULT NULL'
			],
		]);
		option('version', '2');
		$db_version = '2';
	}
	if ($db_version === '2') {
		$db->query("ALTER TABLE reports ADD COLUMN ordnum INTEGER DEFAULT 0");
		option('version', '3');
		$db_version = '3';
	}
}

function option($key, $value = null)
{
	global $db;
	if (tableExits('options') === null) {
		return null;
	}
	if ($value === null) {
		return $db->get('options', 'value', [
			'key' => $key
		]);
	}
	$exits = $db->get('options', 'value', [
		'key' => $key
	]);
	if ($exits !== null) {
		return $db->update('options', [
			'value' => $value
		], [
			'key' => $key
		]);
	}
	return $db->insert('options', [
		'key' => $key,
		'value' => $value
	]);
}

function tableExits($table)
{
	global $db;
	return $db->get('sqlite_master', 'name', [
		'type' => 'table',
		'name' => $table
	]);
}

/**
 * Reports
 */
function reportAdd($title, $description, $status = 0, $group = null, $priority = 0)
{
	global $db;
	$status = intval($status);
	$priority = intval($priority);
	$db->insert('reports', [
		'report_title' => $title,
		'report_description' => $description,
		'report_status' => $status,
		'report_group' => $group,
		'report_priority' => $priority,
		'created_dt' => date('Y-m-d H:i:s')
	]);
	return $db->id();
}

function reportUpdate($report_id, $report_data)
{
	global $db;
	$stm = $db->update('reports', $report_data, [
		'report_id' => $report_id
	]);
	return ($stm->rowCount() > 0);
}

function reportUpdateStatus($report_id, $status)
{
	global $db;
	$stm = $db->update('reports', [
		'report_status' => $status
	], [
		'report_id' => $report_id
	]);
	return ($stm->rowCount() > 0);
}

function reportUpdateOrdnum($ordnums)
{
	global $db;
	$ordnums = json_decode($ordnums, true);
	$suc = true;
	foreach ($ordnums as $report_id => $ordnum) {
		$stm = $db->update('reports', [
			'ordnum' => $ordnum
		], [
			'report_id' => $report_id
		]);
		$suc &= ($stm->rowCount() > 0);
	}
	return $suc;
}

function reportDelete($report_id)
{
	global $db;
	$stm = $db->delete('reports', [
		'report_id' => $report_id
	]);
	return ($stm->rowCount() > 0);
}

function reportGet($report_id)
{
	global $db;
	return $db->get('reports', '*', [
		'report_id' => $report_id
	]);
}

function reportGetAll($status = null)
{
	global $db;
	if ($status === null) $status = array(0, 1, 2, 3);
	return $db->select('reports', '*', [
		'ORDER' => ['report_priority' => 'DESC', 'ordnum' => 'ASC'],
		'report_status' => $status
	]);
}

function reportGetAllGrouped($status = null)
{
	$all = reportGetAll($status);
	$groups = [];
	foreach ($all as $report) {
		$groups[$report['report_status']][] = $report;
	}
	return $groups;
}

/**
 * Attachments
 */
function attachmentGet($attachment_id)
{
	global $db;
	return $db->get('attachments', '*', [
		'attachment_id' => $attachment_id
	]);
}
function attachmentAdd($report_id, $attachment_type, $attachment_content)
{
	global $db;
	if ($attachment_type == 'file') {
		$data = json_decode($attachment_content, true);
		if (!is_array($data)) return false;
		$base64 = preg_replace('/^data:.*?;base64,/', '', $data['base64']);
		$base64_data = base64_decode($base64);
		$filename = 'report_' . $report_id . '_' . time() . '_' . sanitizeFilename($data['filename']);
		file_put_contents(UPLOAD_DIR_ATTACHMENTS . $filename, $base64_data);
		$attachment_content = $filename;
	}

	$stm = $db->insert('attachments', [
		'report_id' => $report_id,
		'attachment_type' => $attachment_type,
		'attachment_content' => $attachment_content,
		'created_dt' => date('Y-m-d H:i:s')
	]);
	return ($stm->rowCount() > 0);
}

function attachmentUpdate($attachment_id, $attachment_content)
{
	global $db;
	if (strlen(trim($attachment_content)) <= 0) return attachmentDelete($attachment_id);
	$stm = $db->update('attachments', [
		'attachment_content' => $attachment_content,
		'updated_dt' => date('Y-m-d H:i:s')
	], [
		'attachment_id' => $attachment_id
	]);
	return ($stm->rowCount() > 0);
}

function attachmentDelete($attachment_id)
{
	global $db;
	$attachment = attachmentGet($attachment_id);
	if ($attachment['attachment_type'] == 'file'
		&& file_exists(UPLOAD_DIR_ATTACHMENTS . $attachment['attachment_content']))
	{
		unlink(UPLOAD_DIR_ATTACHMENTS . $attachment['attachment_content']);
	}
	$stm = $db->delete('attachments', [
		'attachment_id' => $attachment_id
	]);
	return ($stm->rowCount() > 0);
}

function attachmentGetAll($report_id)
{
	global $db;
	$all = $db->select('attachments', '*', [
		'ORDER' => ['created_dt' => 'ASC'],
		'report_id' => $report_id
	]);
	if (is_array($all)) foreach ($all as $key => $row) {
		if ($all[$key]['attachment_type'] == 'file') {
			$all[$key]['attachment_content'] = UPLOAD_URL_ATTACHMENTS . $all[$key]['attachment_content'];
		}
	}
	return $all;
}
