<?php
/**
 * 婚礼环节视频API
 * 功能：获取环节视频关联信息、管理播放进度
 */

require_once __DIR__ . '/../config.php';
header('Content-Type: application/json; charset=utf-8');

$pdo = $GLOBALS['pdo'];
$method = $_SERVER['REQUEST_METHOD'];

function jsonResponse($success, $data = null, $message = '') {
    echo json_encode([
        'success' => $success,
        'data' => $data,
        'message' => $message
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    switch ($method) {
        case 'GET':
            // 获取环节视频列表或单个环节信息
            if (isset($_GET['phase_code'])) {
                // 获取单个环节信息
                $phaseCode = $_GET['phase_code'];
                $stmt = $pdo->prepare("SELECT * FROM wedding_phase_videos WHERE phase_code = ? AND is_active = 1");
                $stmt->execute([$phaseCode]);
                $phase = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if (!$phase) {
                    jsonResponse(false, null, '环节不存在');
                }
                
                // 获取关联的视频信息
                if ($phase['video_asset_id']) {
                    $stmt = $pdo->prepare("SELECT * FROM video_assets WHERE video_id = ?");
                    $stmt->execute([$phase['video_asset_id']]);
                    $video = $stmt->fetch(PDO::FETCH_ASSOC);
                    $phase['video'] = $video;
                }
                
                // 获取用户播放进度
                $userId = $_GET['user_id'] ?? 'anonymous';
                $stmt = $pdo->prepare("SELECT * FROM video_play_progress WHERE user_id = ? AND phase_code = ?");
                $stmt->execute([$userId, $phaseCode]);
                $progress = $stmt->fetch(PDO::FETCH_ASSOC);
                $phase['progress'] = $progress;
                
                jsonResponse(true, $phase);
            } else {
                // 获取所有环节列表
                $stmt = $pdo->query("SELECT phase_code, phase_name, phase_order, start_time, end_time, duration, description, video_asset_id, is_active FROM wedding_phase_videos WHERE is_active = 1 ORDER BY phase_order");
                $phases = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                // 获取用户播放进度
                $userId = $_GET['user_id'] ?? 'anonymous';
                $stmt = $pdo->prepare("SELECT phase_code, current_time, duration, is_completed FROM video_play_progress WHERE user_id = ?");
                $stmt->execute([$userId]);
                $progressList = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                // 构建进度映射
                $progressMap = [];
                foreach ($progressList as $p) {
                    $progressMap[$p['phase_code']] = $p;
                }
                
                // 合并数据
                foreach ($phases as &$phase) {
                    $phase['progress'] = $progressMap[$phase['phase_code']] ?? null;
                }
                
                jsonResponse(true, $phases);
            }
            break;
            
        case 'POST':
            // 更新环节视频关联或保存播放进度
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (isset($input['save_progress'])) {
                // 保存播放进度
                $userId = $input['user_id'] ?? 'anonymous';
                $phaseCode = $input['phase_code'];
                $currentTime = intval($input['current_time']);
                $duration = intval($input['duration']);
                $videoAssetId = $input['video_asset_id'] ?? null;
                $isCompleted = $input['is_completed'] ?? 0;
                
                $stmt = $pdo->prepare("
                    INSERT INTO video_play_progress (user_id, phase_code, video_asset_id, current_time, duration, is_completed, last_played_at)
                    VALUES (?, ?, ?, ?, ?, ?, NOW())
                    ON DUPLICATE KEY UPDATE 
                        video_asset_id = VALUES(video_asset_id),
                        current_time = VALUES(current_time),
                        duration = VALUES(duration),
                        is_completed = VALUES(is_completed),
                        last_played_at = NOW()
                ");
                $stmt->execute([$userId, $phaseCode, $videoAssetId, $currentTime, $duration, $isCompleted]);
                
                jsonResponse(true, null, '进度已保存');
            } elseif (isset($input['update_phase_video'])) {
                // 更新环节关联的视频
                $phaseCode = $input['phase_code'];
                $videoAssetId = $input['video_asset_id'];
                
                $stmt = $pdo->prepare("UPDATE wedding_phase_videos SET video_asset_id = ? WHERE phase_code = ?");
                $stmt->execute([$videoAssetId, $phaseCode]);
                
                jsonResponse(true, null, '视频关联已更新');
            } elseif (isset($input['update_time'])) {
                // 更新环节的时间配置
                $phaseCode = $input['phase_code'];
                $startTime = intval($input['start_time']);
                $endTime = $input['end_time'] !== null ? intval($input['end_time']) : null;
                
                $duration = $endTime !== null ? ($endTime - $startTime) : null;
                
                $stmt = $pdo->prepare("UPDATE wedding_phase_videos SET start_time = ?, end_time = ?, duration = ? WHERE phase_code = ?");
                $stmt->execute([$startTime, $endTime, $duration, $phaseCode]);
                
                jsonResponse(true, null, '时间配置已更新');
            } else {
                jsonResponse(false, null, '未知的请求类型');
            }
            break;
            
        default:
            jsonResponse(false, null, '不支持的请求方法');
    }
} catch (Exception $e) {
    jsonResponse(false, null, '服务器错误: ' . $e->getMessage());
}
