<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('HTTP/1.1 401 Unauthorized');
    echo "You must be logged in to view files.";
    exit();
}

$user_id = $_SESSION['user_id'];

// Check if file ID is provided
if (!isset($_GET['file_id']) || empty($_GET['file_id'])) {
    header('HTTP/1.1 400 Bad Request');
    echo "File ID is required.";
    exit();
}

$file_id = intval($_GET['file_id']);

// Fetch file information
$file_sql = "SELECT f.file_id, f.file_name, f.file_path, f.file_type, f.file_extension, f.uploaded_by, f.is_deleted 
            FROM file_manager f 
            WHERE f.file_id = ?";

$file_stmt = $conn->prepare($file_sql);
$file_stmt->bind_param("i", $file_id);
$file_stmt->execute();
$file_result = $file_stmt->get_result();

if ($file_result->num_rows === 0) {
    header('HTTP/1.1 404 Not Found');
    echo "File not found.";
    exit();
}

$file = $file_result->fetch_assoc();
$file_stmt->close();

// Check if file is deleted
if ($file['is_deleted']) {
    header('HTTP/1.1 404 Not Found');
    echo "This file has been deleted.";
    exit();
}

// Check if user has access to the file
$access_sql = "SELECT 1 FROM file_manager f 
              LEFT JOIN file_shares fs ON (f.file_id = fs.file_id)
              WHERE f.file_id = ? AND 
              (f.uploaded_by = ? OR 
               fs.shared_with = ? OR 
               f.is_public = 1)";

$access_stmt = $conn->prepare($access_sql);
$access_stmt->bind_param("iii", $file_id, $user_id, $user_id);
$access_stmt->execute();
$access_result = $access_stmt->get_result();

// Allow access if the user is an admin (role_id = 1)
$is_admin = false;
$role_sql = "SELECT role_id FROM users WHERE user_id = ?";
$role_stmt = $conn->prepare($role_sql);
$role_stmt->bind_param("i", $user_id);
$role_stmt->execute();
$role_result = $role_stmt->get_result();

if ($role_result->num_rows > 0) {
    $role = $role_result->fetch_assoc();
    if ($role['role_id'] == 1) {
        $is_admin = true;
    }
}
$role_stmt->close();

if ($access_result->num_rows === 0 && !$is_admin) {
    header('HTTP/1.1 403 Forbidden');
    echo "You don't have permission to view this file.";
    exit();
}

$access_stmt->close();

// Check if file exists on the server
if (!file_exists($file['file_path'])) {
    header('HTTP/1.1 404 Not Found');
    echo "File not found on server.";
    exit();
}

// Log the view
$log_sql = "INSERT INTO file_access_logs (file_id, user_id, access_type, ip_address) 
           VALUES (?, ?, 'view', ?)";
$log_stmt = $conn->prepare($log_sql);
$ip_address = $_SERVER['REMOTE_ADDR'];
$log_stmt->bind_param("iis", $file_id, $user_id, $ip_address);
$log_stmt->execute();
$log_stmt->close();

// Close database connection before sending the file
$conn->close();

// Define viewable file extensions
$viewable_extensions = ['pdf', 'jpg', 'jpeg', 'png', 'gif', 'txt'];
$file_extension = strtolower($file['file_extension']);

// Check if the file is viewable
if (!in_array($file_extension, $viewable_extensions)) {
    header('HTTP/1.1 400 Bad Request');
    echo "This file type cannot be previewed.";
    exit();
}

// Set appropriate headers based on file type
switch ($file_extension) {
    case 'pdf':
        header('Content-Type: application/pdf');
        break;
    case 'jpg':
    case 'jpeg':
        header('Content-Type: image/jpeg');
        break;
    case 'png':
        header('Content-Type: image/png');
        break;
    case 'gif':
        header('Content-Type: image/gif');
        break;
    case 'txt':
        header('Content-Type: text/plain');
        break;
    default:
        header('Content-Type: ' . $file['file_type']);
}

// For PDF files, we might want to allow viewing inline
if ($file_extension === 'pdf') {
    header('Content-Disposition: inline; filename="' . basename($file['file_name']) . '"');
} else {
    // For other files, just display them without prompting download
    header('Content-Disposition: inline');
}

header('Content-Transfer-Encoding: binary');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: public');
header('Expires: 0');

// Read and output file
readfile($file['file_path']);
exit();
?>