<?php
/**
 * Application Configuration
 * Dozar & Tripper Management System
 */

// Language must be processed BEFORE session start
// Check for language parameter first
$supported_languages = ['en', 'ne'];
$default_language = 'ne';

// Start session early to capture language preference
ini_set('session.cookie_httponly', 1);
ini_set('session.use_strict_mode', 1);
session_start();

// Get current language from session or default
if (!isset($_SESSION['language'])) {
    $_SESSION['language'] = $default_language;
}

// Set language from GET parameter
if (isset($_GET['lang']) && in_array($_GET['lang'], $supported_languages)) {
    $_SESSION['language'] = $_GET['lang'];
}

define('CURRENT_LANGUAGE', $_SESSION['language']);

// Load language file
$lang_file = __DIR__ . '/../lang/' . CURRENT_LANGUAGE . '.php';
if (file_exists($lang_file)) {
    $lang = require $lang_file;
} else {
    $lang = [];
}

// Language helper function
function t($key, $default = '') {
    global $lang;
    return $lang[$key] ?? $default;
}

// Load database connection
require_once __DIR__ . '/db.php';

// Load Nepali calendar
require_once __DIR__ . '/../includes/nepali_calendar.php';

define('APP_NAME', 'Dozar & Tripper');
define('APP_NAME_NEPALI', 'डोजर र ट्रिपर');
define('APP_VERSION', '1.0.0');

// Site URL
define('SITE_URL', 'https://dozertripper.com.dingoresult.com/dozartripper');

// Upload paths
define('UPLOAD_PATH', __DIR__ . '/../uploads/');
define('DOZAR_UPLOAD_PATH', UPLOAD_PATH . 'dozar/');
define('TRIPPER_UPLOAD_PATH', UPLOAD_PATH . 'tripper/');

// Time zone
date_default_timezone_set('Asia/Kathmandu');

// Error reporting (disable in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Helper function to sanitize input
function sanitize($input) {
    if (is_array($input)) {
        return array_map('sanitize', $input);
    }
    return htmlspecialchars(trim($input ?? ''), ENT_QUOTES, 'UTF-8');
}

// Helper function to get current user
function getCurrentUser() {
    if (isset($_SESSION['user_id'])) {
        return [
            'id' => $_SESSION['user_id'],
            'username' => $_SESSION['username'],
            'full_name' => $_SESSION['full_name'],
            'role' => $_SESSION['role'],
            'collector_access' => $_SESSION['collector_access'],
            'assigned_projects' => $_SESSION['assigned_projects'],
            'can_delete' => $_SESSION['can_delete'] ?? 0
        ];
    }
    return null;
}

// Helper function to check if user is logged in
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

// Helper function to check user role
function hasRole($role) {
    $user = getCurrentUser();
    if (!$user) return false;
    return $user['role'] === $role;
}

// Helper function to check collector access
function hasAccess($access) {
    $user = getCurrentUser();
    if (!$user) return false;
    if ($user['role'] === 'admin') return true;
    if ($user['role'] === 'collector') {
        return $user['collector_access'] === $access || $user['collector_access'] === 'all_modules';
    }
    return false;
}

// Helper function to redirect
function redirect($url) {
    header("Location: " . $url);
    exit;
}

// Helper function to show message
function showMessage($message, $type = 'info') {
    $_SESSION['message'] = $message;
    $_SESSION['message_type'] = $type;
}

// Helper function to display message
function displayMessage() {
    if (isset($_SESSION['message'])) {
        $class = $_SESSION['message_type'] ?? 'info';
        echo '<div class="alert alert-' . $class . '">' . $_SESSION['message'] . '</div>';
        unset($_SESSION['message'], $_SESSION['message_type']);
    }
}

// Format date for display
function formatDate($date) {
    if ($date) {
        // If Nepali language is selected, show Nepali date
        if (CURRENT_LANGUAGE === 'ne') {
            return date_to_nepali($date, 'full');
        }
        return date('Y-m-d', strtotime($date));
    }
    return '';
}

// Format datetime for display
function formatDateTime($datetime) {
    if ($datetime) {
        // If Nepali language is selected, show Nepali date
        if (CURRENT_LANGUAGE === 'ne') {
            $bs_date = date_to_nepali($datetime, 'full');
            return $bs_date . ' ' . date('H:i', strtotime($datetime));
        }
        return date('Y-m-d H:i:s', strtotime($datetime));
    }
    return '';
}

// Format time for display
function formatTime($time) {
    if ($time) {
        return date('H:i', strtotime($time));
    }
    return '';
}

// Get odometer unit label
function getOdometerUnit($module) {
    if ($module === 'dozar') {
        return t('unit_hours', 'Hours');
    } else {
        return t('unit_km', 'KM');
    }
}

// Language switcher URL
function getLanguageSwitchUrl($lang) {
    $params = $_GET;
    $params['lang'] = $lang;
    
    // Get current page path (including subdirectory)
    $currentPage = $_SERVER['PHP_SELF'];
    $scriptName = basename($currentPage);
    
    // Remove query string from current page if any
    if (($pos = strpos($scriptName, '?')) !== false) {
        $scriptName = substr($scriptName, 0, $pos);
    }
    
    // If it's index.php or root, just use the query string
    if ($scriptName === 'index.php' || $scriptName === '') {
        return '?' . http_build_query($params);
    }
    
    return $scriptName . '?' . http_build_query($params);
}

// Get current date in current language format
function getCurrentDateFormatted() {
    if (CURRENT_LANGUAGE === 'ne') {
        return current_nepali_date('full');
    }
    return date('Y-m-d');
}

