<?php
/**
 * Timezone Helper Functions
 * Handles all timezone-related operations for ITR POS System
 */

/**
 * Get the configured timezone from settings
 * @return string Timezone identifier (e.g., 'Asia/Karachi')
 */
function getConfiguredTimezone() {
    global $conn;
    
    // Try to get from settings first
    $sql = "SELECT s.value, s.default_value 
            FROM settings s 
            JOIN setting_categories sc ON s.category_id = sc.id 
            WHERE sc.code = 'system_settings' AND s.code = 'system_timezone' 
            AND s.is_active = 1";
    
    $result = mysqli_query($conn, $sql);
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $timezone = $row['value'] ?: $row['default_value'];
        
        // Validate timezone
        if (in_array($timezone, DateTimeZone::listIdentifiers())) {
            return $timezone;
        }
    }
    
    // Fallback to default
    return 'Asia/Karachi';
}

/**
 * Set the system timezone based on configuration
 * @return bool Success status
 */
function setSystemTimezone() {
    $timezone = getConfiguredTimezone();
    
    try {
        date_default_timezone_set($timezone);
        return true;
    } catch (Exception $e) {
        error_log("Timezone setting failed: " . $e->getMessage());
        return false;
    }
}

/**
 * Get current date/time in configured timezone
 * @param string $format Date format (default: 'Y-m-d H:i:s')
 * @return string Formatted date/time
 */
function getCurrentDateTime($format = 'Y-m-d H:i:s') {
    $timezone = getConfiguredTimezone();
    $date = new DateTime('now', new DateTimeZone($timezone));
    return $date->format($format);
}

/**
 * Get current date in configured timezone
 * @param string $format Date format (default: 'Y-m-d')
 * @return string Formatted date
 */
function getCurrentDate($format = 'Y-m-d') {
    return getCurrentDateTime($format);
}

/**
 * Convert date/time to configured timezone
 * @param string $datetime Date/time string
 * @param string $fromTimezone Source timezone (default: UTC)
 * @param string $format Output format (default: 'Y-m-d H:i:s')
 * @return string Converted date/time
 */
function convertToSystemTimezone($datetime, $fromTimezone = 'UTC', $format = 'Y-m-d H:i:s') {
    try {
        $date = new DateTime($datetime, new DateTimeZone($fromTimezone));
        $date->setTimezone(new DateTimeZone(getConfiguredTimezone()));
        return $date->format($format);
    } catch (Exception $e) {
        error_log("Date conversion failed: " . $e->getMessage());
        return $datetime; // Return original if conversion fails
    }
}

/**
 * Get timezone options for settings
 * @return array Array of timezone options
 */
function getTimezoneOptions() {
    return [
        ['label' => 'Pakistan (Karachi)', 'value' => 'Asia/Karachi'],
        ['label' => 'Pakistan (Lahore)', 'value' => 'Asia/Karachi'],
        ['label' => 'Pakistan (Islamabad)', 'value' => 'Asia/Karachi'],
        ['label' => 'India (Mumbai)', 'value' => 'Asia/Kolkata'],
        ['label' => 'India (Delhi)', 'value' => 'Asia/Kolkata'],
        ['label' => 'Bangladesh (Dhaka)', 'value' => 'Asia/Dhaka'],
        ['label' => 'Sri Lanka (Colombo)', 'value' => 'Asia/Colombo'],
        ['label' => 'Nepal (Kathmandu)', 'value' => 'Asia/Kathmandu'],
        ['label' => 'UAE (Dubai)', 'value' => 'Asia/Dubai'],
        ['label' => 'Saudi Arabia (Riyadh)', 'value' => 'Asia/Riyadh'],
        ['label' => 'Qatar (Doha)', 'value' => 'Asia/Qatar'],
        ['label' => 'Kuwait (Kuwait City)', 'value' => 'Asia/Kuwait'],
        ['label' => 'Bahrain (Manama)', 'value' => 'Asia/Bahrain'],
        ['label' => 'Oman (Muscat)', 'value' => 'Asia/Muscat'],
        ['label' => 'UK (London)', 'value' => 'Europe/London'],
        ['label' => 'USA (New York)', 'value' => 'America/New_York'],
        ['label' => 'USA (Los Angeles)', 'value' => 'America/Los_Angeles'],
        ['label' => 'Canada (Toronto)', 'value' => 'America/Toronto'],
        ['label' => 'Australia (Sydney)', 'value' => 'Australia/Sydney'],
        ['label' => 'UTC (Universal Time)', 'value' => 'UTC']
    ];
}

/**
 * Get timezone display name
 * @param string $timezone Timezone identifier
 * @return string Display name
 */
function getTimezoneDisplayName($timezone) {
    $options = getTimezoneOptions();
    foreach ($options as $option) {
        if ($option['value'] === $timezone) {
            return $option['label'];
        }
    }
    return $timezone;
}

/**
 * Get current time in timezone for preview
 * @param string $timezone Timezone identifier
 * @return string Formatted time
 */
function getTimezonePreview($timezone) {
    try {
        $date = new DateTime('now', new DateTimeZone($timezone));
        return $date->format('Y-m-d H:i:s T');
    } catch (Exception $e) {
        return 'Invalid timezone';
    }
}

/**
 * Initialize timezone system
 * Call this at the beginning of your application
 */
function initializeTimezone() {
    setSystemTimezone();
} 