<?php
/**
 * Controller Tags
 * Gestion des tags de conversations
 */

namespace App\Controllers;

use Core\Controller;
use App\Services\AutoTaggingService;

require_once APP_PATH . '/Services/AutoTaggingService.php';

class TagController extends Controller
{
    private AutoTaggingService $taggingService;

    public function __construct()
    {
        parent::__construct();
        $this->taggingService = new AutoTaggingService();
        
        header('Content-Type: application/json');
    }

    /**
     * Statistiques des tags
     */
    public function getStats(): void
    {
        if (!isset($_SESSION['user_id'])) {
            $this->json(['success' => false, 'error' => 'Non authentifié'], 401);
            return;
        }

        $entrepriseId = $_SESSION['entreprise_id'] ?? 0;
        $period = $_GET['period'] ?? '30days';

        $stats = $this->taggingService->getTagStats($entrepriseId, $period);
        $suggestions = $this->taggingService->getSuggestedTags($entrepriseId);

        $this->json([
            'success' => true,
            'stats' => $stats,
            'suggestions' => $suggestions
        ]);
    }

    /**
     * Ajouter un tag à une conversation
     */
    public function addTag(string $id): void
    {
        if (!isset($_SESSION['user_id'])) {
            $this->json(['success' => false, 'error' => 'Non authentifié'], 401);
            return;
        }

        $input = json_decode(file_get_contents('php://input'), true);
        $tag = $input['tag'] ?? '';

        if (empty($tag)) {
            $this->json(['success' => false, 'error' => 'Tag manquant'], 400);
            return;
        }

        $result = $this->taggingService->addManualTag((int)$id, $tag, $_SESSION['user_id']);

        $this->json([
            'success' => $result,
            'message' => $result ? 'Tag ajouté' : 'Tag déjà existant'
        ]);
    }

    /**
     * Supprimer un tag d'une conversation
     */
    public function removeTag(string $id, string $tag): void
    {
        if (!isset($_SESSION['user_id'])) {
            $this->json(['success' => false, 'error' => 'Non authentifié'], 401);
            return;
        }

        $result = $this->taggingService->removeTag((int)$id, $tag);

        $this->json([
            'success' => $result,
            'message' => 'Tag supprimé'
        ]);
    }
}
