<?php
require_once __DIR__ . '/../Core.php';
require_once __DIR__ . '/../models/Contact.php';
require_once __DIR__ . '/../models/Message.php';
require_once __DIR__ . '/../models/Template.php';
require_once __DIR__ . '/../models/Campaign.php';
require_once __DIR__ . '/../models/Account.php';
require_once __DIR__ . '/../models/User.php';

class SearchController extends Controller
{
    public function index(): void
    {
        require_permission('dashboard.view');
        $q = trim($_GET['q'] ?? '');
        $contacts = $messages = $templates = $campaigns = $accounts = $users = [];
        if ($q !== '') {
            $contacts = (new Contact())->search($q, 'all', 1, 8)['data'];
            $messages = (new Message())->search(['q' => $q], 1, 8)['data'];
            $templates = array_values(array_filter((new Template())->all(), function ($t) use ($q) {
                return stripos((string)$t['name'], $q) !== false || stripos((string)$t['body'], $q) !== false || stripos((string)($t['subject'] ?? ''), $q) !== false;
            }));
            $campaigns = array_values(array_filter((new Campaign())->all(), function ($c) use ($q) {
                return stripos((string)$c['name'], $q) !== false || stripos((string)($c['segment_name'] ?? ''), $q) !== false;
            }));
            $accounts = array_values(array_filter((new Account())->all(), fn($a) => stripos((string)$a['name'], $q) !== false || stripos((string)($a['industry'] ?? ''), $q) !== false));
            $users = array_values(array_filter((new User())->all(), fn($u) => stripos((string)$u['name'], $q) !== false || stripos((string)$u['email'], $q) !== false));
            $templates = array_slice($templates, 0, 8);
            $campaigns = array_slice($campaigns, 0, 8);
            $accounts = array_slice($accounts, 0, 8);
            $users = array_slice($users, 0, 8);
        }
        $this->view('search/index', compact('q','contacts','messages','templates','campaigns','accounts','users'));
    }
}
