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

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

// 1. HANDLE RATING & WATCH TIME SUBMISSION
if (isset($_POST['submit_rating'])) {
    $score = $_POST['score'];
    $review = isset($_POST['review_text']) ? htmlspecialchars($_POST['review_text']) : '';
    $watch_seconds = isset($_POST['watch_time']) ? (int)$_POST['watch_time'] : 0;

    // Use ON DUPLICATE KEY UPDATE to add new watch time to existing time
    $sql = "INSERT INTO ratings (user_id, episode_id, score, review_text, watch_time_seconds) 
            VALUES (?, ?, ?, ?, ?) 
            ON DUPLICATE KEY UPDATE 
            score = VALUES(score), 
            review_text = VALUES(review_text),
            watch_time_seconds = watch_time_seconds + VALUES(watch_time_seconds)";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$user_id, $ep_id, $score, $review, $watch_seconds]);
    $msg = "Evaluation Saved Successfully!";
}

// 2. FETCH EPISODE & DRAMA DETAILS
$stmt = $pdo->prepare("SELECT e.*, d.title 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();
}

// 3. FETCH EXISTING DATA
$checkRating = $pdo->prepare("SELECT * FROM ratings WHERE user_id = ? AND episode_id = ?");
$checkRating->execute([$user_id, $ep_id]);
$current_rating = $checkRating->fetch();
?>

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

<div class="container mt-4 mb-5">
    <div class="row g-4">
        <div class="col-lg-8">
            <h2 class="text-white fw-bold mb-1"><?= $ep['title'] ?></h2>
            <p class="text-white-50 mb-3">Now Reviewing: Episode <?= $ep['ep_number'] ?></p>
            
            <div class="ratio ratio-16x9 shadow-lg rounded overflow-hidden border border-secondary bg-black">
                <?= $ep['iframe_code'] ?>
            </div>
        </div>
        
        <div class="col-lg-4">
            <div class="card bg-dark border-secondary shadow-sm">
                <div class="card-body">
                    <h4 class="text-white text-center mb-1">Evaluate</h4>
                    <p class="text-muted small text-center mb-4">Time spent watching will be recorded.</p>
                    
                    <?php if(isset($msg)): ?>
                        <div class='alert alert-success py-2 small text-center'><?= $msg ?></div>
                    <?php endif; ?>

                    <form method="POST" id="ratingForm">
                        <input type="hidden" name="watch_time" id="watch_time_input" value="0">

                        <label class="form-label text-white-50 small">Score (1 - 10)</label>
                        <div class="d-flex flex-wrap justify-content-center gap-2 mb-4">
                            <?php for($i=1; $i<=10; $i++): ?>
                                <input type="radio" class="btn-check" name="score" id="btn<?= $i ?>" value="<?= $i ?>" 
                                    <?= ($current_rating && $current_rating['score'] == $i) ? 'checked' : '' ?> required>
                                <label class="btn btn-outline-danger btn-sm px-3" for="btn<?= $i ?>"><?= $i ?></label>
                            <?php endfor; ?>
                        </div>

                        <div class="mb-4">
                            <label class="form-label text-white-50 small">Review / Observation</label>
                            <textarea name="review_text" class="form-control bg-dark text-white border-secondary" rows="4" placeholder="Mention technical issues, acting quality, etc..."><?= $current_rating ? $current_rating['review_text'] : '' ?></textarea>
                        </div>

                        <button type="submit" name="submit_rating" class="btn btn-danger w-100 fw-bold py-2">
                            <?= $current_rating ? 'UPDATE EVALUATION' : 'SUBMIT EVALUATION' ?>
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let secondsWatched = 0;
let isTabActive = true;

// Stop counting if user switches tabs
window.onfocus = function() { isTabActive = true; };
window.onblur = function() { isTabActive = false; };

setInterval(() => {
    if (isTabActive) {
        secondsWatched++;
        document.getElementById('watch_time_input').value = secondsWatched;
    }
}, 1000);
</script>

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