<?php
/**
 * Simple Authentication System for Photo Gallery
 * Provides basic login/logout functionality with session management
 */

class SimpleAuth
{
    /**
     * @var array
     */
    private $adminCredentials = [
        /*
         * Default hashed password for 'admin123' - should be changed in production
         * Example of how to hash a password:
         * $auth = new SimpleAuth();
         * $plainPassword = 'mypassword';
         * $hashed = $auth->hashPassword($plainPassword);
         * echo $hashed;
         */
        'admin' => '$2y$12$N0zV6HOn8HtQrDMy29vrsO1iC07VjHrGij6pHZa12X6XSD32Xxng6'
    ];

    public function __construct()
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
    }

    /**
     * Authenticate user with username and password
     */
    public function login($username, $password)
    {
        if (isset($this->adminCredentials[$username]) &&
            password_verify($password, $this->adminCredentials[$username])) {
            $_SESSION['authenticated'] = true;
            $_SESSION['username'] = $username;
            $_SESSION['login_time'] = time();
            return [
                'success' => true,
                'message' => 'Login successful',
                'user' => $username
            ];
        }

        return [
            'success' => false,
            'message' => 'Invalid username or password'
        ];
    }

    /**
     * Log out the current user
     */
    public function logout()
    {
        $_SESSION = [];
        if (isset($_COOKIE[session_name()])) {
            setcookie(session_name(), '', time() - 42000, '/');
        }
        session_destroy();

        return [
            'success' => true,
            'message' => 'Logged out successfully'
        ];
    }

    /**
     * Check if user is authenticated
     */
    public function isAuthenticated()
    {
        return isset($_SESSION['authenticated']) && $_SESSION['authenticated'] === true;
    }

    /**
     * Get current user info
     */
    public function getCurrentUser()
    {
        if ($this->isAuthenticated()) {
            return [
                'username' => $_SESSION['username'] ?? 'unknown',
                'login_time' => $_SESSION['login_time'] ?? 0,
                'authenticated' => true
            ];
        }

        return [
            'authenticated' => false
        ];
    }

    /**
     * Require authentication (redirect if not authenticated)
     */
    public function requireAuth()
    {
        if (!$this->isAuthenticated()) {
            http_response_code(401);
            echo json_encode([
                'success' => false,
                'error' => 'Authentication required',
                'code' => 'AUTH_REQUIRED'
            ]);
            exit;
        }
    }

    /**
     * Hash a password for storage
     * @param string $password Plain text password
     * @return string Hashed password
     */
    public function hashPassword($password)
    {
        return password_hash($password, PASSWORD_DEFAULT);
    }

    /**
     * Change user password
     * @param string $username Username
     * @param string $oldPassword Current password
     * @param string $newPassword New password
     * @return array Result array
     */
    public function changePassword($username, $oldPassword, $newPassword)
    {
        // Verify current password
        if (!isset($this->adminCredentials[$username]) ||
            !password_verify($oldPassword, $this->adminCredentials[$username])) {
            return [
                'success' => false,
                'message' => 'Current password is incorrect'
            ];
        }

        // Update password
        $this->adminCredentials[$username] = $this->hashPassword($newPassword);

        return [
            'success' => true,
            'message' => 'Password changed successfully'
        ];
    }
}
