<?php
// CoreFlux/core/MaintenanceController.php

namespace Core; // Essential: Place this class in the Core namespace

class Maintenance
{
    private $maintenanceConfig;

    public function __construct(array $maintenanceConfig){
        $this->maintenanceConfig = $maintenanceConfig;
    }
    /**
     * Displays the "Site Under Construction" page.
     * Sets HTTP status code 503 Service Unavailable.
     */
    public function show()
    {
        // Set HTTP status code 503 Service Unavailable, indicating temporary downtime.
        http_response_code(503);
        // Suggest client retry after 1 hour (3600 seconds). This helps search engines
        // understand the site is temporarily down, not permanently removed.
        header('Retry-After: 3600');
        // Set Content-Type header to ensure the browser renders HTML correctly.
        header('Content-Type: text/html; charset=UTF-8');

        // Include the maintenance view. FS_APP_PATH is defined in bootstrap.php
        // This constant provides the absolute file system path to your 'app' directory.
        // require_once FS_APP_PATH . DIRECTORY_SEPARATOR . 'Views' . DIRECTORY_SEPARATOR . 'maintenance.php';
        View::make('coreflux-default/maintenance')->render();
        
        // Crucial: Stop further script execution immediately after displaying the page.
        // This prevents any other application logic from running while in maintenance mode.
        exit();
    }

    /**
     * Handles the bypass password submission for maintenance mode.
     * Displays a password form or redirects on successful bypass.
     */
    public function bypass()
    {


        // Load maintenance configuration. FS_CONFIG_PATH is defined in bootstrap.php.
        // This file contains the 'enabled', 'bypass_path', and 'bypass_password' settings.
        // $maintenanceConfig = require_once FS_CONFIG_PATH . DIRECTORY_SEPARATOR . 'maintenance.php';

        // print_r($this->maintenanceConfig);

        $error = null; // Initialize an error variable to display messages on the form.
        $maintenanceConfig = $this->maintenanceConfig['bypass_password'];

        // Check if the request method is POST and if a 'password' field was submitted.
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password'])) {
            // Compare the submitted password with the configured bypass password.
            // Using a direct comparison for simplicity in a custom framework;
            // for production, consider more secure methods like password_verify()
            // if passwords were hashed in a database.
            if ($_POST['password'] == $maintenanceConfig) {
                echo $_POST['password'];
                // Password is correct, set a session variable to grant bypass access.
                // session_start() is assumed to have been called earlier in bootstrap.php.
                $_SESSION['maintenance_bypass'] = true;

                // Redirect the administrator to the site's root URL.
                // This makes them bypass the maintenance page on subsequent requests.
                header('Location: ' . $this->getSiteRootUrl());
                // Crucial: Stop further execution immediately after sending the redirect header.
                exit();
            } else {
                // If the password is incorrect, set an error message.
                $error = "Incorrect password.";
            }
        }
        
        // If it's a GET request (first visit to bypass page) or password was incorrect,
        // display the password submission form.
        // require_once FS_APP_PATH . DIRECTORY_SEPARATOR . 'Views' . DIRECTORY_SEPARATOR . 'maintenance_bypass_form.php';
        View::make('coreflux-default/maintenance_bypass_form')
        ->with([
            'error' => $error
        ])
        ->render();
        
        // Crucial: Stop further execution after showing the form.
        exit();
    }

    /**
     * Helper method to determine the site's root URL for redirection.
     * This ensures the redirect works correctly whether the project is in a
     * subdirectory or at the domain's root.
     * It relies on $_SERVER['SCRIPT_NAME'] (e.g., /CoreFlux/public/index.php).
     */
    private function getSiteRootUrl(): string
    {
        // Example: /CoreFlux/public/index.php
        $scriptName = $_SERVER['SCRIPT_NAME']; 
        
        // dirname($scriptName) gives the directory of the script: /CoreFlux/public
        $publicPathSegment = dirname($scriptName);

        // dirname($publicPathSegment) gives one level up: /CoreFlux
        // This is the project's web root path relative to the web server's DocumentRoot.
        $projectWebRoot = dirname($publicPathSegment);

        // Normalize the path: ensure it has a leading slash and no trailing slash
        // unless it's just '/' (for projects directly in DocumentRoot).
        if ($projectWebRoot === '/' || $projectWebRoot === '\\') {
            return '/'; // If project is at the web server's root
        }
        // Remove trailing slash if it exists, then add one back (unless it's empty string)
        return rtrim($projectWebRoot, '/') . '/';
    }
}