<?php
class Admin {
    private $email;
    private $password;
    private $cookieName = 'admin_remember';
    private $cookieExpiry = 2592000; // 30 days in seconds
    private $envFile;

    public function __construct() {
        $this->email = $_ENV['ADMIN_EMAIL'] ?? 'admin@example.com';
        $this->password = $_ENV['ADMIN_PASSWORD'] ?? 'securepassword123';
        $this->envFile = __DIR__ . '/../.env';

        // Check for remember me cookie
        $this->checkRememberCookie();
    }

    public function authenticate($email, $password) {
        return $email === $this->email && $password === $this->password;
    }

    public function isLoggedIn() {
        return isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;
    }

    public function login($rememberMe = false) {
        $_SESSION['admin_logged_in'] = true;

        if ($rememberMe) {
            $this->setRememberCookie();
        }
    }

    public function logout() {
        unset($_SESSION['admin_logged_in']);
        $this->clearRememberCookie();
        session_destroy();
    }

    /**
     * Get admin email
     */
    public function getEmail() {
        return $this->email;
    }

    /**
     * Update admin credentials
     */
    public function updateCredentials($email, $password) {
        // Validate inputs
        if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return false;
        }

        if (empty($password) || strlen($password) < 8) {
            return false;
        }

        // Update .env file
        if ($this->updateEnvFile('ADMIN_EMAIL', $email) && $this->updateEnvFile('ADMIN_PASSWORD', $password)) {
            // Update current instance
            $this->email = $email;
            $this->password = $password;

            // Update $_ENV
            $_ENV['ADMIN_EMAIL'] = $email;
            $_ENV['ADMIN_PASSWORD'] = $password;

            return true;
        }

        return false;
    }

    /**
     * Update a value in the .env file
     */
    public function updateEnvFile($key, $value) {
        if (!file_exists($this->envFile)) {
            return false;
        }

        $envContent = file_get_contents($this->envFile);
        
        // Escape value if it contains special characters or spaces
        if (preg_match('/[\s#"\'\\\\]/', $value)) {
            $value = '"' . addslashes($value) . '"';
        }

        // Check if the key exists (handle potential multi-line values)
        $pattern = "/^{$key}=.*?(?=\n[A-Z_]+\s*=|\n#|\n\s*\n|\n\s*$|$)/ms";
        if (preg_match($pattern, $envContent)) {
            // Update existing key
            $envContent = preg_replace($pattern, "{$key}={$value}", $envContent);
        } else {
            // Add new key
            $envContent .= PHP_EOL . "{$key}={$value}";
        }

        // Write back to file
        $result = file_put_contents($this->envFile, $envContent) !== false;
        
        // If successful, reload the environment variables
        if ($result) {
            $this->reloadEnvironment($key, $value);
        }
        
        return $result;
    }

    /**
     * Reload environment variables after updating .env file
     */
    private function reloadEnvironment($key = null, $value = null) {
        // If specific key provided, just update that one
        if ($key !== null && $value !== null) {
            // Remove quotes if they were added during escaping
            $cleanValue = trim($value, '"');
            $_ENV[$key] = $cleanValue;
            putenv("{$key}={$cleanValue}");
        } else {
            // Reload entire .env file (more comprehensive but slower)
            try {
                $dotenv = \Dotenv\Dotenv::createImmutable(dirname($this->envFile));
                $dotenv->load();
            } catch (Exception $e) {
                // If dotenv fails, at least update the specific key in $_ENV
                if ($key !== null && $value !== null) {
                    $cleanValue = trim($value, '"');
                    $_ENV[$key] = $cleanValue;
                    putenv("{$key}={$cleanValue}");
                }
            }
        }
    }

    private function setRememberCookie() {
        // Generate a secure token
        $token = bin2hex(random_bytes(32));

        // Store the token in a cookie
        setcookie(
            $this->cookieName,
            $token,
            time() + $this->cookieExpiry,
            '/',
            '',
            true,  // Secure
            true   // HttpOnly
        );

        // Store the token hash in the session for verification
        $_SESSION['remember_token'] = password_hash($token, PASSWORD_DEFAULT);
    }

    private function checkRememberCookie() {
        if (!$this->isLoggedIn() && isset($_COOKIE[$this->cookieName])) {
            $token = $_COOKIE[$this->cookieName];

            // If we have a remember token in the session
            if (isset($_SESSION['remember_token'])) {
                // Verify the token
                if (password_verify($token, $_SESSION['remember_token'])) {
                    // Auto login
                    $_SESSION['admin_logged_in'] = true;

                    // Refresh the cookie
                    $this->setRememberCookie();
                }
            }
        }
    }

    private function clearRememberCookie() {
        // Delete the cookie by setting expiry in the past
        setcookie($this->cookieName, '', time() - 3600, '/', '', true, true);

        // Remove the token from session
        if (isset($_SESSION['remember_token'])) {
            unset($_SESSION['remember_token']);
        }
    }
}