<?php

namespace Core\App\Controllers;

use Core\App\Services\VideoMeetingService;

class VideoMeetingController
{
    /* ─────────────────────────────────────────────
       GET /admin/integrations/video-meeting
    ───────────────────────────────────────────── */
    public function settings(): void
    {
        $providers      = VideoMeetingService::loadAll();
        $activeProvider = VideoMeetingService::getActiveProviderKey();

        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/integrations/video_meeting.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    /* ─────────────────────────────────────────────
       POST /admin/integrations/video-meeting/save
    ───────────────────────────────────────────── */
    public function save(): void
    {
        \Core\System\Csrf::check();
        $db             = \db();
        $activeProvider = trim($_POST['active_provider'] ?? 'jitsi');
        $providerList   = ['jitsi', 'daily', 'whereby'];

        foreach ($providerList as $prov) {
            $apiKey   = trim($_POST["{$prov}_api_key"] ?? '');
            $isActive = ($prov === $activeProvider) ? 1 : 0;

            // Build extra config per provider
            $extra = [];
            if ($prov === 'jitsi') {
                $extra['domain']      = trim($_POST['jitsi_domain']       ?? 'meet.jit.si') ?: 'meet.jit.si';
                $extra['room_prefix'] = trim($_POST['jitsi_room_prefix']  ?? 'meeting')     ?: 'meeting';
            } elseif ($prov === 'daily') {
                $extra['subdomain'] = trim($_POST['daily_subdomain'] ?? '');
            }
            // whereby: no extra config needed

            // Preserve cached Whereby rooms if they exist
            if ($prov === 'whereby') {
                try {
                    $old = $db->prepare("SELECT extra FROM video_meeting_settings WHERE provider='whereby' LIMIT 1");
                    $old->execute();
                    $oldRow = $old->fetch(\PDO::FETCH_ASSOC);
                    if ($oldRow) {
                        $oldExtra = json_decode($oldRow['extra'] ?? '{}', true) ?: [];
                        if (!empty($oldExtra['rooms'])) {
                            $extra['rooms'] = $oldExtra['rooms'];
                        }
                    }
                } catch (\Throwable $e) {}
            }

            $extraJson = json_encode($extra, JSON_UNESCAPED_UNICODE);

            // Upsert
            $exists = $db->prepare("SELECT id FROM video_meeting_settings WHERE provider = ? LIMIT 1");
            $exists->execute([$prov]);
            if ($exists->fetchColumn()) {
                $db->prepare("UPDATE video_meeting_settings SET api_key=:k, extra=:e, is_active=:a, updated_at=NOW() WHERE provider=:p")
                   ->execute([':k' => ($apiKey ?: null), ':e' => $extraJson, ':a' => $isActive, ':p' => $prov]);
            } else {
                $db->prepare("INSERT INTO video_meeting_settings (provider, api_key, extra, is_active) VALUES (?,?,?,?)")
                   ->execute([$prov, ($apiKey ?: null), $extraJson, $isActive]);
            }
        }

        $_SESSION['flash_success'] = __('video_meeting.saved', 'Video meeting settings saved successfully');
        header('Location: /admin/integrations/video-meeting');
        exit;
    }

    /* ─────────────────────────────────────────────
       POST /admin/integrations/video-meeting/test
    ───────────────────────────────────────────── */
    public function testConnection(): void
    {
        header('Content-Type: application/json; charset=utf-8');
        $provider = trim($_POST['provider'] ?? '');
        $apiKey   = trim($_POST['api_key']  ?? '');
        $extra    = json_decode($_POST['extra'] ?? '{}', true) ?: [];

        try {
            echo json_encode(VideoMeetingService::testConnection($provider, $apiKey, $extra), JSON_UNESCAPED_UNICODE);
        } catch (\Throwable $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        exit;
    }

    /* ─────────────────────────────────────────────
       GET /admin/team/meetings/video-url/{id}
       Called via AJAX from meeting_room.php
    ───────────────────────────────────────────── */
    public function getRoomUrl(int $id): void
    {
        header('Content-Type: application/json; charset=utf-8');
        try {
            if (!VideoMeetingService::isEnabled()) {
                echo json_encode(['success' => false, 'error' => __('video_meeting.not_configured', 'Video meeting integration is not configured')]);
                exit;
            }
            $url = VideoMeetingService::getRoomUrl($id);
            if (!$url) {
                echo json_encode(['success' => false, 'error' => __('video_meeting.url_failed', 'Could not generate meeting room URL')]);
                exit;
            }
            echo json_encode(['success' => true, 'url' => $url, 'provider' => VideoMeetingService::getActiveProviderKey()]);
        } catch (\Throwable $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        exit;
    }

    /* ─────────────────────────────────────────────
       POST /admin/team/meetings/video-start/{id}
       Gets URL + posts notification message in group chat
    ───────────────────────────────────────────── */
    public function videoStart(int $id): void
    {
        header('Content-Type: application/json; charset=utf-8');
        try {
            if (!VideoMeetingService::isEnabled()) {
                echo json_encode(['success' => false, 'error' => __('video_meeting.not_configured', 'Video meeting integration is not configured')]);
                exit;
            }

            $url = VideoMeetingService::getRoomUrl($id);
            if (!$url) {
                echo json_encode(['success' => false, 'error' => __('video_meeting.url_failed', 'Could not generate meeting room URL')]);
                exit;
            }

            $db      = \db();
            $adminId = (int)($_SESSION['admin_id'] ?? 0);

            /* ── Check: don't spam — skip if same URL was posted in last 3 min ── */
            $recent = $db->prepare("
                SELECT id FROM team_group_messages
                WHERE meeting_id = ? AND sender_id = ? AND content LIKE ?
                  AND created_at >= DATE_SUB(NOW(), INTERVAL 3 MINUTE)
                LIMIT 1
            ");
            $recent->execute([$id, $adminId, '%' . $url . '%']);

            $msg = null;

            if (!$recent->fetchColumn()) {
                /* ── Build message content ── */
                $providerLabels = ['jitsi' => 'Jitsi Meet', 'daily' => 'Daily.co', 'whereby' => 'Whereby'];
                $providerLabel  = $providerLabels[VideoMeetingService::getActiveProviderKey()] ?? 'Video';
                $content = __('video_meeting.chat_notification', '🎥 Video meeting started') . ' (' . $providerLabel . ")\n" . $url;

                /* ── Insert into group chat ── */
                $ins = $db->prepare("
                    INSERT INTO team_group_messages (meeting_id, sender_id, content, created_at)
                    VALUES (?, ?, ?, NOW())
                ");
                $ins->execute([$id, $adminId, $content]);
                $newId = (int)$db->lastInsertId();

                /* ── Fetch full row (with sender info) for appendMessage ── */
                $sel = $db->prepare("
                    SELECT m.id, m.meeting_id, m.sender_id, m.content,
                           m.attachment_path, m.attachment_type, m.attachment_kind,
                           m.attachment_name, m.attachment_size, m.is_pinned, m.created_at,
                           a.username AS sender_name, a.avatar AS sender_avatar
                    FROM team_group_messages m
                    JOIN admins a ON a.id = m.sender_id
                    WHERE m.id = ?
                ");
                $sel->execute([$newId]);
                $msg = $sel->fetch(\PDO::FETCH_ASSOC) ?: null;
            }

            echo json_encode([
                'success'  => true,
                'url'      => $url,
                'provider' => VideoMeetingService::getActiveProviderKey(),
                'message'  => $msg,   // null if skipped (recent duplicate)
            ], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);

        } catch (\Throwable $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        exit;
    }
}
