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

$user_id = $_SESSION['user_id'];
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    header('Content-Type: application/json');
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $price = floatval($_POST['price'] ?? 0);
    $fake_views = intval($_POST['fake_views'] ?? 0);
    $status = $_POST['status'] ?? 'active';
    
    // Check if thumbnail base64 is set (auto-captured from JS)
    $thumb_b64 = $_POST['thumbnail_b64'] ?? '';

    if (empty($title)) {
        echo json_encode(['success' => false, 'message' => "Title is required."]); exit;
    }
    
    $video_id = generate_uuid();
    $video_url = '';
    $thumbnail_url = '';
    
    // Save auto-captured base64 thumbnail from JS
    if (!empty($thumb_b64)) {
        $img_parts = explode(";base64,", $thumb_b64);
        if (count($img_parts) == 2) {
            $img_type_aux = explode("image/", $img_parts[0]);
            $img_type = $img_type_aux[1] ?? 'jpeg';
            $img_type = in_array($img_type, ['jpeg', 'png', 'webp']) ? $img_type : 'jpeg';
            $img_base64 = base64_decode($img_parts[1]);
            $thumb_name = 'uploads/thumb_' . $video_id . '.' . $img_type;
            if (file_put_contents(__DIR__ . '/' . $thumb_name, $img_base64)) {
                $thumbnail_url = $thumb_name;
            }
        }
    }
    
    if(isset($_FILES['video'])) {
        if ($_FILES['video']['error'] == UPLOAD_ERR_INI_SIZE || $_FILES['video']['error'] == UPLOAD_ERR_FORM_SIZE) {
             echo json_encode(['success' => false, 'message' => "Video file exceeds upload limit (Check php.ini limit)."]); exit;
        } elseif ($_FILES['video']['error'] == 0) {
            if ($_FILES['video']['size'] > 104857600) {
                 echo json_encode(['success' => false, 'message' => "Video file must be 100MB or less. Tried " . number_format($_FILES['video']['size']/1048576, 1) . "MB"]); exit;
            } else {
                $ext = pathinfo($_FILES['video']['name'], PATHINFO_EXTENSION);
                if (empty($ext)) $ext = 'mp4'; // fallback
                $vid_name = 'uploads/vid_' . $video_id . '.' . $ext;
                if(move_uploaded_file($_FILES['video']['tmp_name'], __DIR__ . '/' . $vid_name)) {
                    $video_url = $vid_name;
                } else {
                     echo json_encode(['success' => false, 'message' => "Failed to move video. Directory permission issue?"]); exit;
                }
            }
        } elseif ($_FILES['video']['error'] != UPLOAD_ERR_NO_FILE) {
             echo json_encode(['success' => false, 'message' => "Video upload error code: " . $_FILES['video']['error']]); exit;
        }
    } else {
        echo json_encode(['success' => false, 'message' => "No video file was uploaded. Max post size limit might have been exceeded."]); exit;
    }

    try {
        $stmt = $pdo->prepare("SELECT MAX(position) FROM videos WHERE user_id = ?");
        $stmt->execute([$user_id]);
        $max_pos = $stmt->fetchColumn();
        $new_pos = ($max_pos !== false && $max_pos !== null) ? intval($max_pos) + 1 : 1;

        $stmt = $pdo->prepare("INSERT INTO videos (id, user_id, title, description, price, video_url, thumbnail_url, status, position, fake_views) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        if ($stmt->execute([$video_id, $user_id, $title, $description, $price, $video_url, $thumbnail_url, $status, $new_pos, $fake_views])) {
            echo json_encode(['success' => true, 'message' => "Video uploaded successfully! Link generated."]); exit;
        } else {
            echo json_encode(['success' => false, 'message' => "Failed to save video to database."]); exit;
        }
    } catch(PDOException $e) {
        echo json_encode(['success' => false, 'message' => "Database Error."]); exit;
    }
}

$site_settings = get_site_settings($pdo);
// Self-healing: add allow_uploads column if missing
try { $pdo->exec("ALTER TABLE site_settings ADD COLUMN `allow_uploads` tinyint(1) DEFAULT 1 AFTER allow_registration"); } catch (PDOException $e2) {}
$uploads_enabled = ($site_settings['allow_uploads'] ?? 1);
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<?php include 'includes/head.php'; ?>
<body>
    <?php include 'includes/sidebar.php'; ?>
    <main class="dashboard-main">
        <?php include 'includes/header.php'; ?>
        <div class="dashboard-main-body">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
                <h6 class="fw-semibold mb-0">Upload Video</h6>
                <ul class="d-flex align-items-center gap-2">
                    <li class="fw-medium">
                        <a href="dashboard.php" class="d-flex align-items-center gap-1 hover-text-primary">
                            <iconify-icon icon="solar:home-smile-angle-outline" class="icon text-lg"></iconify-icon> Dashboard
                        </a>
                    </li>
                    <li>-</li>
                    <li class="fw-medium">Upload</li>
                </ul>
            </div>

            <?php if (!$uploads_enabled): ?>
            <!-- ═══ MAINTENANCE MODE ═══ -->
            <style>
                .maintenance-mode {
                    background: #fff5f5;
                    border: 2px dashed #feb2b2;
                    border-radius: 16px;
                    padding: 60px 20px;
                    text-align: center;
                }
                .maintenance-icon {
                    font-size: 4rem;
                    color: #f56565;
                    margin-bottom: 20px;
                    animation: pulse 2s infinite;
                }
                @keyframes pulse {
                    0% { transform: scale(1); }
                    50% { transform: scale(1.05); }
                    100% { transform: scale(1); }
                }
                .upload-container.disabled {
                    pointer-events: none;
                    filter: grayscale(0.5);
                    opacity: 0.7;
                }
            </style>

            <div class="card basic-data-table border-0 shadow-sm">
                <div class="card-header bg-white d-flex align-items-center justify-content-between py-3">
                    <h5 class="card-title mb-0">Upload Video</h5>
                    <span class="badge bg-danger">Maintenance Mode</span>
                </div>
                <div class="card-body">
                    <div class="maintenance-mode mb-4">
                        <iconify-icon icon="solar:settings-bold-duotone" class="maintenance-icon d-block mx-auto"></iconify-icon>
                        <h3 class="fw-bold text-dark">System Maintenance</h3>
                        <p class="text-muted mx-auto" style="max-width: 500px;">
                            We are currently upgrading our servers to provide you with a faster upload experience.
                            <strong>Video uploads are temporarily disabled.</strong> Please check back in a few hours.
                        </p>
                    </div>

                    <div class="alert alert-warning border-0 d-flex align-items-start mb-4 radius-12" role="alert">
                        <iconify-icon icon="solar:info-circle-bold-duotone" class="text-2xl me-12 flex-shrink-0"></iconify-icon>
                        <div>
                            <p class="mb-1 fw-bold">Note for Creators:</p>
                            <p class="mb-0 small text-muted">While the system is down, please ensure your content follows our community guidelines regarding prohibited content to avoid account suspension once we are back online.</p>
                        </div>
                    </div>

                    <div class="upload-container disabled">
                        <form onsubmit="return false;">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label fw-semibold text-muted">Video Title</label>
                                    <input type="text" class="form-control bg-light" placeholder="Disabled" disabled>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label fw-semibold text-muted">Price (TSH)</label>
                                    <input type="number" class="form-control bg-light" placeholder="0.00" disabled>
                                </div>
                                <div class="col-12">
                                    <div class="p-5 border rounded-3 bg-light text-center" style="border-style: dashed !important;">
                                        <iconify-icon icon="solar:cloud-cross-bold-duotone" class="text-4xl text-muted d-block mx-auto mb-8"></iconify-icon>
                                        <p class="mt-2 mb-0 text-muted">Upload Service Unavailable</p>
                                    </div>
                                </div>
                            </div>
                            <button class="btn btn-secondary w-100 mt-4 py-2 fw-bold" disabled>
                                Service Currently Offline
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <?php else: ?>
            <!-- ═══ NORMAL UPLOAD FORM ═══ -->
            <div id="alertBox" class="alert px-16 py-11 text-sm radius-8" style="display:none;"></div>

            <div class="card radius-12" style="max-width: 800px; margin: 0 auto;">
                <div class="card-header border-bottom">
                    <h6 class="mb-0 text-lg">Upload New Video</h6>
                </div>
                <div class="card-body p-24">
                    <form id="uploadForm" onsubmit="uploadVideo(event)">
                        <div class="mb-20">
                            <label class="form-label fw-semibold text-primary-light text-sm mb-8">Select Video (Auto Thumbnails &amp; Max 100MB)</label>
                            
                            <div class="card border border-2 border-dashed border-neutral-200 bg-neutral-50 radius-12 p-40 text-center cursor-pointer hover-bg-primary-50 transition-2 position-relative">
                                <i class="ri-upload-cloud-2-line text-4xl text-primary-600 mb-8"></i>
                                <p class="text-secondary-light fw-medium mb-0" id="fileNameP">Click to browse or drag and drop video here</p>
                                <input type="file" id="videoFile" accept="video/*" class="position-absolute top-0 start-0 w-100 h-100 opacity-0 cursor-pointer" onchange="extractThumbnail(this)">
                            </div>
                            
                            <img id="thumb-preview" src="" class="mt-16 radius-8 shadow-sm" style="display:none; max-width: 200px;">
                            <input type="hidden" id="thumbnail_b64">
                            
                            <div class="progress mt-16 radius-8 bg-neutral-200" style="height: 10px; display:none;" id="progressBar">
                                <div class="progress-bar bg-primary-600" id="progressFill" style="width: 0%;"></div>
                            </div>
                            <p class="text-sm text-secondary-light mt-8 mb-0" id="progressText" style="display:none;">0%</p>
                        </div>

                        <div class="mb-20">
                            <label class="form-label fw-semibold text-primary-light text-sm mb-8">Video Title</label>
                            <input type="text" id="vidTitle" class="form-control radius-8" placeholder="e.g. Connection ya Mwaka" required>
                        </div>

                        <div class="row mb-20">
                            <div class="col-md-4">
                                <label class="form-label fw-semibold text-primary-light text-sm mb-8">Price (TSH)</label>
                                <input type="number" id="vidPrice" class="form-control radius-8" value="1000" min="0" required>
                            </div>
                            <div class="col-md-4 mt-20 mt-md-0">
                                <label class="form-label fw-semibold text-primary-light text-sm mb-8">Fake Views</label>
                                <input type="number" id="vidFakeViews" class="form-control radius-8" value="0" min="0">
                            </div>
                            <div class="col-md-4 mt-20 mt-md-0">
                                <label class="form-label fw-semibold text-primary-light text-sm mb-8">Status</label>
                                <select id="vidStatus" class="form-control radius-8">
                                    <option value="active">Active (Visible)</option>
                                    <option value="inactive">Inactive (Hidden)</option>
                                </select>
                            </div>
                        </div>

                        <div class="mb-24">
                            <label class="form-label fw-semibold text-primary-light text-sm mb-8">Description (Optional)</label>
                            <textarea id="vidDesc" class="form-control radius-8" rows="4" placeholder="Brief description of the content..."></textarea>
                        </div>

                        <button type="submit" id="submitBtn" class="btn btn-primary-600 radius-8 w-100 py-12"><i class="ri-upload-line"></i> Publish Video</button>
                    </form>
                </div>
            </div>
            <?php endif; ?>
        </div>
        <?php include 'includes/footer.php'; ?>
    </main>


    <script>
        function extractThumbnail(input) {
            if (input.files && input.files[0]) {
                const file = input.files[0];
                document.getElementById('fileNameP').innerText = file.name + ' (' + (file.size / 1024 / 1024).toFixed(2) + ' MB)';

                const videoURL = URL.createObjectURL(file);
                const video = document.createElement('video');
                video.src = videoURL;
                video.muted = true;
                video.crossOrigin = 'anonymous';
                video.preload = 'metadata';

                let timeSeeked = false;

                video.addEventListener('loadedmetadata', function() {
                    // Seek to the start of the video
                    video.currentTime = 0;
                });

                video.addEventListener('seeked', function() {
                    if (timeSeeked) return;
                    timeSeeked = true;

                    const canvas = document.createElement('canvas');
                    canvas.width = video.videoWidth || 1280;
                    canvas.height = video.videoHeight || 720;
                    const ctx = canvas.getContext('2d');
                    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

                    const dataURL = canvas.toDataURL('image/jpeg', 0.8);
                    document.getElementById('thumbnail_b64').value = dataURL;

                    const preview = document.getElementById('thumb-preview');
                    preview.src = dataURL;
                    preview.style.display = 'block';

                    URL.revokeObjectURL(videoURL);
                });
            }
        }

        function uploadVideo(e) {
            e.preventDefault();
            const fileInput = document.getElementById('videoFile');
            if(!fileInput.files.length) {
                showAlert('Please select a video file.', 'alert-warning');
                return;
            }
            if(fileInput.files[0].size > 104857600) {
                showAlert('Video file is larger than 100MB!', 'alert-warning');
                return;
            }

            const submitBtn = document.getElementById('submitBtn');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="ri-loader-4-line ri-spin"></i> Uploading...';
            
            document.getElementById('progressBar').style.display = 'flex';
            document.getElementById('progressText').style.display = 'block';

            const formData = new FormData();
            formData.append('video', fileInput.files[0]);
            formData.append('title', document.getElementById('vidTitle').value);
            formData.append('price', document.getElementById('vidPrice').value);
            formData.append('fake_views', document.getElementById('vidFakeViews').value);
            formData.append('status', document.getElementById('vidStatus').value);
            formData.append('description', document.getElementById('vidDesc').value);
            formData.append('thumbnail_b64', document.getElementById('thumbnail_b64').value);

            const xhr = new XMLHttpRequest();
            xhr.open('POST', 'upload', true);
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            
            xhr.upload.onprogress = function(e) {
                if (e.lengthComputable) {
                    const percentComplete = (e.loaded / e.total) * 100;
                    document.getElementById('progressFill').style.width = percentComplete + '%';
                    document.getElementById('progressText').innerText = Math.round(percentComplete) + '% completed';
                }
            };

            xhr.onload = function() {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="ri-upload-line"></i> Publish Video';
                if (xhr.status == 200) {
                    try {
                        const res = JSON.parse(xhr.responseText);
                        if (res.success) {
                            showAlert(res.message, 'alert-success');
                            setTimeout(() => { window.location.href = 'videos'; }, 1500);
                        } else {
                            showAlert(res.message, 'alert-danger');
                        }
                    } catch(err) {
                        showAlert('Server error occurred during parsing.', 'alert-danger');
                    }
                } else {
                    showAlert('Upload failed. Server responded with ' + xhr.status, 'alert-danger');
                }
            };
            
            xhr.onerror = function() {
                submitBtn.disabled = false;
                showAlert('Network error or file too large for server config.', 'alert-danger');
            };

            xhr.send(formData);
        }

        function showAlert(msg, className) {
            const ab = document.getElementById('alertBox');
            ab.innerText = msg;
            ab.className = 'alert px-16 py-11 text-sm radius-8 ' + className;
            ab.style.display = 'block';
        }
    </script>
</body>
</html>


