<?php
// This script is intended to be included within admin_dashboard.php,
// ensuring $conn (database connection) is available.

// Check if $conn exists (safety check, typically handled by dashboard)
if (!isset($conn)) {
    // This assumes db_connection.php is in the config/ folder relative to the root dashboard script
    if (file_exists('config/db_connection.php')) {
        require_once 'config/db_connection.php';
    } else {
        echo "<div class='message error'>FATAL ERROR: Database connection configuration file not found.</div>";
        exit();
    }
}

$message = '';
$message_class = '';

// Define maximum file size for videos (100MB in bytes)
$MAX_VIDEO_SIZE = 100 * 1024 * 1024; 

// --- NEW 0. HANDLE VIDEO DELETION LOGIC (FIX) ---
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id']) && is_numeric($_GET['id'])) {
    
    $video_id_to_delete = (int)$_GET['id'];
    
    if (isset($conn)) {
        // Step 1: Get the file path from the database
        $sql_select_path = "SELECT file_path FROM general_videos WHERE video_id = ?";
        if ($stmt_path = $conn->prepare($sql_select_path)) {
            $stmt_path->bind_param("i", $video_id_to_delete);
            $stmt_path->execute();
            $result_path = $stmt_path->get_result();
            
            if ($result_path->num_rows > 0) {
                $video = $result_path->fetch_assoc();
                $file_path = $video['file_path'];
                
                $file_deleted = true;
                if (file_exists($file_path)) {
                    // Step 2: Delete the file from the server
                    if (!unlink($file_path)) {
                        $message = "Error: DB entry removed, but **file system failed to delete the file** '{$file_path}'. Check permissions.";
                        $message_class = 'error';
                        $file_deleted = false;
                    }
                } else {
                    $message = "Warning: File was missing from disk, but DB record will be removed.";
                    $message_class = 'error';
                }
                
                // Step 3: Delete the record from the database
                $sql_delete = "DELETE FROM general_videos WHERE video_id = ?";
                if ($stmt_delete = $conn->prepare($sql_delete)) {
                    $stmt_delete->bind_param("i", $video_id_to_delete);
                    
                    if ($stmt_delete->execute()) {
                        if ($file_deleted || !file_exists($file_path)) {
                            $message = "Success: Video (ID: {$video_id_to_delete}) deleted successfully.";
                            $message_class = 'success';
                        }
                    } else {
                        $message = "Error deleting video from DB: " . $stmt_delete->error;
                        $message_class = 'error';
                    }
                    $stmt_delete->close();
                }
            } else {
                $message = "Error: Video ID {$video_id_to_delete} not found.";
                $message_class = 'error';
            }
            $stmt_path->close();
        } else {
             $message = "Error: DB statement preparation failed for path lookup.";
             $message_class = 'error';
        }
    } else {
        $message = "Error: Database connection not available.";
        $message_class = 'error';
    }
}
// --- END OF DELETE LOGIC ---


// --- 1. HANDLE VIDEO UPLOAD LOGIC ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['upload_video'])) {
    
    // Check if a file was actually uploaded
    if (isset($_FILES['video_file']) && $_FILES['video_file']['error'] === UPLOAD_ERR_OK) {
        
        $file_info = $_FILES['video_file'];
        $file_name_raw = $file_info['name'];
        $file_extension = strtolower(pathinfo($file_name_raw, PATHINFO_EXTENSION));
        $file_size = $file_info['size'];

        // **File Type Validation: Only MP4 and WMV**
        $allowed_extensions = ['mp4', 'wmv'];
        if (!in_array($file_extension, $allowed_extensions)) {
            $message = "Error: File type '{$file_extension}' is not allowed. Only MP4 and WMV files are supported.";
            $message_class = 'error';
        } 
        // **File Size Validation: Max 100MB**
        elseif ($file_size > $MAX_VIDEO_SIZE) {
            $message = "Error: Video size exceeds the maximum limit of 100MB.";
            $message_class = 'error';
        }
        else {
            // FIX: File name uniqueness handling similar to previous scripts
            $path_info = pathinfo($file_name_raw);
            $file_name_base = $path_info['filename'];
            $ext = isset($path_info['extension']) ? $path_info['extension'] : '';

            $timestamp = date('Ymd_His');
            $file_name_unique = $file_name_base . '_' . $timestamp . ($ext ? '.' . $ext : '');

            // Automatically derive file_name from the uploaded file (without extension)
            $file_name = $file_name_base; // Store the clean name in DB
            
            $target_dir = 'uploads/general_videos/';
            $file_path = $target_dir . $file_name_unique; 
            
            // Use the authenticated user's ID for the Foreign Key constraint.
            // Assuming '1' is a fallback Admin ID in the 'users' table
            $uploaded_by_id = $_SESSION['user_id'] ?? 1; 

            // **Database Table: general_videos**
            $sql_insert = "INSERT INTO general_videos (video_name, file_path, file_extension, file_size, uploaded_by) VALUES (?, ?, ?, ?, ?)";

            if ($stmt = $conn->prepare($sql_insert)) {
                // Bind parameters (string, string, string, integer, integer)
                $stmt->bind_param("sssii", $file_name, $file_path, $file_extension, $file_size, $uploaded_by_id);
                
                if ($stmt->execute()) {
                    // FIX: Un-comment and use the file move function for real deployment
                    if (move_uploaded_file($file_info['tmp_name'], $file_path)) {
                        $message = "Success: Video '{$file_name_unique}' uploaded and saved successfully.";
                        $message_class = 'success';
                    } else {
                        // Log database entry but show file system error
                        $message = "Error: DB updated, but **file system failed to save the video** to '{$file_path}'. Check permissions.";
                        $message_class = 'error';
                    }
                } else {
                    $message = "Error uploading video: " . $stmt->error;
                    $message_class = 'error';
                }
                $stmt->close();
            } else {
                $message = "Error: Database preparation failed for upload.";
                $message_class = 'error';
            }
        }
    } else {
        // Handle case where no file was selected or an upload error occurred
        if (isset($_POST['upload_video'])) {
             // Check for PHP max size errors (if file exceeds php.ini limits)
             $upload_error = $_FILES['video_file']['error'] ?? UPLOAD_ERR_NO_FILE;
             if ($upload_error == UPLOAD_ERR_INI_SIZE || $upload_error == UPLOAD_ERR_FORM_SIZE) {
                 $message = "Error: The uploaded file exceeds the server's maximum size limit.";
             } else if ($upload_error == UPLOAD_ERR_NO_FILE) {
                 $message = "Error: Please select a file to upload.";
             } else {
                 $message = "Error: An unknown upload error occurred (Code: {$upload_error}).";
             }
             $message_class = 'error';
        }
    }
}

// --- 2. FETCH ALL VIDEOS FOR DISPLAY ---
$all_videos = [];

if (isset($conn)) {
    // FIX: Added gv.file_path to the SELECT query for the Download and Play buttons
    $sql_fetch = "
        SELECT 
            gv.video_id, 
            gv.video_name, 
            gv.file_path, /* FIX: Added file_path */
            gv.file_extension, 
            gv.file_size,
            u.username AS uploaded_by_name, 
            gv.uploaded_at 
        FROM general_videos gv
        LEFT JOIN users u ON gv.uploaded_by = u.user_id
        ORDER BY gv.uploaded_at DESC
    ";
    
    $result = $conn->query($sql_fetch);

    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $row['uploaded_by'] = $row['uploaded_by_name'] ?? 'N/A';
            // Format size from bytes to MB for display
            $row['display_size'] = round($row['file_size'] / (1024 * 1024), 2) . ' MB';
            $all_videos[] = $row;
        }
    } else {
        $message_fetch = "Error retrieving videos: " . $conn->error;
    }
}
?>

<style>
    /* Styling similar to manage_documents.php */
    .section-header {
        margin-bottom: 25px;
        color: #2c3e50;
    }
    .data-container {
        margin-top: 30px;
    }
    .btn-action { /* General action button style for consistency */
        padding: 5px 10px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        transition: background-color 0.3s;
        margin-right: 5px;
        display: inline-block;
        text-decoration: none;
    }
    .btn-view {
        background-color: #3498db;
        color: white;
    }
    .btn-view:hover {
        background-color: #2980b9;
    }
    .btn-download {
        background-color: #2ecc71;
        color: white;
    }
    .btn-download:hover {
        background-color: #27ae60;
    }
    .btn-delete {
        background-color: #e74c3c;
        color: white;
    }
    .btn-delete:hover {
        background-color: #c0392b;
    }
    .message {
        padding: 10px;
        margin-bottom: 20px;
        border-radius: 4px;
        font-weight: bold;
    }
    .message.success {
        background-color: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }
    .message.error {
        background-color: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }
    .upload-form-group {
        display: flex;
        gap: 10px;
        align-items: flex-end;
    }
    .upload-form-group > div {
        flex-grow: 1;
    }
    .upload-form-group button {
        margin-top: 0;
        padding: 10px 15px;
    }
</style>

<script>
/**
 * Opens a video file in a modal player.
 * @param {string} filePath - The server path to the video.
 */
function openPopup(filePath) {
    const popup = document.getElementById('videoModal');
    const content = document.getElementById('videoContent');

    // Use the HTML5 <video> tag for playback
    let viewerHTML = `
        <video controls style="max-width: 100%; max-height: 80vh; display: block; margin: 0 auto;">
            <source src="${filePath}" type="video/mp4">
            <source src="${filePath}" type="video/wmv">
            Your browser does not support the video tag.
        </video>
    `;

    content.innerHTML = viewerHTML;
    // Ensure the modal is displayed as a flex container to center it
    popup.style.display = 'flex';
}

function closePopup() {
    const popup = document.getElementById('videoModal');
    // Stop video playback when closing the modal
    const videoElement = popup.querySelector('video');
    if (videoElement) {
        videoElement.pause();
        videoElement.currentTime = 0;
    }
    popup.style.display = 'none';
}
</script>

<div class="form-card">
    <h2 class="section-header">Upload New General Video (Max 100MB)</h2>
    
    <?php if ($message): ?>
        <div class="message <?php echo $message_class; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>

    <form method="POST" action="admin_dashboard.php?page=manage_videos" enctype="multipart/form-data">
        <input type="hidden" name="upload_video" value="1">
        
        <div class="upload-form-group">
            <div>
                <label for="video_file">Select Video (MP4 or WMV only)</label>
                                <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $MAX_VIDEO_SIZE; ?>" />
                <input type="file" id="video_file" name="video_file" style="padding-top: 5px;" accept=".mp4, .wmv" required>
            </div>
            
            <button type="submit" class="btn-primary">Upload Video</button>
        </div>
    </form>
</div>

<div class="form-card data-container">
    <h2 class="section-header">Video List</h2>
    
    <?php if (isset($message_fetch)): ?>
        <div class="message error"><?php echo htmlspecialchars($message_fetch); ?></div>
    <?php elseif (!empty($all_videos)): ?>
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Extension</th> 
                    <th>Size</th>
                    <th>Uploaded By</th>
                    <th>Date</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($all_videos as $video): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($video['video_id']); ?></td>
                        <td><?php echo htmlspecialchars($video['video_name']); ?></td> 
                        <td><?php echo htmlspecialchars($video['file_extension']); ?></td>
                        <td><?php echo htmlspecialchars($video['display_size']); ?></td>
                        <td><?php echo htmlspecialchars($video['uploaded_by']); ?></td>
                        <td><?php echo htmlspecialchars(substr($video['uploaded_at'], 0, 10)); ?></td>
                        <td>
                            <a href="<?php echo htmlspecialchars($video['file_path']); ?>" 
							   class="btn-action btn-download" 
							   download="<?php echo htmlspecialchars($video['video_name']); ?>">
								Download
							</a>
                            <button class="btn-action btn-view" onclick="openPopup('<?php echo htmlspecialchars($video['file_path']); ?>')">Play</button>
							
                                                        <a href="admin_dashboard.php?page=manage_videos&action=delete&id=<?php echo (int)$video['video_id']; ?>" 
                               onclick="return confirm('Are you sure you want to delete this video? This cannot be undone.');" 
                               class="btn-action btn-delete">
                                Delete
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php else: ?>
        <p>No videos found in the database. Upload one above to get started.</p>
    <?php endif; ?>
</div>

<div id="videoModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%;
 background-color:rgba(0,0,0,0.8); z-index:9999; justify-content:center; align-items:center;">
    <div style="background:white; padding:20px; border-radius:8px; max-width:90%; max-height:90%; overflow:auto; position:relative;">
        <button onclick="closePopup()" style="position:absolute; top:10px; right:15px; background:red; color:white; border:none; border-radius:4px; padding:5px 10px; cursor:pointer;">X</button>
        <div id="videoContent" style="text-align:center;"></div>
    </div>
</div>