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

class SearchModel {
    private Database $db;

    public function __construct() {
        $this->db = new Database();
    }

    public function searchJobcards(string $query, string $role, int $userId): array {
        $sql = "SELECT j.*, 
                       c.name as client_name, c.company_name, 
                       t.name as tech_name 
                FROM jobcards j
                LEFT JOIN users c ON j.client_id = c.id
                LEFT JOIN users t ON j.technician_id = t.id
                WHERE (j.jobcard_number LIKE :q1 
                   OR j.instructions LIKE :q2 
                   OR j.work_done LIKE :q3 
                   OR c.name LIKE :q4 
                   OR c.company_name LIKE :q5)";

        // STRICT RBAC ENFORCEMENT (Role-Based Access Control)
        if ($role === 'staff') {
            $sql .= " AND j.technician_id = :user_id";
        } elseif ($role === 'client') {
            $sql .= " AND j.client_id = :user_id";
        }

        $sql .= " ORDER BY j.created_at DESC LIMIT 20";

        $this->db->query($sql);
        
        // Bind the search string to each unique parameter
        $searchTerm = "%{$query}%";
        $this->db->bind(':q1', $searchTerm);
        $this->db->bind(':q2', $searchTerm);
        $this->db->bind(':q3', $searchTerm);
        $this->db->bind(':q4', $searchTerm);
        $this->db->bind(':q5', $searchTerm);
        
        if ($role !== 'admin') {
            $this->db->bind(':user_id', $userId);
        }

        return $this->db->resultSet();
    }

    public function searchUsers(string $query): array {
        $this->db->query("
            SELECT * FROM users 
            WHERE name LIKE :q1 
               OR email LIKE :q2 
               OR company_name LIKE :q3 
               OR contact_number LIKE :q4
            ORDER BY name ASC LIMIT 15
        ");
        
        $searchTerm = "%{$query}%";
        $this->db->bind(':q1', $searchTerm);
        $this->db->bind(':q2', $searchTerm);
        $this->db->bind(':q3', $searchTerm);
        $this->db->bind(':q4', $searchTerm);
        
        return $this->db->resultSet();
    }

    public function searchPartners(string $query): array {
        $this->db->query("
            SELECT * FROM partners 
            WHERE name LIKE :q1 
               OR email LIKE :q2 
               OR contact_number LIKE :q3
            ORDER BY name ASC LIMIT 10
        ");
        
        $searchTerm = "%{$query}%";
        $this->db->bind(':q1', $searchTerm);
        $this->db->bind(':q2', $searchTerm);
        $this->db->bind(':q3', $searchTerm);
        
        return $this->db->resultSet();
    }
}