<?php 
include '../config/config.php'; 
include '../includes/auth.php'; 

$ep_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$user_id = $_SESSION['user_id'];

// 1. FETCH EPISODE & DRAMA DETAILS
$stmt = $pdo->prepare("SELECT e.*, d.title, d.id as drama_id FROM episodes e JOIN dramas d ON e.drama_id = d.id WHERE e.id = ?");
$stmt->execute([$ep_id]);
$ep = $stmt->fetch();

if (!$ep) { header("Location: dashboard.php"); exit(); }

// 2. CHECK IF MEMBER ALREADY RATED THIS EPISODE (Strict One-Time Rule)
$check_stmt = $pdo->prepare("SELECT id FROM ratings WHERE user_id = ? AND episode_id = ?");
$check_stmt->execute([$user_id, $ep_id]);
$already_rated = $check_stmt->fetch();

// 3. SAFE AUTOPLAY LOGIC
$iframe_code = $ep['iframe_code'];
if (preg_match('/src="([^"]+)"/', $iframe_code, $match)) {
    $url = $match[1];
    $params = (strpos($url, '?') !== false) ? '&' : '?';
    $params .= "autoplay=1&mute=1&rel=0";
    $new_url = $url . $params;
    $iframe_code = str_replace($url, $new_url, $iframe_code);
    if (strpos($iframe_code, 'allow="') === false) {
        $iframe_code = str_replace('<iframe ', '<iframe allow="autoplay; encrypted-media" ', $iframe_code);
    } else {
        $iframe_code = str_replace('allow="', 'allow="autoplay; ', $iframe_code);
    }
}

// 4. FETCH DYNAMIC PARAMETERS
$param_stmt = $pdo->query("SELECT * FROM rating_parameters ORDER BY id ASC");
$parameters = $param_stmt->fetchAll();

// 5. HANDLE EVALUATION SUBMISSION
if (isset($_POST['submit_evaluation']) && !$already_rated) {
    $drama_id = (int)$_POST['drama_id'];
    $scores = $_POST['param_scores']; 
    $overall_score = array_sum($scores);

    try {
        $pdo->beginTransaction();
        
        // Use standard INSERT to prevent overwriting
        $sql_rating = "INSERT INTO ratings (user_id, drama_id, episode_id, score) VALUES (?, ?, ?, ?)";
        $stmt_rating = $pdo->prepare($sql_rating);
        $stmt_rating->execute([$user_id, $drama_id, $ep_id, $overall_score]);
        
        $rating_id = $pdo->lastInsertId();

        $stmt_val = $pdo->prepare("INSERT INTO rating_values (rating_id, parameter_id, score) VALUES (?, ?, ?)");
        foreach ($scores as $p_id => $score_val) { 
            $stmt_val->execute([$rating_id, $p_id, $score_val]); 
        }

        $pdo->commit();
        $success_msg = "Audit Submitted Successfully!";
        $already_rated = true; // Update state to hide form immediately
    } catch (Exception $e) { 
        $pdo->rollBack(); 
        $error_msg = "Error: You might have already rated this episode."; 
    }
}

include '../includes/header.php'; 
?>

<div class="container mt-4 mb-5">
    <div class="row">
        <div class="col-lg-8">
            <div class="d-flex justify-content-between align-items-end mb-3">
                <div>
                    <h2 class="text-white fw-bold mb-0"><?= htmlspecialchars($ep['title']) ?></h2>
                    <p class="text-danger fw-bold mb-0">Episode <?= $ep['ep_number'] ?></p>
                </div>
                <div class="text-white-50 small">
                    <span class="badge bg-dark border border-secondary p-2">
                        <i class="bi bi-eye-fill text-danger me-1"></i> 
                        WATCHING: <span id="timer_display" class="text-white">0s</span>
                    </span>
                </div>
            </div>
            
            <div class="ratio ratio-16x9 shadow-lg rounded overflow-hidden border border-secondary bg-black mb-4">
                <?= $iframe_code ?>
            </div>
        </div>

        <div class="col-lg-4">
            <h4 class="text-white fw-bold mb-3">Episode Evaluation</h4>
            
            <?php if(isset($success_msg)): ?>
                <div class="alert alert-success border-0 small fw-bold mb-3"><?= $success_msg ?></div>
            <?php endif; ?>

            <?php if($already_rated): ?>
                <div class="card bg-dark border-success shadow text-center p-4">
                    <i class="bi bi-patch-check-fill text-success display-4 mb-2"></i>
                    <h5 class="text-white fw-bold">Audit Completed</h5>
                    <p class="text-white-50 small">You have already evaluated this episode. Ratings can only be submitted once per member.</p>
                    <a href="episodes.php?drama_id=<?= $ep['drama_id'] ?>" class="btn btn-outline-light btn-sm mt-2">Return to List</a>
                </div>
            <?php else: ?>
                <div class="card bg-dark border-secondary shadow">
                    <form class="card-body" method="POST" id="evalForm">
                        <input type="hidden" name="drama_id" value="<?= $ep['drama_id'] ?>">
                        <input type="hidden" name="final_watch_time" id="final_watch_time" value="0">
                        
                        <?php foreach ($parameters as $param): ?>
                        <div class="mb-3 border-bottom border-secondary pb-3">
                            <div class="d-flex justify-content-between mb-1">
                                <label class="small text-white-50 fw-bold"><?= htmlspecialchars($param['parameter_name']) ?></label>
                                <span class="badge bg-black border border-secondary text-info">Max: <?= $param['max_marks'] ?></span>
                            </div>
                            <input type="number" name="param_scores[<?= $param['id'] ?>]" class="form-control bg-black text-white border-secondary param-input" max="<?= $param['max_marks'] ?>" min="0" required>
                        </div>
                        <?php endforeach; ?>

                        <div class="bg-black p-3 rounded border border-danger mb-3 text-center">
                            <small class="text-muted d-block small">TOTAL SCORE</small>
                            <span class="h3 fw-bold text-white mb-0"><span id="live_total">0</span> / 100</span>
                        </div>

                        <button type="submit" name="submit_evaluation" class="btn btn-danger w-100 fw-bold py-2">SUBMIT AUDIT</button>
                    </form>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<form id="heartbeatForm" style="display:none;">
    <input type="hidden" name="episode_id" value="<?= $ep_id ?>">
    <input type="hidden" name="drama_id" value="<?= $ep['drama_id'] ?>">
    <input type="hidden" name="watch_time" id="heartbeat_seconds" value="0">
</form>

<script>
let secondsWatched = 0;
const timerDisplay = document.getElementById('timer_display');
const watchTimeInput = document.getElementById('final_watch_time');
const heartbeatInput = document.getElementById('heartbeat_seconds');

setInterval(() => {
    if (document.hasFocus()) {
        secondsWatched++;
        timerDisplay.innerText = secondsWatched + "s";
        if(watchTimeInput) watchTimeInput.value = secondsWatched;
        if(heartbeatInput) heartbeatInput.value = secondsWatched;
    }
}, 1000);

setInterval(() => {
    if(secondsWatched > 5) {
        let formData = new FormData(document.getElementById('heartbeatForm'));
        fetch('save_watch_time.php', { method: 'POST', body: formData });
    }
}, 30000);

document.querySelectorAll('.param-input').forEach(input => {
    input.addEventListener('input', function() {
        let max = parseInt(this.getAttribute('max'));
        if (parseInt(this.value) > max) { this.value = max; }
        calculateTotal();
    });
});

function calculateTotal() {
    let total = 0;
    document.querySelectorAll('.param-input').forEach(input => {
        total += parseInt(input.value) || 0;
    });
    const liveTotal = document.getElementById('live_total');
    if(liveTotal) liveTotal.innerText = total;
}
</script>

<?php include '../includes/footer.php'; ?>