<?php

declare(strict_types=1);

$config = require __DIR__ . '/../config/config.php';

date_default_timezone_set($config['app']['timezone'] ?? 'UTC');

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../src/autoload.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/settings_helper.php';

if (!function_exists('str_starts_with')) {
    function str_starts_with(string $haystack, string $needle): bool
    {
        if ($needle == '') {
            return true;
        }

        return strncmp($haystack, $needle, strlen($needle)) === 0;
    }
}

function e(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

function format_date(string $date, ?string $format = null): string
{
    if ($date === '' || $date === '0000-00-00') {
        return '';
    }
    
    if ($format === null) {
        $format = Settings::get('date_format', 'Y-m-d');
    }
    
    $timestamp = strtotime($date);
    if ($timestamp === false) {
        return $date;
    }
    
    return date($format, $timestamp);
}

function format_time(string $time, ?string $format = null): string
{
    if ($time === '' || $time === '00:00:00') {
        return '';
    }
    
    if ($format === null) {
        $format = Settings::get('time_format', 'H:i');
    }
    
    $timestamp = strtotime($time);
    if ($timestamp === false) {
        return $time;
    }
    
    return date($format, $timestamp);
}

function format_datetime(string $datetime, ?string $dateFormat = null, ?string $timeFormat = null): string
{
    if ($datetime === '' || $datetime === '0000-00-00 00:00:00') {
        return '';
    }
    
    if ($dateFormat === null) {
        $dateFormat = Settings::get('date_format', 'Y-m-d');
    }
    if ($timeFormat === null) {
        $timeFormat = Settings::get('time_format', 'H:i');
    }
    
    $timestamp = strtotime($datetime);
    if ($timestamp === false) {
        return $datetime;
    }
    
    return date($dateFormat . ' ' . $timeFormat, $timestamp);
}
