<?php
namespace App\Controllers\Backend;

use App\Controllers\BaseController;
use App\Models\UserModel;
use App\Models\ChurchModel;
use App\Models\EventPackageModel;

class AjaxController extends BaseController
{

    public function searchUsers()
    {
        $term = $this->request->getGet('term');
        $userModel = new UserModel();

        $query = $userModel->select('id, name, email');
        
        if ($term) {
            $query->groupStart()
                  ->like('name', $term)
                  ->orLike('email', $term)
                  ->groupEnd();
        }
        
        $users = $query->findAll(15); 


        $results = array_map(function($user) {
            return [
                'id'   => $user->id,
                'text' => "{$user->name} ({$user->email})"
            ];
        }, $users);

        return $this->response->setJSON(['results' => $results]);
    }


    public function searchChurches()
    {
        $term = $this->request->getGet('term');
        $churchModel = new ChurchModel();

        $query = $churchModel->select('id, name, city');
        
        if ($term) {
            $query->groupStart()
                  ->like('name', $term)
                  ->orLike('city', $term)
                  ->groupEnd();
        }
        
        $churches = $query->where('is_active', 1)
                          ->orderBy('name', 'ASC')
                          ->findAll(15);

        $results = array_map(function($church) {
            return [
                'id'   => $church->id,
                'text' => $church->city ? "{$church->name} - {$church->city}" : $church->name
            ];
        }, $churches);

        return $this->response->setJSON(['results' => $results]);
    }
    
    public function getPackagesByEvent(int $eventId)
    {
        if ($this->request->isAJAX()) {
            $packages = (new EventPackageModel())
                ->where('event_id', $eventId)
                ->where('deleted_at IS NULL') 
                ->findAll();
    
            return $this->response->setJSON($packages);
        }
        return $this->response->setStatusCode(403, 'Forbidden');
    }
}