<?php

/*
'########:'##::::'##::'######::'##::::'##::'######:::'#######::'########::'########:
... ##..:: ##:::: ##:'##... ##: ##:::: ##:'##... ##:'##.... ##: ##.... ##: ##.....::
::: ##:::: ##:::: ##: ##:::..:: ##:::: ##: ##:::..:: ##:::: ##: ##:::: ##: ##:::::::
::: ##:::: ##:::: ##:. ######:: #########: ##::::::: ##:::: ##: ##:::: ##: ######:::
::: ##:::: ##:::: ##::..... ##: ##.... ##: ##::::::: ##:::: ##: ##:::: ##: ##...::::
::: ##:::: ##:::: ##:'##::: ##: ##:::: ##: ##::: ##: ##:::: ##: ##:::: ##: ##:::::::
::: ##::::. #######::. ######:: ##:::: ##:. ######::. #######:: ########:: ########:
:::..::::::.......::::......:::..:::::..:::......::::.......:::........:::........::                                                                                   
*/

declare(strict_types=1);

use App\helpers\ConfigManager;

// Set server timezone
// date_default_timezone_set("Africa/Lagos");

// Define constants for file system paths 
define('MAINROOT', dirname(dirname(dirname(__FILE__))));
define('APPROOT', dirname(dirname(__FILE__)));

// Define constants for URLs
define("URLROOT", "https://zoop.thewatchtower.ae");
define("URL_DOMAIN", "zoop.thewatchtower.ae");
define("ADMIN_ROOT", URLROOT . "/admin");
define("RESTAURANT_ROOT", URLROOT . "/restaurant");
define("RIDER_ROOT", URLROOT . "/rider");

// Load environment variables
$dotenv = Dotenv\Dotenv::createMutable(APPROOT . '/Config/');
$dotenv->load();

// Load required environment variables
$dotenv->required(['DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS', 'ENVIRONMENT']);

// Show PHP errors if in development environment
if ($_ENV['ENVIRONMENT'] === 'development' || $_ENV['ENVIRONMENT'] === 'dev') {
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
}

// Define constant for current page URL
define("CURLINK", (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");

// Define constants for date and time formats
define("DATENOW", date('Y-m-d H:i:s'));
define("TIMENOW", date('H:i:s'));
define("DATEFULL", date('D, M jS Y'));

// Define constant for spacer character
define("SPACER", " ");

define("CONFIG", [
    'title_helper' => ' | ',
    'backup' => false,
    'minify_html' => true,
    'maintenance' => false,
    'maintenance_time' => '30 Minutes',
    'backup_dir' => APPROOT . "/Backup/",
    'password_strength' => 2, // Weak
    'password_length' => 7, // 7 Characters
    'cookie_expire' => 60 * 60 * 24 * 30, // 30 days cookie stored
    'token_expire' => 25, // 25 minutes
    'login_attempt' => 4, // maximum attempts before locked out
    'next_attempt' => 10, // next login time after being locked out
]);

define("UPLOADS", [
    "upload_dir" => MAINROOT . "/upload",
    "upload" => URLROOT . "/upload",
    "public_dir" => MAINROOT . "/public/assets",
    "public" => URLROOT . "/assets",
    "restaurant_dish" => URLROOT . "/assets/restaurant-dish",
    "restaurant_banner" => URLROOT . "/assets/restaurant-banner",
    "restaurant_dish_dir" => MAINROOT . "/public/assets/restaurant-dish",
    "restaurant_banner_dir" => MAINROOT . "/public/assets/restaurant-banner",
    "customer_upload" => MAINROOT . "/upload/customer",
    "customer_dir" => URLROOT . "/upload/customer",
    "restaurant_upload" => MAINROOT . "/upload/restaurant",
    "restaurant_dir" => URLROOT . "/upload/restaurant",
    "rider_upload" => MAINROOT . "/upload/rider",
    "rider_dir" => URLROOT . "/upload/rider",
]);

define("QUEUE", [
    "track_open" => true,
    "track_url" => URLROOT . "/api/tracker/queue/open",
    "send_sequence" => 3,
]);

define("SESSION", [
    "customer" => "_zp_customer",
    "restaurant" => "_zp_restaurant",
    "rider" => "_zp_rider",
    "admin" => "_zp_admin",
]);


// Load config manager
$configManager = new ConfigManager(APPROOT . '/Config/setting.json');

define("APP", [
    'name' => $configManager->getSetting('app.name'),
    'tagline' => $configManager->getSetting('app.tagline'),
    'favicon' => $configManager->getSetting('app.favicon'),
    'logo-light' => $configManager->getSetting('app.logo_light'),
    'logo-dark' => $configManager->getSetting('app.logo_dark'),
    'logo-mini' => $configManager->getSetting('app.logo_mini'),
    'logo-meta' => $configManager->getSetting('app.logo_seo'),
    'phone' => $configManager->getSetting('app.telephone'),
    'mobile' => $configManager->getSetting('app.mobile'),
    'theme' => $configManager->getSetting('app.theme_color'),
    'address' => $configManager->getSetting('app.address'),
    'email' => $configManager->getSetting('app.email'),
    'support_team' => $configManager->getSetting('app.support_team'),
    'support_mail' => $configManager->getSetting('app.support_email'),
    'support_phone' => $configManager->getSetting('app.support_telephone'),
    'copyright' => $configManager->getSetting('app.copyright'),
]);

define("CURRENCY", [
    'name' => $configManager->getSetting('currency.name'),
    'symbol' => $configManager->getSetting('currency.symbol'),
    'code' => $configManager->getSetting('currency.code'),
]);

define("SOCIAL", [
    'facebook' => $configManager->getSetting('social.facebook'),
    'twitter' => $configManager->getSetting('social.twitter'),
    'youtube' => $configManager->getSetting('social.youtube'),
    'instagram' => $configManager->getSetting('social.instagram'),
    'linkedin' => $configManager->getSetting('social.linkedin'),
    'whatsapp' => $configManager->getSetting('social.whatsapp'),
    'telegram' => $configManager->getSetting('social.telegram'),
    'snapchat' => $configManager->getSetting('social.snapchat'),
    'tiktok' => $configManager->getSetting('social.tiktok'),
    'discord' => $configManager->getSetting('social.discord'),
    'vimeo' => $configManager->getSetting('social.vimeo'),
    'pinterest' => $configManager->getSetting('social.pinterest'),
    'reddit' => $configManager->getSetting('social.reddit'),
    'github' => $configManager->getSetting('social.github'),
    'discord' => $configManager->getSetting('social.discord'),
    'medium' => $configManager->getSetting('social.medium'),
]);

define("SMTP", [
    "host" => $_ENV['SMTP_HOST'],
    "port" => $_ENV['SMTP_PORT'],
    "username" => $_ENV['SMTP_USERNAME'],
    "password" => $_ENV['SMTP_PASSWORD'],
    "encryption" => $_ENV['SMTP_SECURE'],
    "auth" => $_ENV['SMTP_AUTH'],
    "name" => APP['name'],
    "email" => $_ENV['SMTP_EMAIL'],
]);

// Define constants for email templates
define("MAIL_TEXT", [
    "[web_name]" => $configManager->getSetting('app.name'),
    "[web_tagline]" => $configManager->getSetting('app.tagline'),
    "[web_year]" => date("Y"),
    "[web_url]" => URLROOT,
    "[web_logo]" => URLROOT . $configManager->getSetting('app.logo_dark'),
    "[web_theme]" => $configManager->getSetting('app.theme_dark'),
    "[web_address]" => $configManager->getSetting('app.address'),
    "[web_support_team]" => $configManager->getSetting('app.support_team'),
    "[web_support_mail]" => $configManager->getSetting('app.support_mail'),
    "[web_help_center]" => URLROOT . '/help',
    "[web_email]" => $configManager->getSetting('app.email'),
    "[web_phone]" => $configManager->getSetting('app.phone'),
    "[web_copyright]" => $configManager->getSetting('app.copyright'),
    "[social_directory]" => URLROOT . '/assets/images/social/',
    "[social_facebook]" => $configManager->getSetting('social.facebook'),
    "[social_twitter]" => $configManager->getSetting('social.twitter'),
    "[social_instagram]" => $configManager->getSetting('social.instagram'),
    "[social_linkedin]" => $configManager->getSetting('social.linkedin'),
    "[social_whatsapp]" => $configManager->getSetting('social.whatsapp'),
    "[social_telegram]" => $configManager->getSetting('social.telegram'),
    "[social_youtube]" => $configManager->getSetting('social.youtube'),
    "[social_pinterest]" => $configManager->getSetting('social.pinterest'),
    "[social_vimeo]" => $configManager->getSetting('social.vimeo'),
    "[social_tiktok]" => $configManager->getSetting('social.tiktok'),
    "[social_github]" => $configManager->getSetting('social.github'),
    "[social_discord]" => $configManager->getSetting('social.discord'),
    "[social_dribbble]" => $configManager->getSetting('social.dribbble'),
    "[social_snapchat]" => $configManager->getSetting('social.snapchat'),
    "[social_medium]" => $configManager->getSetting('social.medium'),
]);

define("GOOGLE_OAUTH", [
    "client_id" => $_ENV['GOOGLE_CLIENT_ID'],
    "client_secret" => $_ENV['GOOGLE_CLIENT_SECRET'],
]);

define("FACEBOOK_OAUTH", [
    "app_id" => $_ENV['FACEBOOK_APP_ID'],
    "secret" => $_ENV['FACEBOOK_SECRET'],
]);

function error_handler(int $type, string $msg, ?string $file = null, ?int $line = null)
{
    $error = json_encode(["type" => $type, "message" => $msg, "file" => $file, "line" => 'Found On Line ' . $line], JSON_PRETTY_PRINT);
    $data = <<<html
    <html>
        <head>
            <title>Error Page</title>
        </head>
        <body style="background-color: #f0f0f0; font-family: Arial, sans-serif;">
            <div style="max-width: 800px; margin: 0 auto; padding: 20px; text-align: center;">
                <h1 style="color: #ff0000; font-size: 48px;">Oops!</h1>
                <p style="color: #333333; font-size: 24px;">Something went wrong with your request.</p>
                <p style="color: #333333; font-size: 18px;">Please check the URL or try again later.</p>
                <div style="border: 1px solid #cccccc; background-color: #ffffff; padding: 10px; margin: 20px;">
                <p style="color: #333333; font-size: 16px;">PHP Error:</p>
                <p style="color: #ff0000; font-size: 14px;">{$error}</p>
                </div>
                <a href="/" style="color: #ffffff; background-color: #333333; padding: 10px 20px; text-decoration: none; font-size: 18px;">Go to Home Page</a>
            </div>
        </body>
    </html>
    html;

    echo $data;
    exit;
}

// Custom INI settings
ini_set('max_input_vars', '1000');
ini_set('memory_limit', '512M');
ini_set('max_execution_time', '600');
ini_set('upload_max_filesize', '250M');
ini_set('post_max_size', '250M');

// Enable error logging
ini_set('log_errors', 'On');
ini_set('error_log', APPROOT . '/Logs/system.log');
set_error_handler('error_handler', E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);

function minifyHTML(string $html): string
{
    $search = [
        '/\s+/', # Replace all whitespaces with a single space
        '/<!--.*?-->/', # Remove HTML comments
        '/\/\/.*?[\n\r]/', # Remove single line JavaScript comments
        '/\/\*.*?\*\//s' # Remove multi-line JavaScript comments
    ];

    $replace = [' ', '', '', ''];

    return preg_replace($search, $replace, $html);
}
