<?php
namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Services\CommunicationDirectoryService;
use App\Core\Database;
use App\Core\Permission;

final class CommunicationDirectoryController extends Controller
{
    public function people(): void
    {
        Auth::requireLogin();
        Permission::requireAny('communications.directory.all', 'communications.directory.own');

        $service=new CommunicationDirectoryService();

        $this->json([
            'results'=>$service->searchPeople(
                (string)($_GET['q'] ?? '')
            )
        ]);
    }

    public function activities(): void
    {
        Auth::requireLogin();
        Permission::requireAny('communications.directory.all', 'communications.directory.own');

        $service=new CommunicationDirectoryService();

        $this->json([
            'results'=>$service->searchActivities(
                (string)($_GET['q'] ?? '')
            )
        ]);
    }

    public function test(): void
    {
        Auth::requireLogin();
        Permission::requireSuperAdmin();

        $pdo=Database::connection();

        $counts=[];

        foreach([
            'clients',
            'membres_famille',
            'professeurs',
            'ateliers',
            'groupes_cours'
        ] as $table){
            $counts[$table]=(int)$pdo->query(
                "SELECT COUNT(*) FROM `{$table}`"
            )->fetchColumn();
        }

        $this->json([
            'ok'=>true,
            'counts'=>$counts,
            'session_keys'=>array_keys($_SESSION ?? [])
        ]);
    }

    private function json(array $payload): void
    {
        header('Content-Type: application/json; charset=utf-8');
        header('Cache-Control: no-store, private');
        header('X-Content-Type-Options: nosniff');

        echo json_encode(
            $payload,
            JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES
        );
        exit;
    }
}
