<?php
session_start();
require_once __DIR__ . '/database.php';

// Base URL and paths (for links and assets)
$scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
$baseUrl = rtrim(dirname($scriptName), '/\\');
if (strpos($baseUrl, '\\') !== false) $baseUrl = str_replace('\\', '/', $baseUrl);
define('BASE_URL', $baseUrl === '/' ? '' : $baseUrl);
define('SITE_URL', 'http://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . BASE_URL);
define('BASE_PATH', dirname(__DIR__));
define('UPLOAD_PATH', BASE_PATH . '/uploads/');
define('UPLOAD_URL', 'uploads/');

// Ensure upload directories exist
$upload_dirs = ['uploads', 'uploads/products', 'uploads/gallery', 'uploads/videos', 'uploads/home', 'uploads/clients', 'uploads/site', 'uploads/pages', 'uploads/about', 'uploads/tech_quality', 'uploads/feedback'];
foreach ($upload_dirs as $dir) {
    $full = BASE_PATH . '/' . $dir;
    if (!is_dir($full)) {
        @mkdir($full, 0755, true);
    }
}

function getSetting($key, $default = '') {
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT setting_value FROM site_settings WHERE setting_key = ?");
    $stmt->execute([$key]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row ? $row['setting_value'] : $default;
}

function getMenuItems() {
    $pdo = getDB();
    $stmt = $pdo->query("SELECT label, url FROM menu_items WHERE is_active = 1 ORDER BY sort_order");
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function currentPage($url) {
    $script = basename($_SERVER['SCRIPT_NAME'] ?? '');
    // Strict basename match only. strpos($url, $script) breaks: video-gallery.php contains gallery.php
    $url = preg_replace('/\?.*$/', '', trim($url));
    $menuScript = basename($url);
    return ($script === $menuScript);
}
