<?php

declare(strict_types=1);

class AdminUserController
{
    public static function routes(): void
    {
        Router::get('/admin/users', [self::class, 'index']);
        Router::get('/admin/users/create', [self::class, 'create']);
        Router::post('/admin/users/store', [self::class, 'store']);
        Router::get('/admin/users/{id}/edit', [self::class, 'edit']);
        Router::post('/admin/users/{id}/update', [self::class, 'update']);
        Router::post('/admin/users/{id}/delete', [self::class, 'destroy']);
        Router::post('/admin/users/bulk-delete', [self::class, 'bulkDelete']);
        Router::post('/admin/users/{id}/toggle-active', [self::class, 'toggleActive']);
    }

    public static function index(): void
    {
        Auth::requireAdmin();
        $search = $_GET['q'] ?? '';
        $total = User::count($search);
        $pagination = Pagination::fromRequest($total, 100);
        Router::render('admin/users', [
            'pageTitle' => 'Users', 'activeMenu' => 'users', 'contentTemplate' => '_users',
            'headerAction' => ['url' => '/admin/users/create', 'label' => 'New User'],
            'users' => User::all($pagination->perPage, $pagination->offset, $search),
            'pagination' => $pagination, 'search' => $search,
        ]);
    }

    public static function create(): void
    {
        Auth::requireAdmin();
        Router::render('admin/user_form', [
            'pageTitle' => 'New User', 'activeMenu' => 'users', 'contentTemplate' => '_user_form',
            'editUser' => null, 'error' => null,
        ]);
    }

    public static function store(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { Router::redirect('/admin/users'); }
        $role = $_POST['role'] ?? 'user';
        if (!in_array($role, ['user', 'moderator', 'admin'], true)) { $role = 'user'; }
         
         
        if ($role !== 'user' && (Auth::user()['role'] ?? '') !== 'admin') { $role = 'user'; }
        User::create([
            'username' => trim($_POST['username'] ?? ''),
            'email' => trim($_POST['email'] ?? ''),
            'password' => $_POST['password'] ?? '',
            'role' => $role,
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
        ]);
        $_SESSION['flash'] = ['type' => 'success', 'message' => 'User created successfully.'];
        Router::redirect('/admin/users');
    }

    public static function edit(): void
    {
        Auth::requireAdmin();
        $userId = (int) Router::param('id');
        $u = User::find($userId);
        if (!$u) { Router::redirect('/admin/users'); }

        $stats = [
            'favorites' => (int) Database::fetchOne('SELECT COUNT(*) as c FROM user_favorites WHERE user_id = ?', [$userId])['c'],
            'likes'     => (int) Database::fetchOne('SELECT COUNT(*) as c FROM video_likes WHERE user_id = ? AND type = ?', [$userId, 'like'])['c'],
            'comments'  => (int) Database::fetchOne('SELECT COUNT(*) as c FROM comments WHERE user_id = ?', [$userId])['c'],
            'history'   => (int) Database::fetchOne('SELECT COUNT(*) as c FROM user_history WHERE user_id = ?', [$userId])['c'],
        ];
        $recentComments = Database::fetchAll(
            'SELECT c.id, c.body, c.status, c.created_at, v.title as video_title, v.id as video_id
             FROM comments c LEFT JOIN videos v ON c.video_id = v.id
             WHERE c.user_id = ? ORDER BY c.created_at DESC LIMIT 5', [$userId]
        );
        $recentFavorites = Database::fetchAll(
            'SELECT v.id, v.title, v.slug, v.thumbnail FROM user_favorites uf
             JOIN videos v ON uf.video_id = v.id
             WHERE uf.user_id = ? ORDER BY uf.created_at DESC LIMIT 5', [$userId]
        );

        Router::render('admin/user_form', [
            'pageTitle' => 'Edit User', 'activeMenu' => 'users', 'contentTemplate' => '_user_form',
            'editUser' => $u, 'error' => null,
            'stats' => $stats, 'recentComments' => $recentComments, 'recentFavorites' => $recentFavorites,
        ]);
    }

    public static function update(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { Router::redirect('/admin/users'); }
        $id = (int) Router::param('id');
        $existing = User::find($id);
        if (!$existing) { Router::redirect('/admin/users'); return; }

         
         
        if ($existing['role'] !== 'user' && (Auth::user()['role'] ?? '') !== 'admin') {
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'You are not allowed to edit this account.'];
            Router::redirect('/admin/users'); return;
        }

        $data = [
            'username' => trim($_POST['username'] ?? ''),
            'email' => trim($_POST['email'] ?? ''),
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
            'bio' => mb_substr(trim($_POST['bio'] ?? ''), 0, 500),
        ];

         
         
         
        if ($existing['role'] === 'admin' || (Auth::user()['role'] ?? '') !== 'admin') {
            $data['role'] = $existing['role'];
        } else {
            $role = $_POST['role'] ?? 'user';
            if (!in_array($role, ['user', 'moderator', 'admin'], true)) { $role = 'user'; }
            $data['role'] = $role;
        }
        if (!empty($_POST['password'])) {
            $data['password'] = $_POST['password'];
        }
        User::update($id, $data);
        $_SESSION['flash'] = ['type' => 'success', 'message' => 'User updated successfully.'];
        Router::redirect('/admin/users');
    }

    public static function destroy(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { Router::redirect('/admin/users'); }
        $id = (int) Router::param('id');
        if ($id === Auth::id()) {
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'You cannot delete your own account.'];
            Router::redirect('/admin/users');
        }
        $target = User::find($id);
        if (!$target) { Router::redirect('/admin/users'); return; }
        if ($target['role'] !== 'user' && (Auth::user()['role'] ?? '') !== 'admin') {
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'You are not allowed to delete this account.'];
            Router::redirect('/admin/users'); return;
        }
        if ($target['role'] === 'admin' && self::activeAdminCount() <= 1) {
            $_SESSION['flash'] = ['type' => 'error', 'message' => 'You cannot delete the last administrator.'];
            Router::redirect('/admin/users'); return;
        }
        User::delete($id);
        $_SESSION['flash'] = ['type' => 'success', 'message' => 'User deleted successfully.'];
        Router::redirect('/admin/users');
    }

    public static function bulkDelete(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { http_response_code(403); echo json_encode(['error' => 'CSRF']); return; }
        $input = json_decode(file_get_contents('php://input'), true);
        $ids = array_filter(array_map('intval', $input['ids'] ?? []), fn($id) => $id > 0);
         
        $ids = array_filter($ids, fn($id) => $id !== Auth::id());
         
        if ((Auth::user()['role'] ?? '') !== 'admin') {
            $ids = array_filter($ids, function ($id) {
                $t = User::find($id);
                return $t && $t['role'] === 'user';
            });
        }
        foreach ($ids as $id) { User::delete($id); }
        $_SESSION['flash'] = ['type' => 'success', 'message' => count($ids) . ' user(s) deleted.'];
        echo json_encode(['deleted' => count($ids)]);
    }

    public static function toggleActive(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) {
            http_response_code(403);
            echo json_encode(['error' => 'CSRF token invalid']);
            return;
        }
        $userId = (int) Router::param('id');
        $user = User::find($userId);
        if (!$user) {
            http_response_code(404);
            echo json_encode(['error' => 'User not found']);
            return;
        }
        if ($user['role'] !== 'user' && (Auth::user()['role'] ?? '') !== 'admin') {
            http_response_code(403); echo json_encode(['error' => 'Forbidden']); return;
        }
        if ($userId === Auth::id()) {
            http_response_code(400); echo json_encode(['error' => 'You cannot change your own status.']); return;
        }
        $newStatus = $user['is_active'] ? 0 : 1;
        if ($user['role'] === 'admin' && $user['is_active'] && self::activeAdminCount() <= 1) {
            http_response_code(400); echo json_encode(['error' => 'Cannot deactivate the last administrator.']); return;
        }
        Database::query('UPDATE users SET is_active = ? WHERE id = ?', [$newStatus, $userId]);
        header('Content-Type: application/json');
        echo json_encode(['success' => true, 'is_active' => $newStatus]);
    }

    private static function activeAdminCount(): int
    {
        return (int) (Database::fetchOne("SELECT COUNT(*) AS c FROM users WHERE role = 'admin' AND is_active = 1")['c'] ?? 0);
    }
}
