<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['POST']);
$user = hw_auth_user();
if (!$user) hw_json(['success' => false, 'message' => 'Unauthorized'], 401);

$input = hw_input_json();
$appointmentId = (int)($input['appointment_id'] ?? 0);

if ($appointmentId <= 0) hw_json(['success' => false, 'message' => 'appointment_id is required'], 422);

try {
    $pdo = hw_db();
    
    // Verify appointment exists and user has access
    $stmt = $pdo->prepare("
        SELECT a.*, c.user_id as coach_user_id 
        FROM appointments a 
        JOIN coaches c ON a.coach_id = c.id 
        WHERE a.id = ? AND (a.user_id = ? OR c.user_id = ?)
    ");
    $stmt->execute([$appointmentId, (int)$user['sub'], (int)$user['sub']]);
    $appointment = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$appointment) {
        hw_json(['success' => false, 'message' => 'Appointment not found or access denied'], 404);
    }
    
    // Check if session already exists
    $stmt = $pdo->prepare("SELECT * FROM video_sessions WHERE appointment_id = ?");
    $stmt->execute([$appointmentId]);
    $existingSession = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($existingSession) {
        hw_json([
            'success' => true,
            'session_id' => $existingSession['id'],
            'session_token' => $existingSession['session_token'],
            'room_id' => $existingSession['room_id'],
            'status' => $existingSession['status']
        ]);
    }
    
    // Create new video session
    $sessionToken = bin2hex(random_bytes(32));
    $roomId = 'room_' . $appointmentId . '_' . time();
    
    $stmt = $pdo->prepare("
        INSERT INTO video_sessions (appointment_id, session_token, room_id, status) 
        VALUES (?, ?, ?, 'scheduled')
    ");
    $stmt->execute([$appointmentId, $sessionToken, $roomId]);
    $sessionId = (int)$pdo->lastInsertId();
    
    // Add participants
    $isCoach = $appointment['coach_user_id'] == (int)$user['sub'];
    
    // Add current user
    $stmt = $pdo->prepare("
        INSERT INTO session_participants (session_id, user_id, role) 
        VALUES (?, ?, ?)
    ");
    $stmt->execute([$sessionId, (int)$user['sub'], $isCoach ? 'host' : 'participant']);
    
    // Add other participant
    $otherUserId = $isCoach ? $appointment['user_id'] : $appointment['coach_user_id'];
    $stmt->execute([$sessionId, $otherUserId, $isCoach ? 'participant' : 'host']);
    
    // Audit log
    $pdo->prepare('INSERT INTO audit_logs (user_id, action, meta) VALUES (?, ?, JSON_OBJECT("session_id", ?, "appointment_id", ?))')
        ->execute([(int)$user['sub'], 'video_session_created', $sessionId, $appointmentId]);
    
    hw_json([
        'success' => true,
        'session_id' => $sessionId,
        'session_token' => $sessionToken,
        'room_id' => $roomId,
        'status' => 'scheduled'
    ]);
} catch (Throwable $e) {
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}