<?php
/**
 * Admin Videos Management
 * Video Portal Management System
 */

require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';

requireAdmin();

$settings = getAllSettings();
$categories = getCategories(false);

$error = '';
$success = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add') {
        $title = sanitize($_POST['title'] ?? '');
        $description = sanitize($_POST['description'] ?? '');
        $videoType = $_POST['video_type'] ?? 'link';
        $videoUrl = sanitize($_POST['video_url'] ?? '');
        $categoryId = intval($_POST['category_id'] ?? 0);
        $status = $_POST['status'] ?? 'active';
        $uploadedFile = $_POST['uploaded_file'] ?? '';
        
        if (empty($title)) {
            $error = 'Please enter a video title';
        } elseif ($videoType === 'link' && empty($videoUrl)) {
            $error = 'Please enter a video URL';
        } elseif ($videoType === 'file' && empty($uploadedFile)) {
            $error = 'Please upload a video file first';
        } else {
            $filePath = null;
            $thumbnail = null;
            
            // Use pre-uploaded file
            if ($videoType === 'file' && !empty($uploadedFile)) {
                $filePath = $uploadedFile;
                $videoUrl = 'assets/uploads/videos/' . $uploadedFile;
            }
            
            // Handle thumbnail upload
            if (empty($error) && isset($_FILES['thumbnail']) && $_FILES['thumbnail']['error'] === UPLOAD_ERR_OK) {
                $thumbDir = __DIR__ . '/../assets/uploads/videos';
                if (!file_exists($thumbDir)) {
                    mkdir($thumbDir, 0755, true);
                }
                $thumbResult = uploadFile($_FILES['thumbnail'], $thumbDir, ['jpg', 'jpeg', 'png', 'gif']);
                if ($thumbResult['success']) {
                    $thumbnail = $thumbResult['filename'];
                }
            }
            
            if (empty($error)) {
                global $pdo;
                try {
                    $stmt = $pdo->prepare("INSERT INTO videos (title, description, video_url, video_type, file_path, thumbnail, category_id, status, created_by) 
                                          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$title, $description, $videoUrl, $videoType, $filePath, $thumbnail, 
                                   $categoryId ?: null, $status, $_SESSION['user_id'] ?? null]);
                    $success = 'Video added successfully';
                } catch (PDOException $e) {
                    $error = 'Failed to add video: ' . $e->getMessage();
                }
            }
        }
    } elseif ($action === 'edit') {
        $id = intval($_POST['id'] ?? 0);
        $title = sanitize($_POST['title'] ?? '');
        $description = sanitize($_POST['description'] ?? '');
        $videoUrl = sanitize($_POST['video_url'] ?? '');
        $categoryId = intval($_POST['category_id'] ?? 0);
        $status = $_POST['status'] ?? 'active';
        
        if (empty($title) || empty($id)) {
            $error = 'Invalid data';
        } else {
            global $pdo;
            try {
                // Get current video data
                $video = getVideoById($id);
                $thumbnail = $video['thumbnail'];
                
                // Handle new thumbnail upload
                if (isset($_FILES['thumbnail']) && $_FILES['thumbnail']['error'] === UPLOAD_ERR_OK) {
                    $thumbDir = __DIR__ . '/../assets/uploads/videos';
                    if (!file_exists($thumbDir)) {
                        mkdir($thumbDir, 0755, true);
                    }
                    $thumbResult = uploadFile($_FILES['thumbnail'], $thumbDir, ['jpg', 'jpeg', 'png', 'gif']);
                    if ($thumbResult['success']) {
                        $thumbnail = $thumbResult['filename'];
                    }
                }
                
                $stmt = $pdo->prepare("UPDATE videos SET title = ?, description = ?, video_url = ?, thumbnail = ?, category_id = ?, status = ? WHERE id = ?");
                $stmt->execute([$title, $description, $videoUrl, $thumbnail, $categoryId ?: null, $status, $id]);
                $success = 'Video updated successfully';
            } catch (PDOException $e) {
                $error = 'Failed to update video: ' . $e->getMessage();
            }
        }
    } elseif ($action === 'delete') {
        $id = intval($_POST['id'] ?? 0);
        if ($id) {
            global $pdo;
            try {
                $stmt = $pdo->prepare("DELETE FROM videos WHERE id = ?");
                $stmt->execute([$id]);
                $success = 'Video deleted successfully';
            } catch (PDOException $e) {
                $error = 'Failed to delete video';
            }
        }
    }
}

// Get search query
$searchQuery = isset($_GET['search']) ? trim($_GET['search']) : '';

// Get all videos (with search)
if (!empty($searchQuery)) {
    global $pdo;
    $searchTerm = '%' . $searchQuery . '%';
    $stmt = $pdo->prepare("SELECT v.*, c.name as category_name, u.username as created_by_name 
                           FROM videos v 
                           LEFT JOIN categories c ON v.category_id = c.id 
                           LEFT JOIN users u ON v.created_by = u.id 
                           WHERE v.title LIKE ? OR v.description LIKE ?
                           ORDER BY v.created_at DESC");
    $stmt->execute([$searchTerm, $searchTerm]);
    $videos = $stmt->fetchAll();
} else {
    $videos = getVideos(null, null);
}

$siteName = $settings['site_name'] ?? 'Video Portal';
$portalLogo = $settings['portal_logo'] ?? '';
$rtl = $settings['rtl_direction'] ?? '0';
?>
<!DOCTYPE html>
<html lang="<?php echo $rtl == '1' ? 'he' : 'en'; ?>" dir="<?php echo $rtl == '1' ? 'rtl' : 'ltr'; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Videos - <?php echo htmlspecialchars($siteName); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../assets/css/style.css">
    <?php if (!empty($settings['primary_color'])): ?>
    <style>
        :root {
            --primary-color: <?php echo $settings['primary_color']; ?>;
            --secondary-color: <?php echo $settings['secondary_color'] ?? '#2c3e50'; ?>;
            --sidebar-color: <?php echo $settings['sidebar_color'] ?? '#1e272e'; ?>;
        }
        
        /* Upload Zone Styles */
        .upload-zone {
            border: 2px dashed #ddd;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
            background: #f9f9f9;
            transition: all 0.3s;
            cursor: pointer;
        }
        
        .upload-zone:hover, .upload-zone.dragover {
            border-color: var(--primary-color);
            background: #f0f7ff;
        }
        
        .upload-zone p {
            margin: 5px 0;
            color: #666;
        }
        
        /* Progress Bar Styles */
        .upload-progress {
            text-align: left;
        }
        
        .progress-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .progress-info span:first-child {
            font-weight: 600;
            color: #333;
        }
        
        .progress-bar-container {
            width: 100%;
            height: 20px;
            background: #e9ecef;
            border-radius: 10px;
            overflow: hidden;
            margin-bottom: 8px;
        }
        
        .progress-bar {
            height: 100%;
            width: 0%;
            background: linear-gradient(90deg, var(--primary-color), #2ecc71);
            border-radius: 10px;
            transition: width 0.3s ease;
        }
        
        .progress-details {
            font-size: 13px;
            color: #666;
        }
        
        .upload-complete {
            padding: 20px;
        }
    </style>
    <?php endif; ?>
</head>
<body class="<?php echo $rtl == '1' ? 'rtl' : ''; ?>">
    <div class="portal-wrapper">
        <!-- Sidebar -->
        <aside class="sidebar">
            <div class="sidebar-header">
                <?php if (!empty($portalLogo)): ?>
                    <img src="../assets/uploads/logos/<?php echo $portalLogo; ?>" alt="<?php echo htmlspecialchars($siteName); ?>">
                <?php else: ?>
                    <i class="fas fa-play-circle" style="font-size: 40px;"></i>
                <?php endif; ?>
                <h2>Admin Panel</h2>
            </div>
            
            <ul class="sidebar-menu">
                <li>
                    <a href="dashboard.php">
                        <i class="fas fa-tachometer-alt"></i>
                        <span>Dashboard</span>
                    </a>
                </li>
                
                <li>
                    <a href="videos.php" class="active">
                        <i class="fas fa-video"></i>
                        <span>Videos</span>
                    </a>
                </li>
                
                <li>
                    <a href="categories.php">
                        <i class="fas fa-folder"></i>
                        <span>Categories</span>
                    </a>
                </li>
                
                <li>
                    <a href="users.php">
                        <i class="fas fa-users"></i>
                        <span>Users</span>
                    </a>
                </li>
                
                <li>
                    <a href="settings.php">
                        <i class="fas fa-cog"></i>
                        <span>Settings</span>
                    </a>
                </li>
                
                <li>
                    <a href="logs.php">
                        <i class="fas fa-file-alt"></i>
                        <span>Upload Logs</span>
                    </a>
                </li>
                
                <div class="menu-divider"></div>
                
                <li>
                    <a href="../index.php">
                        <i class="fas fa-home"></i>
                        <span>Back to Portal</span>
                    </a>
                </li>
                
                <li>
                    <a href="../logout.php">
                        <i class="fas fa-sign-out-alt"></i>
                        <span>Logout</span>
                    </a>
                </li>
            </ul>
        </aside>
        
        <!-- Main Content -->
        <main class="main-content">
            <!-- Top Bar -->
            <div class="top-bar">
                <h1><i class="fas fa-video"></i> Manage Videos</h1>
                
                <button class="btn btn-primary" data-modal="addVideoModal">
                    <i class="fas fa-plus"></i> Add Video
                </button>
            </div>
            
            <?php if ($error): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
                </div>
            <?php endif; ?>
            
            <?php if ($success): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i> <?php echo $success; ?>
                </div>
            <?php endif; ?>
            
            <!-- Videos Table -->
            <div class="card">
                <div class="card-header" style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px;">
                    <h2><i class="fas fa-list"></i> Videos List (<?php echo count($videos); ?>)</h2>
                    <form method="GET" style="display: flex; gap: 10px;">
                        <input type="text" name="search" class="form-control" placeholder="Search videos..." 
                               value="<?php echo htmlspecialchars($searchQuery); ?>" style="width: 250px;">
                        <button type="submit" class="btn btn-primary btn-sm">
                            <i class="fas fa-search"></i>
                        </button>
                        <?php if (!empty($searchQuery)): ?>
                        <a href="videos.php" class="btn btn-secondary btn-sm">
                            <i class="fas fa-times"></i> Clear
                        </a>
                        <?php endif; ?>
                    </form>
                </div>
                <div class="card-body">
                    <?php if (empty($videos)): ?>
                        <div class="empty-state">
                            <i class="fas fa-video-slash"></i>
                            <h3>No Videos</h3>
                            <p>Start by adding your first video</p>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table" id="videosTable">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Title</th>
                                        <th>Category</th>
                                        <th>Type</th>
                                        <th>Downloads</th>
                                        <th>Status</th>
                                        <th>Created</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($videos as $index => $video): ?>
                                    <tr>
                                        <td><?php echo $index + 1; ?></td>
                                        <td><?php echo htmlspecialchars($video['title']); ?></td>
                                        <td><?php echo htmlspecialchars($video['category_name'] ?? '-'); ?></td>
                                        <td>
                                            <span class="badge badge-<?php echo $video['video_type'] === 'link' ? 'info' : 'warning'; ?>">
                                                <?php echo ucfirst($video['video_type']); ?>
                                            </span>
                                        </td>
                                        <td><?php echo number_format($video['download_count']); ?></td>
                                        <td>
                                            <span class="badge badge-<?php echo $video['status'] === 'active' ? 'success' : 'danger'; ?>">
                                                <?php echo ucfirst($video['status']); ?>
                                            </span>
                                        </td>
                                        <td><?php echo formatDate($video['created_at'], 'd/m/Y'); ?></td>
                                        <td>
                                            <div class="actions">
                                                <button class="btn btn-primary btn-sm" 
                                                        onclick="editVideo(<?php echo htmlspecialchars(json_encode($video)); ?>)">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <form method="POST" style="display: inline;" 
                                                      onsubmit="return confirm('Are you sure you want to delete this video?');">
                                                    <input type="hidden" name="action" value="delete">
                                                    <input type="hidden" name="id" value="<?php echo $video['id']; ?>">
                                                    <button type="submit" class="btn btn-danger btn-sm">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
    
    <!-- Add Video Modal -->
    <div class="modal-overlay" id="addVideoModal">
        <div class="modal">
            <div class="modal-header">
                <h3><i class="fas fa-plus"></i> Add New Video</h3>
                <button class="modal-close">&times;</button>
            </div>
            <form id="addVideoForm" method="POST" enctype="multipart/form-data">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add">
                    <input type="hidden" name="uploaded_file" id="uploaded_file_path" value="">
                    
                    <div class="form-group">
                        <label>Title *</label>
                        <input type="text" name="title" id="add_title" class="form-control" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Description</label>
                        <textarea name="description" class="form-control" rows="3"></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label>Video Type</label>
                        <select name="video_type" id="video_type" class="form-control">
                            <option value="link">External Link</option>
                            <option value="file">Upload File</option>
                        </select>
                    </div>
                    
                    <div class="form-group" id="link-group">
                        <label>Video URL *</label>
                        <input type="url" name="video_url" id="video_url" class="form-control" placeholder="https://...">
                    </div>
                    
                    <div class="form-group" id="file-group" style="display: none;">
                        <label>Video File</label>
                        <div class="upload-zone" id="upload-zone">
                            <input type="file" name="video_file" id="video_file" class="form-control" 
                                   accept=".mp4,.avi,.mov,.mkv,.wmv,.flv,.webm,.zip,.rar" style="display:none;">
                            <div class="upload-placeholder" id="upload-placeholder">
                                <i class="fas fa-cloud-upload-alt" style="font-size: 40px; color: #aaa; margin-bottom: 10px;"></i>
                                <p>Click to select file or drag & drop</p>
                                <small style="color: #888;">MP4, AVI, MOV, MKV, WMV, FLV, WEBM, ZIP, RAR (max 100MB)</small>
                            </div>
                            <div class="upload-selected" id="upload-selected" style="display: none;">
                                <i class="fas fa-file-video" style="font-size: 30px; color: var(--primary-color); margin-bottom: 10px;"></i>
                                <p id="selected-filename" style="font-weight: 600;"></p>
                                <p id="selected-filesize" style="color: #666; font-size: 13px;"></p>
                                <button type="button" class="btn btn-success btn-sm" id="approve-upload" style="margin-top: 10px;">
                                    <i class="fas fa-check"></i> Approve & Upload
                                </button>
                                <button type="button" class="btn btn-secondary btn-sm" id="change-file" style="margin-top: 10px;">
                                    <i class="fas fa-redo"></i> Change
                                </button>
                            </div>
                            <div class="upload-progress" id="upload-progress" style="display: none;">
                                <div class="progress-info">
                                    <span id="progress-filename"></span>
                                    <span id="progress-percent">0%</span>
                                </div>
                                <div class="progress-bar-container">
                                    <div class="progress-bar" id="progress-bar"></div>
                                </div>
                                <div class="progress-details">
                                    <span id="progress-loaded">0 MB</span> / <span id="progress-total">0 MB</span>
                                    <span id="progress-speed" style="margin-left: 15px;"></span>
                                </div>
                            </div>
                            <div class="upload-complete" id="upload-complete" style="display: none;">
                                <i class="fas fa-check-circle" style="font-size: 40px; color: #27ae60; margin-bottom: 10px;"></i>
                                <p style="color: #27ae60; font-weight: 600;">Upload Complete!</p>
                                <p id="complete-filename" style="color: #666;"></p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>Thumbnail Image</label>
                        <input type="file" name="thumbnail" class="form-control" accept="image/*">
                    </div>
                    
                    <div class="form-group">
                        <label>Category</label>
                        <select name="category_id" class="form-control">
                            <option value="">-- Select Category --</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat['id']; ?>"><?php echo htmlspecialchars($cat['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Status</label>
                        <select name="status" class="form-control">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" id="save-video-btn">
                        <i class="fas fa-save"></i> Save Video
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Edit Video Modal -->
    <div class="modal-overlay" id="editVideoModal">
        <div class="modal">
            <div class="modal-header">
                <h3><i class="fas fa-edit"></i> Edit Video</h3>
                <button class="modal-close">&times;</button>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <div class="modal-body">
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="id" id="edit_id">
                    
                    <div class="form-group">
                        <label>Title *</label>
                        <input type="text" name="title" id="edit_title" class="form-control" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Description</label>
                        <textarea name="description" id="edit_description" class="form-control" rows="3"></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label>Video URL</label>
                        <input type="text" name="video_url" id="edit_video_url" class="form-control">
                    </div>
                    
                    <div class="form-group">
                        <label>Thumbnail Image</label>
                        <input type="file" name="thumbnail" class="form-control" accept="image/*">
                        <small style="color: #666;">Leave empty to keep current thumbnail</small>
                    </div>
                    
                    <div class="form-group">
                        <label>Category</label>
                        <select name="category_id" id="edit_category_id" class="form-control">
                            <option value="">-- Select Category --</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat['id']; ?>"><?php echo htmlspecialchars($cat['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Status</label>
                        <select name="status" id="edit_status" class="form-control">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Update Video
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Mobile Toggle -->
    <button class="mobile-toggle">
        <i class="fas fa-bars"></i>
    </button>
    
    <script src="../assets/js/script.js"></script>
    <script>
        function editVideo(video) {
            document.getElementById('edit_id').value = video.id;
            document.getElementById('edit_title').value = video.title;
            document.getElementById('edit_description').value = video.description || '';
            document.getElementById('edit_video_url').value = video.video_url;
            document.getElementById('edit_category_id').value = video.category_id || '';
            document.getElementById('edit_status').value = video.status;
            openModal('editVideoModal');
        }
        
        // Video type toggle
        document.getElementById('video_type').addEventListener('change', function() {
            var linkGroup = document.getElementById('link-group');
            var fileGroup = document.getElementById('file-group');
            
            if (this.value === 'file') {
                linkGroup.style.display = 'none';
                fileGroup.style.display = 'block';
                document.getElementById('video_url').removeAttribute('required');
            } else {
                linkGroup.style.display = 'block';
                fileGroup.style.display = 'none';
                document.getElementById('video_url').setAttribute('required', 'required');
            }
        });
        
        // File Upload with Progress
        (function() {
            var uploadZone = document.getElementById('upload-zone');
            var fileInput = document.getElementById('video_file');
            var placeholder = document.getElementById('upload-placeholder');
            var selected = document.getElementById('upload-selected');
            var progressDiv = document.getElementById('upload-progress');
            var completeDiv = document.getElementById('upload-complete');
            var approveBtn = document.getElementById('approve-upload');
            var changeBtn = document.getElementById('change-file');
            var uploadedFilePath = document.getElementById('uploaded_file_path');
            var selectedFile = null;
            var uploadStartTime = null;
            
            // Click to select file
            uploadZone.addEventListener('click', function(e) {
                if (e.target === approveBtn || e.target === changeBtn || 
                    e.target.closest('#approve-upload') || e.target.closest('#change-file')) {
                    return;
                }
                if (completeDiv.style.display !== 'none') return;
                if (progressDiv.style.display !== 'none') return;
                fileInput.click();
            });
            
            // Drag and drop
            uploadZone.addEventListener('dragover', function(e) {
                e.preventDefault();
                uploadZone.classList.add('dragover');
            });
            
            uploadZone.addEventListener('dragleave', function() {
                uploadZone.classList.remove('dragover');
            });
            
            uploadZone.addEventListener('drop', function(e) {
                e.preventDefault();
                uploadZone.classList.remove('dragover');
                if (e.dataTransfer.files.length > 0) {
                    handleFileSelect(e.dataTransfer.files[0]);
                }
            });
            
            // File selected
            fileInput.addEventListener('change', function() {
                if (this.files.length > 0) {
                    handleFileSelect(this.files[0]);
                }
            });
            
            function handleFileSelect(file) {
                var allowedTypes = ['mp4', 'avi', 'mov', 'mkv', 'wmv', 'flv', 'webm', 'zip', 'rar'];
                var ext = file.name.split('.').pop().toLowerCase();
                
                if (!allowedTypes.includes(ext)) {
                    alert('Invalid file type. Allowed: ' + allowedTypes.join(', '));
                    return;
                }
                
                if (file.size > 100 * 1024 * 1024) {
                    alert('File too large. Maximum size is 100MB.');
                    return;
                }
                
                selectedFile = file;
                document.getElementById('selected-filename').textContent = file.name;
                document.getElementById('selected-filesize').textContent = formatFileSize(file.size);
                
                placeholder.style.display = 'none';
                selected.style.display = 'block';
                progressDiv.style.display = 'none';
                completeDiv.style.display = 'none';
            }
            
            // Change file button
            changeBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                resetUpload();
                fileInput.click();
            });
            
            // Approve and upload button
            approveBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                if (!selectedFile) return;
                
                uploadFile(selectedFile);
            });
            
            function uploadFile(file) {
                var formData = new FormData();
                formData.append('video_file', file);
                formData.append('action', 'ajax_upload');
                
                var xhr = new XMLHttpRequest();
                uploadStartTime = Date.now();
                
                // Show progress
                selected.style.display = 'none';
                progressDiv.style.display = 'block';
                document.getElementById('progress-filename').textContent = file.name;
                document.getElementById('progress-total').textContent = formatFileSize(file.size);
                
                xhr.upload.addEventListener('progress', function(e) {
                    if (e.lengthComputable) {
                        var percent = Math.round((e.loaded / e.total) * 100);
                        document.getElementById('progress-bar').style.width = percent + '%';
                        document.getElementById('progress-percent').textContent = percent + '%';
                        document.getElementById('progress-loaded').textContent = formatFileSize(e.loaded);
                        
                        // Calculate speed
                        var elapsed = (Date.now() - uploadStartTime) / 1000;
                        if (elapsed > 0) {
                            var speed = e.loaded / elapsed;
                            document.getElementById('progress-speed').textContent = formatFileSize(speed) + '/s';
                        }
                    }
                });
                
                xhr.addEventListener('load', function() {
                    if (xhr.status === 200) {
                        try {
                            var response = JSON.parse(xhr.responseText);
                            if (response.success) {
                                progressDiv.style.display = 'none';
                                completeDiv.style.display = 'block';
                                document.getElementById('complete-filename').textContent = file.name;
                                uploadedFilePath.value = response.filename;
                            } else {
                                alert('Upload failed: ' + response.error);
                                resetUpload();
                            }
                        } catch (e) {
                            alert('Upload failed: Invalid server response');
                            resetUpload();
                        }
                    } else {
                        alert('Upload failed: Server error');
                        resetUpload();
                    }
                });
                
                xhr.addEventListener('error', function() {
                    alert('Upload failed: Network error');
                    resetUpload();
                });
                
                xhr.open('POST', 'upload_handler.php', true);
                xhr.send(formData);
            }
            
            function resetUpload() {
                selectedFile = null;
                fileInput.value = '';
                uploadedFilePath.value = '';
                placeholder.style.display = 'block';
                selected.style.display = 'none';
                progressDiv.style.display = 'none';
                completeDiv.style.display = 'none';
                document.getElementById('progress-bar').style.width = '0%';
            }
            
            function formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                var k = 1024;
                var sizes = ['Bytes', 'KB', 'MB', 'GB'];
                var i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }
            
            // Reset when modal closes
            document.querySelectorAll('[data-dismiss="modal"], .modal-close').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    setTimeout(resetUpload, 300);
                });
            });
        })();
    </script>
</body>
</html>
