<?php declare(strict_types=1);
// Christo Lochenberg Developments | info@christodev.co.za | +27 61 523 9126

class Search extends Controller {
    
    private $searchModel;

    public function __construct() {
        if (!isLoggedIn()) {
            header('Location: ' . URLROOT . '/users/login');
            exit;
        }
        $this->searchModel = $this->model('SearchModel');
    }

    public function index(): void {
        // Sanitize the search query safely from the URL
        $q = isset($_GET['q']) ? trim(filter_input(INPUT_GET, 'q', FILTER_SANITIZE_FULL_SPECIAL_CHARS)) : '';
        
        $jobcards = [];
        $users = [];
        $partners = [];

        if (!empty($q)) {
            $role = $_SESSION['user_role'];
            $userId = (int)$_SESSION['user_id'];
            
            // Everyone can search jobcards (Model handles the RBAC isolation)
            $jobcards = $this->searchModel->searchJobcards($q, $role, $userId);
            
            // Only Admins can global search the actual user/partner directories
            if ($role === 'admin') {
                $users = $this->searchModel->searchUsers($q);
                $partners = $this->searchModel->searchPartners($q);
            }
            
            systemLog('GLOBAL_SEARCH', "User searched for: '{$q}'");
        }

        $data = [
            'title' => 'Global Search',
            'query' => $q,
            'jobcards' => $jobcards,
            'users' => $users,
            'partners' => $partners
        ];

        // --- UPDATED: Now points to your standard search index view ---
        $this->view('search/index', $data);
    }
}