<?php
namespace Peak;

class Auth {
    public static function isLoggedIn(): bool {
        return isset($_SESSION['user_id']);
    }

    public static function requireAuth(): void {
        if (!self::isLoggedIn()) Response::error('Unauthorized', 401);
    }

    public static function isOwner(): bool {
        return self::isLoggedIn() && ($_SESSION['email'] ?? '') === Config::$OWNER_EMAIL;
    }

    public static function requireOwner(): void {
        if (!self::isOwner()) Response::error('Forbidden', 403);
    }

    public static function handleRequest(string $method, ?string $id): void {
        if ($method === 'GET' && $id === 'me') {
            if (!self::isLoggedIn()) Response::json(['authenticated' => false]);
            Response::json(['authenticated' => true, 'user' => [
                'id' => $_SESSION['user_id'],
                'full_name' => $_SESSION['full_name'] ?? '',
                'email' => $_SESSION['email'] ?? '',
                'role' => $_SESSION['role'] ?? ''
            ]]);
        }
        if ($method !== 'POST') Response::error('Method not allowed', 405);
        $data = Request::json();
        switch ($id) {
            case 'login': self::handleLogin($data); break;
            case 'send-verification':
            case 'register': self::handleRegister($data); break;
            case 'logout': self::handleLogout(); break;
            case 'forgot-password': self::handleForgotPassword($data); break;
            case 'reset-password': self::handleResetPassword($data); break;
            default: Response::error('Not found', 404);
        }
    }

    private static function handleLogin(array $data): void {
        $email = $data['email'] ?? '';
        $password = $data['password'] ?? '';
        if (!$email || !$password) Response::error('Email and password required');
        $user = Database::fetch('SELECT id, full_name, email, password, role FROM users WHERE email = ?', [$email]);
        if (!$user || !password_verify($password, $user['password'])) Response::error('Invalid email or password', 401);
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['full_name'] = $user['full_name'];
        $_SESSION['email'] = $user['email'];
        $_SESSION['role'] = $user['role'];
        Response::json(['success' => true, 'user' => ['id' => $user['id'], 'full_name' => $user['full_name'], 'email' => $user['email'], 'role' => $user['role']]]);
    }

    private static function handleRegister(array $data): void {
        $fullName = $data['full_name'] ?? '';
        $email = $data['email'] ?? '';
        $password = $data['password'] ?? '';
        if (!$fullName || !$email || !$password) Response::error('All fields required');
        if (strlen($password) < 6) Response::error('Password must be at least 6 characters');
        if (Database::fetch('SELECT id FROM users WHERE email = ?', [$email])) Response::error('Email already registered', 409);
        $hash = password_hash($password, PASSWORD_BCRYPT);
        $userId = Database::insert('INSERT INTO users (full_name, email, password, role, email_verified) VALUES (?, ?, ?, ?, 1)', [$fullName, $email, $hash, 'Viewer']);
        $_SESSION['user_id'] = (int)$userId;
        $_SESSION['full_name'] = $fullName;
        $_SESSION['email'] = $email;
        $_SESSION['role'] = 'Viewer';
        Response::json(['success' => true, 'user' => ['id' => (int)$userId, 'full_name' => $fullName, 'email' => $email, 'role' => 'Viewer']]);
    }

    private static function handleLogout(): void {
        $_SESSION = [];
        setcookie(session_name(), '', time() - 3600, '/');
        session_destroy();
        Response::json(['success' => true]);
    }

    private static function handleForgotPassword(array $data): void {
        $email = $data['email'] ?? '';
        if (!$email) Response::error('Email required');
        $user = Database::fetch('SELECT id, full_name FROM users WHERE email = ?', [$email]);
        if (!$user) Response::json(['success' => true, 'message' => 'If the email exists, a reset link has been sent.']);
        $token = bin2hex(random_bytes(32));
        $expires = date('Y-m-d H:i:s', time() + 3600);
        Database::query('INSERT INTO password_reset_tokens (user_id, token, expires_at) VALUES (?, ?, ?)', [$user['id'], $token, $expires]);
        $resetLink = ($_SERVER['HTTP_ORIGIN'] ?? 'http://localhost:3000') . '/login.html?reset=' . $token;
        $html = '<div style="font-family:Montserrat,sans-serif;background:#0F1115;color:#E5E7EB;padding:40px;max-width:480px;margin:0 auto;"><h2 style="font-weight:300;font-size:24px;letter-spacing:-0.03em;">Peak<span style="color:#6B7280;">Platform</span></h2><p style="color:#9CA3AF;line-height:1.6;">Hi ' . htmlspecialchars($user['full_name']) . ',</p><p style="color:#9CA3AF;line-height:1.6;">Click the button below to reset your password. This link expires in 1 hour.</p><a href="' . $resetLink . '" style="display:inline-block;padding:14px 36px;border-radius:100px;background:linear-gradient(135deg,#B0B8C4,#9CA3AF);color:#0F1115;text-decoration:none;font-size:12px;font-weight:600;letter-spacing:0.15em;text-transform:uppercase;margin:24px 0;">Reset Password</a><p style="color:#6B7280;font-size:12px;">If you didn\'t request this, ignore this email.</p></div>';
        MailService::send($email, 'Reset Your Peak Platform Password', $html);
        Response::json(['success' => true, 'message' => 'If the email exists, a reset link has been sent.']);
    }

    private static function handleResetPassword(array $data): void {
        $token = $data['token'] ?? '';
        $password = $data['password'] ?? '';
        if (!$token || !$password) Response::error('Token and password required');
        if (strlen($password) < 6) Response::error('Password must be at least 6 characters');
        $row = Database::fetch('SELECT user_id FROM password_reset_tokens WHERE token = ? AND expires_at > NOW() AND used = 0', [$token]);
        if (!$row) Response::error('Invalid or expired reset token');
        $hash = password_hash($password, PASSWORD_BCRYPT);
        Database::query('UPDATE users SET password = ? WHERE id = ?', [$hash, $row['user_id']]);
        Database::query('UPDATE password_reset_tokens SET used = 1 WHERE token = ?', [$token]);
        Response::json(['success' => true, 'message' => 'Password reset successfully.']);
    }
}
