<?php

echo "<h2>CoreFlux .htaccess Configuration Checker</h2>";
echo "<p>This script will check and attempt to correct the <code>RewriteBase</code> directives in your root and public/.htaccess files.</p>";

// --- 1. Load Path Configuration (File System Paths) ---
// Adjust this path if app/config/paths.php is not relative to this checker script.
// Assuming htaccess_checker.php is in the project root: /CoreFlux/htaccess_checker.php
// The config file is at /CoreFlux/app/config/paths.php
$configPath = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'paths.php';

if (!file_exists($configPath)) {
    die("<p style='color: red;'>❌ Error: Path configuration file not found at <code>" . htmlspecialchars($configPath) . "</code>. Please ensure it exists.</p>");
}
$pathConfig = require_once $configPath;

// --- Define Script-Specific Constants (File System Paths) ---
// These are absolute file system paths.
// Ensure these are defined only ONCE here.
define('FS_ROOT_PATH', $pathConfig['project_root_fs']);
define('FS_PUBLIC_PATH', FS_ROOT_PATH . DIRECTORY_SEPARATOR . $pathConfig['public_dir_name']);
define('FS_ROOT_HTACCESS_FILE', FS_ROOT_PATH . DIRECTORY_SEPARATOR . '.htaccess');
define('FS_PUBLIC_HTACCESS_FILE', FS_PUBLIC_PATH . DIRECTORY_SEPARATOR . '.htaccess');


// --- 2. Determine the Correct RewriteBase Paths (Dynamic, based on current web request) ---

// Robustly calculate the web paths relative to the DOCUMENT_ROOT
// This is the most reliable way to get the RewriteBase values.
$documentRoot = rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR . '/\\'); // Normalize document root
$projectFolderRelativePath = str_replace($documentRoot, '', FS_ROOT_PATH); // e.g., /CoreFlux or /

// Ensure projectFolderRelativePath starts with a slash
if (empty($projectFolderRelativePath) || $projectFolderRelativePath[0] !== '/') {
    $projectFolderRelativePath = '/' . $projectFolderRelativePath;
}
// Ensure projectFolderRelativePath ends with a slash (unless it's just '/')
if (strlen($projectFolderRelativePath) > 1 && substr($projectFolderRelativePath, -1) !== '/') {
    $projectFolderRelativePath .= '/';
}


// Correct RewriteBase for the root .htaccess (e.g., /CoreFlux/)
$correctRootRewriteBase = $projectFolderRelativePath;

// Correct RewriteBase for the public/.htaccess (e.g., /CoreFlux/public/)
$correctPublicRewriteBase = $projectFolderRelativePath . $pathConfig['public_dir_name'] . '/';


// --- Class Definition for HTACCESS operations ---
class CheckHtaccess {
    private $initialized = false;

    public function init() {
        if (!$this->initialized) {
            $this->initialized = true;
            echo "<p style='color: blue;'>✅ <code>CheckHtaccess</code> initialized.</p>";
        }
    }

    public function updateHtaccessFile(string $filePath, string $correctRewriteBase, string $fileType): bool {
        if (!$this->initialized) {
            echo "<p style='color: red;'>❌ Error: <code>CheckHtaccess</code> not initialized. Call <code>init()</code> first.</p>";
            return false;
        }
        echo "<p>Checking <code>" . htmlspecialchars($fileType) . "</code> .htaccess at: <code>" . htmlspecialchars($filePath) . "</code></p>";

        if (!file_exists($filePath)) {
            echo "<p style='color: orange;'>⚠️ Warning: <code>" . htmlspecialchars($fileType) . "</code> .htaccess file not found. Please create it first.</p>";
            return false;
        }

        $content = file_get_contents($filePath);
        if ($content === false) {
            echo "<p style='color: red;'>❌ Error: Could not read <code>" . htmlspecialchars($fileType) . "</code> .htaccess. Check file permissions.</p>";
            return false;
        }

        // Regex to find the RewriteBase line
        $pattern = '/^(\s*RewriteBase\s+).*$/m';
        $replacement = '${1}' . preg_quote($correctRewriteBase, '/');

        if (preg_match($pattern, $content)) {
            // RewriteBase line exists, replace it
            $newContent = preg_replace($pattern, $replacement, $content);
            if ($newContent === null) {
                echo "<p style='color: red;'>❌ Error: Regex replacement failed for <code>" . htmlspecialchars($fileType) . "</code> .htaccess.</p>";
                return false;
            }

            if ($newContent !== $content) {
                // Content changed, write it back
                if (file_put_contents($filePath, $newContent) !== false) {
                    echo "<p style='color: green;'>✅ Success: <code>RewriteBase</code> in <code>" . htmlspecialchars($fileType) . "</code> .htaccess updated to: <code>" . htmlspecialchars($correctRewriteBase) . "</code></p>";
                    return true;
                } else {
                    echo "<p style='color: red;'>❌ Error: Could not write to <code>" . htmlspecialchars($fileType) . "</code> .htaccess. Check file permissions.</p>";
                    return false;
                }
            } else {
                echo "<p style='color: blue;'>✔️ OK: <code>RewriteBase</code> in <code>" . htmlspecialchars($fileType) . "</code> .htaccess is already correct: <code>" . htmlspecialchars($correctRewriteBase) . "</code></p>";
                return true;
            }
        } else {
            // RewriteBase line does not exist, attempt to insert it after RewriteEngine On
            $patternInsert = '/^(\s*RewriteEngine\s+On\s*)$/mi'; // Case-insensitive 'On'
            $insertContent = "\nRewriteBase " . $correctRewriteBase . "\n";
            $newContent = preg_replace($patternInsert, '$1' . $insertContent, $content);

            if ($newContent !== null && $newContent !== $content) {
                if (file_put_contents($filePath, $newContent) !== false) {
                    echo "<p style='color: green;'>✅ Success: <code>RewriteBase</code> line added to <code>" . htmlspecialchars($fileType) . "</code> .htaccess: <code>" . htmlspecialchars($correctRewriteBase) . "</code></p>";
                    return true;
                } else {
                    echo "<p style='color: red;'>❌ Error: Could not write to <code>" . htmlspecialchars($fileType) . "</code> .htaccess. Check file permissions.</p>";
                    return false;
                }
            } else {
                echo "<p style='color: orange;'>⚠️ Warning: <code>RewriteBase</code> line not found and could not be automatically inserted after <code>RewriteEngine On</code>. Please add it manually.</p>";
                return false;
            }
        }
    }
}


// --- 3. Instantiate the class and perform checks and updates ---

// Create an instance of the checker
$checker = new CheckHtaccess();
// Initialize it
$checker->init();

echo "<h3>Root .htaccess</h3>";
$checker->updateHtaccessFile(FS_ROOT_HTACCESS_FILE, $correctRootRewriteBase, 'root');

echo "<h3>Public .htaccess</h3>";
$checker->updateHtaccessFile(FS_PUBLIC_HTACCESS_FILE, $correctPublicRewriteBase, 'public');

echo "<h3>Finished.</h3>";
echo "<p>Please ensure your Apache <code>mod_rewrite</code> is enabled and <code>AllowOverride All</code> is set for your project directories in Apache's configuration (<code>httpd.conf</code> or <code>httpd-vhosts.conf</code>).</p>";

// Display the calculated bases for user reference
echo "<p>Calculated Root RewriteBase: <code>" . htmlspecialchars($correctRootRewriteBase) . "</code></p>";
echo "<p>Calculated Public RewriteBase: <code>" . htmlspecialchars($correctPublicRewriteBase) . "</code></p>";

?>