<?php
/**
 * KSO Chandigarh AdminLTE URL Initialization File
 * 
 * This file ensures that URLs work correctly with or without file extensions
 * specifically for the AdminLTE dashboard section.
 */

// Define base URLs for the admin section
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
$host = $_SERVER['HTTP_HOST'];
$adminDir = dirname($_SERVER['SCRIPT_NAME']);

// Define admin URL constants
define('ADMIN_URL', $protocol . $host . $adminDir);
define('ADMINLTE_ASSETS_URL', ADMIN_URL . '/dist');
define('ADMINLTE_API_URL', ADMIN_URL . '/api');

/**
 * Get canonical link for SEO
 * 
 * @param string $url The canonical URL
 * @return string The canonical link HTML
 */
function getCanonicalLink($url) {
    return '<link rel="canonical" href="' . htmlspecialchars($url) . '">';
}

/**
 * Convert a regular AdminLTE URL to a clean URL
 * 
 * @param string $page The page name (without .php)
 * @param array $params Optional query parameters
 * @return string The clean URL
 */
function adminUrl($page, $params = []) {
    $url = ADMIN_URL . '/' . $page;
    
    if (!empty($params)) {
        $url .= '?' . http_build_query($params);
    }
    
    return $url;
}

/**
 * Get an API endpoint URL
 * 
 * @param string $endpoint The API endpoint path (supports new organized structure)
 *                        Examples: 
 *                        - 'fetch_members.php' (root level)
 *                        - 'dashboard/fetch_dashboard_stats.php' (organized)
 *                        - 'finance/fetch_transactions.php' (organized)
 * @return string The complete API URL
 */
function apiUrl($endpoint) {
    return ADMINLTE_API_URL . '/' . $endpoint;
}

/**
 * Get API URLs for the new organized structure
 * 
 * @param string $category The API category (dashboard, finance, charts, reports, system, auth)
 * @param string $endpoint The specific endpoint file
 * @return string The complete API URL
 */
function organizedApiUrl($category, $endpoint) {
    return ADMINLTE_API_URL . '/' . $category . '/' . $endpoint;
}

/**
 * Quick access functions for organized API categories
 */
function dashboardApiUrl($endpoint) { return organizedApiUrl('dashboard', $endpoint); }
function financeApiUrl($endpoint) { return organizedApiUrl('finance', $endpoint); }
function chartsApiUrl($endpoint) { return organizedApiUrl('charts', $endpoint); }
function reportsApiUrl($endpoint) { return organizedApiUrl('reports', $endpoint); }
function systemApiUrl($endpoint) { return organizedApiUrl('system', $endpoint); }
function authApiUrl($endpoint) { return organizedApiUrl('auth', $endpoint); }

/**
 * Update internal links in AdminLTE templates to use clean URLs
 * 
 * @param string $content The HTML content
 * @return string Updated HTML with clean URLs
 */
function updateAdminLteLinks($content) {
    $basePattern = 'href=(["\'])(' . preg_quote(ADMIN_URL, '/') . '/|)([^"\']*?)\.php(["\'])';
    $replacement = 'href=$1$2$3$4';
    
    return preg_replace('/' . $basePattern . '/', $replacement, $content);
}

/**
 * Initialize output buffering for AdminLTE pages
 */
function initAdminCleanUrls() {
    ob_start(function($buffer) {
        return updateAdminLteLinks($buffer);
    });
}

// Start URL processing for all AdminLTE pages
initAdminCleanUrls();

/**
 * Function to check if clean URLs are working in the AdminLTE section
 * 
 * @return bool True if clean URLs are working
 */
function checkAdminCleanUrls() {
    // Test URL without .php extension
    $testUrl = ADMIN_URL . '/dashboard';
    
    // Try to access the URL
    $ch = curl_init($testUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    // If we got a 200 response, clean URLs are working
    return $httpCode === 200;
}

// Add canonical links to header if needed
function addAdminCanonicalLinks() {
    $currentScript = basename($_SERVER['SCRIPT_FILENAME']);
    $currentPath = str_replace('.php', '', $currentScript);
    
    return getCanonicalLink(ADMIN_URL . '/' . $currentPath);
}

// Update DataTables AJAX URLs to work with clean URLs
function updateDataTablesUrls() {
    ?>
    <script>
    $(document).ready(function() {
        // Patch DataTables AJAX URLs to work with our clean URL system
        if ($.fn.dataTable) {
            // Store the original DataTable function
            var originalDataTable = $.fn.dataTable;
            
            // Override the DataTable function
            $.fn.dataTable = function(options) {
                // If there's an AJAX URL with .php extension, modify it
                if (options && options.ajax && typeof options.ajax === 'object' && options.ajax.url) {
                    // Remove .php from the URL if it's an internal API
                    if (options.ajax.url.indexOf('<?= ADMIN_URL ?>') === 0 || options.ajax.url.indexOf('/') === 0) {
                        options.ajax.url = options.ajax.url.replace(/\.php(\?|$)/, '$1');
                    }
                }
                
                // Call the original function
                return originalDataTable.apply(this, arguments);
            };
            
            // Copy all properties from the original object
            $.extend($.fn.dataTable, originalDataTable);
        }
    });
    </script>
    <?php
}
