<?php
/**
 * Database Path Helper
 * Automatically detects if running on localhost or cPanel
 * Provides consistent path handling for both environments
 */

class DatabaseHelper {
    
    /**
     * Get the appropriate data directory path
     * Works on both localhost (/emporio-sport) and cPanel (/)
     */
    public static function getDataDirectory() {
        $baseDir = __DIR__;
        $dataDir = $baseDir . '/data';
        
        // Create directory if it doesn't exist
        if (!is_dir($dataDir)) {
            @mkdir($dataDir, 0755, true);
        }
        
        return $dataDir;
    }
    
    /**
     * Detect if running on localhost or cPanel
     */
    public static function isLocalhost() {
        $host = $_SERVER['HTTP_HOST'] ?? '';
        return strpos($host, 'localhost') !== false || strpos($host, '127.0.0.1') !== false;
    }
    
    /**
     * Get the web base path for URLs
     */
    public static function getWebBasePath() {
        if (!defined('WEB_BASE_PATH')) {
            $scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
            if (strpos($scriptName, '/emporio-sport/') === 0 || $scriptName === '/emporio-sport' || $scriptName === '/emporio-sport/index.php') {
                define('WEB_BASE_PATH', '/emporio-sport');
            } else {
                define('WEB_BASE_PATH', '');
            }
        }
        return WEB_BASE_PATH;
    }
    
    /**
     * Get a JSON file path in the data directory
     */
    public static function getJsonFilePath($filename) {
        return self::getDataDirectory() . '/' . $filename;
    }
    
    /**
     * Load JSON data from file
     */
    public static function loadJson($filename) {
        $filepath = self::getJsonFilePath($filename);
        if (file_exists($filepath)) {
            return json_decode(file_get_contents($filepath), true) ?: [];
        }
        return [];
    }
    
    /**
     * Save JSON data to file
     */
    public static function saveJson($filename, $data) {
        $filepath = self::getJsonFilePath($filename);
        return file_put_contents(
            $filepath, 
            json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
        ) !== false;
    }
    
    /**
     * Append to JSON file (for logs, entries, etc)
     */
    public static function appendJson($filename, $item) {
        $data = self::loadJson($filename);
        
        // Ensure it's an array
        if (!is_array($data)) {
            $data = [];
        }
        
        // Add timestamp if not present
        if (!isset($item['timestamp'])) {
            $item['timestamp'] = date('Y-m-d H:i:s');
        }
        
        $data[] = $item;
        
        return self::saveJson($filename, $data);
    }
    
    /**
     * Get database status info (for debugging)
     */
    public static function getDatabaseInfo() {
        return [
            'environment' => self::isLocalhost() ? 'localhost' : 'cPanel/Production',
            'base_path' => self::getDataDirectory(),
            'web_base' => self::getWebBasePath(),
            'data_writable' => is_writable(self::getDataDirectory()),
            'timestamp' => date('Y-m-d H:i:s')
        ];
    }
}

// Auto-detect web base path on initialization
DatabaseHelper::getWebBasePath();
?>
