<?php
// Zoom webhook endpoint for recording.completed events

require_once __DIR__ . '/../../config/database.php';

header('Content-Type: application/json');

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

$event = $data['event'] ?? '';

// Handle Zoom URL validation for webhooks
if ($event === 'endpoint.url_validation') {
    $payload = $data['payload'] ?? [];
    $plainToken = $payload['plainToken'] ?? '';
    $encryptedToken = '';

    if (defined('ZOOM_WEBHOOK_SECRET') && ZOOM_WEBHOOK_SECRET && $plainToken !== '') {
        $encryptedToken = hash_hmac('sha256', $plainToken, ZOOM_WEBHOOK_SECRET);
    }

    echo json_encode([
        'plainToken' => $plainToken,
        'encryptedToken' => $encryptedToken,
    ]);
    exit;
}

// Basic auth using a shared secret token in Authorization header
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if (!defined('ZOOM_WEBHOOK_SECRET') || !ZOOM_WEBHOOK_SECRET || $authHeader !== 'Bearer ' . ZOOM_WEBHOOK_SECRET) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

if ($event !== 'recording.completed') {
    echo json_encode(['success' => true, 'message' => 'Ignored event']);
    exit;
}

$object = $data['payload']['object'] ?? [];
$meetingId = $object['id'] ?? null;
if (!$meetingId) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing meeting ID']);
    exit;
}

try {
    $db = Database::getInstance();

    $lesson = $db->get("SELECT * FROM course_lessons WHERE zoom_meeting_id = ? LIMIT 1", [$meetingId]);
    if (!$lesson) {
        // Nothing to link to; acknowledge anyway.
        echo json_encode(['success' => true, 'message' => 'No matching lesson for meeting']);
        exit;
    }

    $courseId = (int)$lesson['course_id'];
    $moduleId = $lesson['module_id'] ?? null;

    $recordings = $object['recording_files'] ?? [];
    $created = 0;

    foreach ($recordings as $file) {
        $fileType = $file['file_type'] ?? '';
        if (strtoupper($fileType) !== 'MP4') {
            continue;
        }

        $playUrl = $file['play_url'] ?? ($file['download_url'] ?? null);
        if (!$playUrl) {
            continue;
        }

        // Avoid duplicates if webhook is delivered multiple times
        $existing = $db->get(
            "SELECT id FROM course_lessons WHERE course_id = ? AND content_type = 'video' AND content_url = ? LIMIT 1",
            [$courseId, $playUrl]
        );
        if ($existing) {
            continue;
        }

        $recTitle = ($lesson['title'] ?? 'Live Session') . ' (Recording)';
        $desc = 'Zoom cloud recording for session: ' . ($lesson['title'] ?? '');

        $db->query(
            "INSERT INTO course_lessons (module_id, course_id, title, description, content_type, content_url, is_published) VALUES (?, ?, ?, ?, 'video', ?, 1)",
            [$moduleId, $courseId, $recTitle, $desc, $playUrl]
        );
        $created++;
    }

    echo json_encode(['success' => true, 'recordings_added' => $created]);
    exit;
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    exit;
}
