<?php
/**
 * Agentic Square - Core Configuration File
 * CodeCanyon Premium License Standard
 */

// Core Session Initialization
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Global Application Constants
define('APP_NAME', 'Agentic Square');

$appBasePath = '';
if (!empty($_SERVER['DOCUMENT_ROOT'])) {
    $documentRootPath = realpath($_SERVER['DOCUMENT_ROOT']);
    $applicationRootPath = realpath(__DIR__ . '/..');
    $documentRoot = $documentRootPath ? rtrim(str_replace('\\', '/', $documentRootPath), '/') : '';
    $applicationRoot = $applicationRootPath ? rtrim(str_replace('\\', '/', $applicationRootPath), '/') : '';

    if ($documentRoot && $applicationRoot && strpos($applicationRoot, $documentRoot) === 0) {
        $appBasePath = substr($applicationRoot, strlen($documentRoot));
        $appBasePath = '/' . trim(str_replace('\\', '/', $appBasePath), '/');
        $appBasePath = $appBasePath === '/' ? '' : $appBasePath;
    }
}

if ($appBasePath === '' && !empty($_SERVER['SCRIPT_NAME'])) {
    $scriptName = str_replace('\\', '/', $_SERVER['SCRIPT_NAME']);
    $appFolderName = basename(dirname(__DIR__));
    $appFolderPosition = strpos($scriptName, '/' . $appFolderName . '/');

    if ($appFolderPosition !== false) {
        $appBasePath = substr($scriptName, 0, $appFolderPosition + strlen('/' . $appFolderName));
    }
}

define('APP_BASE_PATH', $appBasePath);
$appScheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$appHost = $_SERVER['HTTP_HOST'] ?? '';
define('APP_URL', $appHost ? $appScheme . '://' . $appHost . APP_BASE_PATH : APP_BASE_PATH);

function app_url(string $path = ''): string
{
    $path = ltrim($path, '/');

    if ($path === '') {
        return APP_BASE_PATH === '' ? '/' : APP_BASE_PATH . '/';
    }

    return (APP_BASE_PATH === '' ? '' : APP_BASE_PATH) . '/' . $path;
}

function media_url(?string $path, string $fallback = ''): string
{
    $path = trim((string)$path);

    if ($path === '') {
        $path = $fallback;
    }

    if ($path === '') {
        return '';
    }

    if (preg_match('#^(https?:)?//#i', $path) || preg_match('#^[a-z][a-z0-9+.-]*:#i', $path)) {
        return $path;
    }

    return app_url($path);
}

function item_url(array $item): string
{
    return app_url('items/' . rawurlencode((string)$item['item_slug']) . '/' . (int)$item['id']);
}

function seller_url(array $seller): string
{
    return app_url('profile/' . rawurlencode((string)$seller['seller_slug']) . '/' . (int)$seller['user_id']);
}

function get_site_meta_title(): string
{
    global $pdo;

    static $siteMetaTitle = null;

    if ($siteMetaTitle !== null) {
        return $siteMetaTitle;
    }

    $siteMetaTitle = APP_NAME;

    if (!isset($pdo) || !$pdo instanceof PDO) {
        return $siteMetaTitle;
    }

    try {
        $stmt = $pdo->query("SELECT seo_meta_title, business_name FROM general_settings WHERE id = 1 LIMIT 1");
        $settings = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        $siteMetaTitle = trim((string)($settings['seo_meta_title'] ?? ''));

        if ($siteMetaTitle === '') {
            $siteMetaTitle = trim((string)($settings['business_name'] ?? ''));
        }
    } catch (Throwable $e) {
        try {
            $stmt = $pdo->query("SELECT business_name FROM general_settings WHERE id = 1 LIMIT 1");
            $settings = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
            $siteMetaTitle = trim((string)($settings['business_name'] ?? ''));
        } catch (Throwable $innerException) {
            $siteMetaTitle = APP_NAME;
        }
    }

    if ($siteMetaTitle === '') {
        $siteMetaTitle = APP_NAME;
    }

    return $siteMetaTitle;
}

function get_site_seo_meta_title(): string
{
    global $pdo;

    static $seoMetaTitle = null;

    if ($seoMetaTitle !== null) {
        return $seoMetaTitle;
    }

    $seoMetaTitle = '';

    if (!isset($pdo) || !$pdo instanceof PDO) {
        return $seoMetaTitle;
    }

    try {
        $stmt = $pdo->query("SELECT seo_meta_title FROM general_settings WHERE id = 1 LIMIT 1");
        $settings = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        $seoMetaTitle = trim((string)($settings['seo_meta_title'] ?? ''));
    } catch (Throwable $e) {
        $seoMetaTitle = '';
    }

    return $seoMetaTitle;
}

function get_site_identity(): array
{
    global $pdo;

    static $siteIdentity = null;

    if ($siteIdentity !== null) {
        return $siteIdentity;
    }

    $siteIdentity = [
        'business_name' => APP_NAME,
        'logo_path' => '',
        'logo_url' => '',
    ];

    if (!isset($pdo) || !$pdo instanceof PDO) {
        return $siteIdentity;
    }

    try {
        $stmt = $pdo->query("SELECT business_name, logo_path FROM general_settings WHERE id = 1 LIMIT 1");
        $settings = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        $businessName = trim((string)($settings['business_name'] ?? ''));
        $logoPath = trim((string)($settings['logo_path'] ?? ''));

        if ($businessName !== '') {
            $siteIdentity['business_name'] = $businessName;
        }

        if ($logoPath !== '') {
            $siteIdentity['logo_path'] = $logoPath;
            $siteIdentity['logo_url'] = media_url($logoPath);
        }
    } catch (Throwable $e) {
        $siteIdentity['business_name'] = APP_NAME;
    }

    return $siteIdentity;
}

function infer_page_title(): string
{
    $scriptName = basename((string)($_SERVER['SCRIPT_NAME'] ?? ''));

    if ($scriptName === '' || $scriptName === 'index.php') {
        return '';
    }

    return ucwords(str_replace(['-', '_', '.php'], [' ', ' ', ''], $scriptName));
}

function document_title(?string $pageTitle = null): string
{
    $siteIdentity = function_exists('get_site_identity') ? get_site_identity() : ['business_name' => APP_NAME];
    $businessName = trim((string)($siteIdentity['business_name'] ?? APP_NAME));
    $seoMetaTitle = get_site_seo_meta_title();
    $pageTitle = trim((string)($pageTitle ?? infer_page_title()));

    if ($businessName === '') {
        $businessName = APP_NAME;
    }

    if ($pageTitle === '') {
        if ($seoMetaTitle !== '' && strcasecmp($seoMetaTitle, $businessName) !== 0) {
            return $businessName . ' - ' . $seoMetaTitle;
        }

        return $businessName;
    }

    if (strcasecmp($pageTitle, $businessName) === 0) {
        return $businessName;
    }

    return $pageTitle . ' | ' . $businessName;
}

function get_gtm_container_id(): string
{
    global $pdo;

    static $gtmContainerId = null;

    if ($gtmContainerId !== null) {
        return $gtmContainerId;
    }

    $gtmContainerId = '';

    if (!isset($pdo) || !$pdo instanceof PDO) {
        return $gtmContainerId;
    }

    try {
        $stmt = $pdo->query("SELECT gtm_container_id FROM general_settings WHERE id = 1 LIMIT 1");
        $settings = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        $rawContainerId = strtoupper(trim((string)($settings['gtm_container_id'] ?? '')));

        if (preg_match('/^GTM-[A-Z0-9]+$/', $rawContainerId)) {
            $gtmContainerId = $rawContainerId;
        }
    } catch (Throwable $e) {
        $gtmContainerId = '';
    }

    return $gtmContainerId;
}

function get_site_currency(): string
{
    global $pdo;

    static $siteCurrency = null;

    if ($siteCurrency !== null) {
        return $siteCurrency;
    }

    $siteCurrency = 'USD';

    if (!isset($pdo) || !$pdo instanceof PDO) {
        return $siteCurrency;
    }

    try {
        $stmt = $pdo->query("SELECT currency FROM general_settings WHERE id = 1 LIMIT 1");
        $settings = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        $currency = strtoupper(trim((string)($settings['currency'] ?? 'USD')));

        if (preg_match('/^[A-Z]{3}$/', $currency)) {
            $siteCurrency = $currency;
        }
    } catch (Throwable $e) {
        $siteCurrency = 'USD';
    }

    return $siteCurrency;
}

function currency_symbol(?string $currency = null): string
{
    $currency = strtoupper(trim((string)($currency ?: get_site_currency())));
    $symbols = [
        'USD' => '$',
        'EUR' => '€',
        'GBP' => '£',
        'CAD' => 'C$',
        'AUD' => 'A$',
        'JPY' => '¥',
        'INR' => '₹',
        'SGD' => 'S$',
    ];

    return $symbols[$currency] ?? $currency . ' ';
}

function format_currency($amount, ?string $currency = null): string
{
    $currency = $currency ?: get_site_currency();

    return currency_symbol($currency) . number_format((float)$amount, 2);
}

function ensure_transaction_fee_schema(): void
{
    global $pdo;

    static $schemaChecked = false;

    if ($schemaChecked || !isset($pdo) || !$pdo instanceof PDO) {
        return;
    }

    $schemaChecked = true;

    try {
        $generalFeeColumn = $pdo->query("SHOW COLUMNS FROM general_settings LIKE 'transaction_fee_rate'")->fetch(PDO::FETCH_ASSOC);

        if (!$generalFeeColumn) {
            $pdo->exec("ALTER TABLE general_settings ADD COLUMN transaction_fee_rate DECIMAL(10,2) NULL DEFAULT 0.00 AFTER commission_rate");
        }

        $orderFeeRateColumn = $pdo->query("SHOW COLUMNS FROM orders LIKE 'transaction_fee_rate'")->fetch(PDO::FETCH_ASSOC);

        if (!$orderFeeRateColumn) {
            $pdo->exec("ALTER TABLE orders ADD COLUMN transaction_fee_rate DECIMAL(10,2) NULL DEFAULT 0.00 AFTER price");
        }

        $orderFeeAmountColumn = $pdo->query("SHOW COLUMNS FROM orders LIKE 'transaction_fee_amount'")->fetch(PDO::FETCH_ASSOC);

        if (!$orderFeeAmountColumn) {
            $pdo->exec("ALTER TABLE orders ADD COLUMN transaction_fee_amount DECIMAL(10,2) NULL DEFAULT 0.00 AFTER transaction_fee_rate");
        }

        $orderTotalColumn = $pdo->query("SHOW COLUMNS FROM orders LIKE 'total_amount'")->fetch(PDO::FETCH_ASSOC);

        if (!$orderTotalColumn) {
            $pdo->exec("ALTER TABLE orders ADD COLUMN total_amount DECIMAL(10,2) NULL DEFAULT 0.00 AFTER transaction_fee_amount");
        }
    } catch (Throwable $e) {
        // Schema migration is opportunistic here; calling pages can continue with safe fallbacks.
    }
}

function get_transaction_fee_rate(): float
{
    global $pdo;

    ensure_transaction_fee_schema();

    if (!isset($pdo) || !$pdo instanceof PDO) {
        return 0.00;
    }

    try {
        $stmt = $pdo->query("SELECT transaction_fee_rate FROM general_settings WHERE id = 1 LIMIT 1");
        $settings = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        return max(0.00, (float)($settings['transaction_fee_rate'] ?? 0.00));
    } catch (Throwable $e) {
        return 0.00;
    }
}

// Database Configuration Parameters
define('DB_HOST', 'localhost');
define('DB_USER', 'atooreew_db');
define('DB_PASS', 'c!86AfB4K4Y8@.=D');
define('DB_NAME', 'atooreew_marketplace_db');

// Error Reporting Environment Switch (Toggle to false in production deployment)
$development_mode = true;
if ($development_mode) {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
} else {
    error_reporting(0);
    ini_set('display_errors', 0);
}

// =========================================================================
// 1. SECURE NATIVE DATABASE ESTABLISHMENT HOOK (MySQLi Driver Backend Layer)
// =========================================================================
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

// Verify successful connection parameters to prevent silent fallback failure drops
if (!$conn) {
    die("Critical System Error: MySQLi Database Connection Layer Collapsed. Reason: " . mysqli_connect_error());
}

// =========================================================================
// 2. MODERN PDO EMBEDDED ENGINE INTERFACES (PDO Driver Frontend Layout Layer)
// =========================================================================
try {
    $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
    $options = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ];
    $pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
} catch (\PDOException $e) {
    die("Critical System Error: PDO Database Connection Layer Collapsed. Reason: " . $e->getMessage());
}
