<?php
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';

$video_id = $_GET['id'] ?? '';

if (empty($video_id)) {
    die("Invalid video ID.");
}

// Basic protection: check if session indicates payment success
if (!isset($_SESSION['paid'][$video_id]) || $_SESSION['paid'][$video_id] !== true) {
    // Alternatively, if they are the owner, let them watch it
    if(isset($_SESSION['user_id'])) {
        $stmt = $pdo->prepare("SELECT user_id FROM videos WHERE id = ?");
        $stmt->execute([$video_id]);
        $vid = $stmt->fetch();
        if(!$vid || $vid['user_id'] != $_SESSION['user_id']) {
            die("Access Denied. You have not paid for this video.");
        }
    } else {
        die("Access Denied. You have not paid for this video.");
    }
}

try {
    $stmt = $pdo->prepare("SELECT * FROM videos WHERE id = ?");
    $stmt->execute([$video_id]);
    $video = $stmt->fetch();
    
    if (!$video) die("Video not found.");
    
    // Increment view count since they are watching
    if(!isset($_SESSION['viewed'][$video_id])) {
        $stmt = $pdo->prepare("UPDATE videos SET views = views + 1 WHERE id = ?");
        $stmt->execute([$video_id]);
        $_SESSION['viewed'][$video_id] = true;
    }

} catch (PDOException $e) {
    die("Database Error.");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($video['title']) ?> - Watch</title>
    <style>
        body { margin: 0; padding: 0; background: #000; color: #fff; font-family: sans-serif; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; }
        video { max-width: 100%; max-height: 80vh; outline: none; background: #111; border-radius: 8px; box-shadow: 0 4px 20px rgba(0,0,0,0.5); }
        h1 { margin-top: 20px; font-size: 1.5rem; text-align: center; }
        .back-btn { margin-top: 15px; color: #aaa; text-decoration: none; font-size: 0.9rem; }
        .back-btn:hover { color: #fff; }
    </style>
</head>
<body>
    <video src="<?= htmlspecialchars($video['video_url']) ?>" controls autoplay controlsList="nodownload"></video>
    <h1><?= htmlspecialchars($video['title']) ?></h1>
    <a href="v.php" class="back-btn">&larr; Back to Gallery</a>
</body>
</html>

