<?php

namespace Dashboard\Controllers\Ajax;

use Dashboard\Core\Controller;
use Dashboard\Services\AvatarService;
use Dashboard\Services\SearchService;
use PDO;

class SearchController extends Controller
{
    public function index()
    {
        $query = mb_strtolower(input('query'), 'UTF-8');
				
				if (strlen($query) < 3) {
					response()->json([]);
				}
	    
		    $searchService = new SearchService();
				$results = $searchService->search($query);
				
				response()->json($results);
    }
	
	public function user()
	{
		$id = input("id");
		$query = input("query");
		$page = input("page", 1); // Default page is 1
		$limit = 10;
		$offset = ($page - 1) * $limit;
		
		// Handle fetching a single user by ID
		if ($id) {
			$search = db()->prepare("SELECT A.id, A.username, A.realname as displayName, A.email FROM Accounts A WHERE A.id = :id");
			$search->execute([
				"id" => $id
			]);
			$result = $search->fetch(PDO::FETCH_ASSOC);
			
			if ($result) {
				$result["avatar"] = AvatarService::get($result["id"], $result["displayName"]);
			}
			
			response()->json($result);
		}
		
		// Ensure the query has at least 3 characters for searching
		if (strlen($query) < 3) {
			response()->json([
				"users" => [],
				"hasMore" => false
			]);
		}
		
		// Fetch users with pagination
		$search = db()->prepare("
        SELECT A.id, A.username, A.realname as displayName, A.email
        FROM Accounts A
        WHERE A.username LIKE :search
           OR A.realname LIKE :search
           OR A.email LIKE :search
        LIMIT :limit OFFSET :offset
    ");
		$search->bindValue("search", "%$query%", PDO::PARAM_STR);
		$search->bindValue("limit", $limit, PDO::PARAM_INT);
		$search->bindValue("offset", (int) $offset, PDO::PARAM_INT);
		$search->execute();
		
		$users = array_map(function ($user) {
			$user["avatar"] = AvatarService::get($user["id"], $user["displayName"]);
			return $user;
		}, $search->fetchAll(PDO::FETCH_ASSOC));
		
		// Check if there are more records for pagination
		$countSearch = db()->prepare("
        SELECT COUNT(A.id) as total
        FROM Accounts A
        WHERE A.username LIKE :search
           OR A.realname LIKE :search
           OR A.email LIKE :search
    ");
		$countSearch->execute([
			"search" => "%$query%"
		]);
		$totalRecords = $countSearch->fetch(PDO::FETCH_ASSOC)["total"];
		$hasMore = ($offset + $limit) < $totalRecords;
		
		// Return results with pagination information
		response()->json([
			"users" => $users,
			"hasMore" => $hasMore
		]);
	}
}