<?php
// app/Controllers/ChatController.php
// Controller pro týmový chat – JSON API endpointy pro načítání, odesílání a mazání zpráv.
// Tento controller nevykresluje HTML layout, ale vrací pouze JSON odpovědi.

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Models\ChatRepository;
use App\Models\TeamRepository;

class ChatController extends Controller
{
    private ChatRepository $chatRepository;
    private TeamRepository $teamRepository;

    public function __construct($db)
    {
        parent::__construct($db);
        Auth::requireLogin();
        $this->chatRepository = new ChatRepository($this->db);
        $this->teamRepository = new TeamRepository($this->db);
    }

    //vypíše zprávy pro tým
    public function zpravy(): void
    {
        if (!isset($_GET['team_id'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing team_id']);
            return;
        }

        $teamId = (int)$_GET['team_id'];
        $user = Auth::user();

        $isMember = $this->jeClenemTymu($teamId, $user['id']);
        if (!$isMember) {
            http_response_code(403);
            echo json_encode(['error' => 'Access denied']);
            return;
        }

        $messages = $this->chatRepository->getTeamMessages($teamId);
        
        header('Content-Type: application/json');
        echo json_encode([
            'success' => true,
            'messages' => $messages
        ]);
    }

    //odešle zprávu
    public function odeslat(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            http_response_code(405);
            echo json_encode(['error' => 'Method not allowed']);
            return;
        }

        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['team_id']) || !isset($data['content']) || empty(trim($data['content']))) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing required fields']);
            return;
        }

        $teamId = (int)$data['team_id'];
        $content = trim($data['content']);
        $user = Auth::user();

        $isMember = $this->jeClenemTymu($teamId, $user['id']);
        if (!$isMember) {
            http_response_code(403);
            echo json_encode(['error' => 'Access denied']);
            return;
        }

        // vytvoří zprávu
        $messageId = $this->chatRepository->sendMessage($teamId, $user['id'], $content);

        header('Content-Type: application/json');
        echo json_encode([
            'success' => true,
            'message_id' => $messageId
        ]);
    }

    //smaže zprávu
    public function delete(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            http_response_code(405);
            echo json_encode(['error' => 'Method not allowed']);
            return;
        }

        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['message_id'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing message_id']);
            return;
        }

        $messageId = (int)$data['message_id'];
        $user = Auth::user();
        $isAdmin = $user['role'] === 'admin';

        $deleted = $this->chatRepository->deleteMessage($messageId, $user['id'], $isAdmin);

        header('Content-Type: application/json');
        echo json_encode([
            'success' => $deleted
        ]);
    }

    // zjistí jestli je uživatel členem týmu
    private function jeClenemTymu(int $teamId, int $userId): bool
    {
        $user = Auth::user();
        
        // admin má přístup ke všem týmům
        if ($user['role'] === 'admin') {
            return true;
        }

        $pdo = $this->chatRepository->getPdo();
        $stmt = $pdo->prepare(
            "SELECT COUNT(*) as cnt FROM clenove_tymu 
             WHERE tym_id = :tym_id AND uzivatel_id = :uid"
        );
        $stmt->execute([
            ':tym_id' => $teamId,
            ':uid' => $userId
        ]);

        $result = $stmt->fetch(\PDO::FETCH_ASSOC);
        return (int)($result['cnt'] ?? 0) > 0;
    }
}
