<?php
session_start();
require_once 'db_connect.php';

// 1. The Bouncer: Block anyone not logged in
if (!isset($_SESSION['user_id'])) {
    header("HTTP/1.1 403 Forbidden");
    exit("Access Denied");
}

if (!isset($_SESSION['user_id'])) {
    header("HTTP/1.1 400 Bad Request");
    exit("No video ID provided");
}

$video_id = $_GET['id'];
$user_id = $_SESSION['user_id'];

try {
    // 2. Access Control: Role-Based Query Routing
    $role = $_SESSION['role'] ?? 'user'; // Fallback to 'user' if undefined

    // --- UPDATED RBAC: Both admin tiers can view the vault ---
    if (in_array($role, ['admin', 'standard_admin'])) {
        // ADMIN PASS: Admins can view any video in the database
        $stmt = $pdo->prepare("
            SELECT file_path, encryption_status
            FROM VideoMetadata
            WHERE id = :video_id
        ");
        $stmt->execute([':video_id' => $video_id]);
    } else {
        // CLIENT PASS: Regular users can ONLY view their own assigned cameras
        $stmt = $pdo->prepare("
            SELECT vm.file_path, vm.encryption_status
            FROM VideoMetadata vm
            JOIN EdgeNodes en ON vm.edge_node_id = en.id
            WHERE vm.id = :video_id AND en.assigned_user_id = :user_id
        ");
        $stmt->execute([':video_id' => $video_id, ':user_id' => $user_id]);
    }
    
    $video = $stmt->fetch();

    if (!$video) {
        header("HTTP/1.1 404 Not Found");
        exit("Video not found or access revoked.");
    }

    $file_path = __DIR__ . "/../" . $video['file_path'];

    if (!file_exists($file_path)) {
        header("HTTP/1.1 404 Not Found");
        exit("File missing from vault.");
    }

    // 3. Set standard secure video headers
    header('Content-Type: video/mp4');
    header('Cache-Control: no-store, no-cache, must-revalidate');

    // --- 4. THE DECRYPTION ENGINE ---
    if ($video['encryption_status'] === 'encrypted' || pathinfo($file_path, PATHINFO_EXTENSION) === 'enc') {
        
        // Load the locked binary data into memory
        $file_contents = file_get_contents($file_path);
        
        // Extract the Initialization Vector (IV) from the first 16 bytes
        $iv_length = openssl_cipher_iv_length('aes-256-cbc');
        $iv = substr($file_contents, 0, $iv_length);
        
        // Extract the actual scrambled video payload
        $encrypted_data = substr($file_contents, $iv_length);
        
        // Decrypt it on-the-fly using the Master Key
        $decrypted_video = openssl_decrypt($encrypted_data, 'aes-256-cbc', AES_KEY, 0, $iv);
        
        if ($decrypted_video === false) {
            header("HTTP/1.1 500 Internal Server Error");
            exit("Cryptographic failure: Could not unlock video.");
        }

        // Output the clean video bytes directly to the browser
        header('Content-Length: ' . strlen($decrypted_video));
        echo $decrypted_video;
        
    } else {
        // Fallback for older, unencrypted .mp4 test files
        header('Content-Length: ' . filesize($file_path));
        readfile($file_path);
    }
    
    exit();

} catch (PDOException $e) {
    header("HTTP/1.1 500 Internal Server Error");
    exit("System Error.");
}
?>
