<?php
/**
 * Database Configuration
 * Version: 2.0 - Fixed timezone for Kenyan time (EAT - UTC+3)
 */

// Database Configuration
define('DB_HOST', 'localhost');
define('DB_USER', 'lipawinc_skyzen');
define('DB_PASS', 'lipawinc_skyzen');
define('DB_NAME', 'lipawinc_skyzen');

// Site Configuration
define('SITE_URL', 'https://skyzen.co.ke'); // Change this to your domain

// Timezone Configuration - East Africa Time (Kenya)
date_default_timezone_set('Africa/Nairobi');
define('DB_TIMEZONE', '+03:00'); // EAT is UTC+3

// Error Reporting (Set to 0 in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Session Configuration
ini_set('session.cookie_httponly', 1);
ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_secure', 0); // Set to 1 if using HTTPS

/**
 * MySQLi Connection with Kenyan timezone
 */
function getConnection() {
    static $conn = null;
    
    if ($conn === null) {
        try {
            $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
            
            if ($conn->connect_error) {
                die('Database connection failed: ' . $conn->connect_error);
            }
            
            // Set charset
            $conn->set_charset('utf8mb4');
            
            // Set MySQL timezone to Kenyan time (EAT - UTC+3)
            if (!$conn->query("SET time_zone = '" . DB_TIMEZONE . "'")) {
                error_log("Failed to set MySQL timezone: " . $conn->error);
            }
            
        } catch (Exception $e) {
            die('Database error: ' . $e->getMessage());
        }
    }
    
    return $conn;
}

/**
 * PDO Connection with Kenyan timezone
 */
function getPDO() {
    static $pdo = null;
    
    if ($pdo === null) {
        try {
            $pdo = new PDO(
                'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4',
                DB_USER,
                DB_PASS,
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false
                ]
            );
            
            // Set MySQL timezone to Kenyan time (EAT - UTC+3)
            $pdo->exec("SET time_zone = '" . DB_TIMEZONE . "'");
            
        } catch (PDOException $e) {
            die('PDO Connection failed: ' . $e->getMessage());
        }
    }
    
    return $pdo;
}

/**
 * Get current Kenyan datetime in MySQL format
 * @param string $format Optional format (default: Y-m-d H:i:s)
 * @return string Current Kenyan time
 */
function getKenyanTime($format = 'Y-m-d H:i:s') {
    $timezone = new DateTimeZone('Africa/Nairobi');
    $datetime = new DateTime('now', $timezone);
    return $datetime->format($format);
}

/**
 * Get current Kenyan date
 * @return string Current date in Y-m-d format
 */
function getKenyanDate() {
    return getKenyanTime('Y-m-d');
}

/**
 * Convert UTC time to Kenyan time
 * @param string $utcTime UTC datetime string
 * @param string $format Output format (default: Y-m-d H:i:s)
 * @return string Kenyan time
 */
function utcToKenyan($utcTime, $format = 'Y-m-d H:i:s') {
    try {
        $utcTimezone = new DateTimeZone('UTC');
        $kenyanTimezone = new DateTimeZone('Africa/Nairobi');
        
        $datetime = new DateTime($utcTime, $utcTimezone);
        $datetime->setTimezone($kenyanTimezone);
        
        return $datetime->format($format);
    } catch (Exception $e) {
        error_log("UTC to Kenyan conversion error: " . $e->getMessage());
        return $utcTime;
    }
}

/**
 * Convert Kenyan time to UTC
 * @param string $kenyanTime Kenyan datetime string
 * @param string $format Output format (default: Y-m-d H:i:s)
 * @return string UTC time
 */
function kenyanToUtc($kenyanTime, $format = 'Y-m-d H:i:s') {
    try {
        $kenyanTimezone = new DateTimeZone('Africa/Nairobi');
        $utcTimezone = new DateTimeZone('UTC');
        
        $datetime = new DateTime($kenyanTime, $kenyanTimezone);
        $datetime->setTimezone($utcTimezone);
        
        return $datetime->format($format);
    } catch (Exception $e) {
        error_log("Kenyan to UTC conversion error: " . $e->getMessage());
        return $kenyanTime;
    }
}

/**
 * Format Kenyan datetime for display
 * @param string $datetime Datetime string from database
 * @param string $format Display format (default: M j, Y g:i A)
 * @return string Formatted datetime
 */
function formatKenyanTime($datetime, $format = 'M j, Y g:i A') {
    try {
        if (empty($datetime) || $datetime === '0000-00-00 00:00:00') {
            return 'N/A';
        }
        
        $kenyanTimezone = new DateTimeZone('Africa/Nairobi');
        $dt = new DateTime($datetime, $kenyanTimezone);
        return $dt->format($format);
    } catch (Exception $e) {
        error_log("Format Kenyan time error: " . $e->getMessage());
        return $datetime;
    }
}

/**
 * Get time ago in Kenyan timezone
 * @param string $datetime Datetime string
 * @return string Time ago text (e.g., "2 hours ago")
 */
function timeAgoKenyan($datetime) {
    try {
        if (empty($datetime) || $datetime === '0000-00-00 00:00:00') {
            return 'Unknown';
        }
        
        $kenyanTimezone = new DateTimeZone('Africa/Nairobi');
        $now = new DateTime('now', $kenyanTimezone);
        $ago = new DateTime($datetime, $kenyanTimezone);
        $diff = $now->diff($ago);
        
        if ($diff->y > 0) return $diff->y . ' year' . ($diff->y > 1 ? 's' : '') . ' ago';
        if ($diff->m > 0) return $diff->m . ' month' . ($diff->m > 1 ? 's' : '') . ' ago';
        if ($diff->d > 0) return $diff->d . ' day' . ($diff->d > 1 ? 's' : '') . ' ago';
        if ($diff->h > 0) return $diff->h . ' hour' . ($diff->h > 1 ? 's' : '') . ' ago';
        if ($diff->i > 0) return $diff->i . ' minute' . ($diff->i > 1 ? 's' : '') . ' ago';
        return 'Just now';
    } catch (Exception $e) {
        error_log("Time ago error: " . $e->getMessage());
        return 'Unknown';
    }
}

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Log timezone info (for debugging - remove in production)
if (defined('DEBUG_TIMEZONE') && DEBUG_TIMEZONE) {
    error_log("PHP Timezone: " . date_default_timezone_get());
    error_log("Current Kenyan Time: " . getKenyanTime());
    error_log("Database Timezone: " . DB_TIMEZONE);
}
?>