<?php
// Zoom helper functions for SmartThink LMS

if (!function_exists('zoom_set_last_error')) {
    function zoom_set_last_error(string $message): void {
        $GLOBALS['ZOOM_LAST_ERROR'] = $message;
    }
}

if (!function_exists('zoom_last_error')) {
    function zoom_last_error(): ?string {
        return isset($GLOBALS['ZOOM_LAST_ERROR']) ? (string)$GLOBALS['ZOOM_LAST_ERROR'] : null;
    }
}

if (!function_exists('zoom_is_configured')) {
    function zoom_is_configured(): bool {
        return defined('ZOOM_ACCOUNT_ID') && ZOOM_ACCOUNT_ID &&
               defined('ZOOM_CLIENT_ID') && ZOOM_CLIENT_ID &&
               defined('ZOOM_CLIENT_SECRET') && ZOOM_CLIENT_SECRET;
    }
}

if (!function_exists('zoom_get_access_token')) {
    function zoom_get_access_token(): ?string {
        if (!zoom_is_configured()) {
            return null;
        }

        $url = 'https://zoom.us/oauth/token?grant_type=account_credentials&account_id=' . urlencode(ZOOM_ACCOUNT_ID);
        $auth = base64_encode(ZOOM_CLIENT_ID . ':' . ZOOM_CLIENT_SECRET);

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Authorization: Basic ' . $auth,
                'Content-Type: application/x-www-form-urlencoded',
            ],
        ]);

        $response = curl_exec($ch);
        $errno = curl_errno($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if ($errno) {
            $msg = 'Zoom OAuth error: ' . $error;
            zoom_set_last_error($msg);
            error_log($msg);
            return null;
        }

        $data = json_decode($response, true);
        if (!is_array($data) || empty($data['access_token'])) {
            $detail = null;
            if (is_array($data)) {
                if (isset($data['reason'])) {
                    $detail = $data['reason'];
                } elseif (isset($data['error'])) {
                    $detail = $data['error'];
                }
            }

            $msg = 'Zoom OAuth invalid response';
            if ($detail) {
                $msg .= ': ' . $detail;
            }

            zoom_set_last_error($msg);
            error_log($msg . ' Raw: ' . $response);
            return null;
        }

        return $data['access_token'];
    }
}

if (!function_exists('zoom_create_meeting')) {
    /**
     * Create a Zoom meeting for a course live session.
     *
     * @param string $topic
     * @param string $startTime ISO 8601 date-time in UTC or with timezone, e.g. 2026-02-20T19:00:00Z
     * @param int    $durationMinutes
     * @param string $hostId Zoom user ID or email ("me" is allowed for account default)
     * @param array  $options Additional Zoom API options
     *
     * @return array|null Decoded Zoom meeting response or null on failure
     */
    function zoom_create_meeting(string $topic, string $startTime, int $durationMinutes, string $hostId = 'me', array $options = []): ?array {
        $token = zoom_get_access_token();
        if (!$token) {
            return null;
        }

        $base = defined('ZOOM_API_BASE') ? ZOOM_API_BASE : 'https://api.zoom.us/v2';
        $url = rtrim($base, '/') . '/users/' . rawurlencode($hostId) . '/meetings';

        $body = array_merge([
            'topic' => $topic,
            'type' => 2, // scheduled meeting
            'start_time' => $startTime,
            'duration' => $durationMinutes,
            'timezone' => date_default_timezone_get(),
            'settings' => [
                'join_before_host' => false,
                'waiting_room' => true,
                'auto_recording' => 'cloud',
            ],
        ], $options);

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $token,
                'Content-Type: application/json',
            ],
            CURLOPT_POSTFIELDS => json_encode($body),
        ]);

        $response = curl_exec($ch);
        $errno = curl_errno($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if ($errno) {
            $msg = 'Zoom create meeting error: ' . $error;
            zoom_set_last_error($msg);
            error_log($msg);
            return null;
        }

        $data = json_decode($response, true);
        if (!is_array($data) || empty($data['id'])) {
            $detail = null;
            if (is_array($data)) {
                if (isset($data['message'])) {
                    $detail = $data['message'];
                } elseif (isset($data['reason'])) {
                    $detail = $data['reason'];
                } elseif (isset($data['code'])) {
                    $detail = 'Error code ' . $data['code'];
                }
            }

            $msg = 'Zoom create meeting invalid response';
            if ($detail) {
                $msg .= ': ' . $detail;
            }

            zoom_set_last_error($msg);
            error_log($msg . ' Raw: ' . $response);
            return null;
        }

        return $data;
    }
}
