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

if (!isset($_GET['id'])) {
    die("No video ID provided.");
}

$id = $_GET['id'];
$user_id = $_SESSION['user_id'];

// Check ownership
$stmt = $pdo->prepare("SELECT * FROM videos WHERE id = ? AND user_id = ?");
$stmt->execute([$id, $user_id]);
$video = $stmt->fetch();

if (!$video) {
    die("Video not found or access denied.");
}

// Handle Axios POST (update request)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $price = trim($_POST['price'] ?? 0);
    $fake_views = trim($_POST['fake_views'] ?? 0);
    $status = trim($_POST['status'] ?? 'active');
    
    // Process video upload if exists
    $video_url = $video['video_url'];
    if (isset($_FILES['video_file']) && $_FILES['video_file']['error'] == UPLOAD_ERR_OK) {
        $upload_dir = __DIR__ . '/uploads/';
        if (!file_exists($upload_dir)) mkdir($upload_dir, 0777, true);
        
        $filename = uniqid() . '_' . basename($_FILES['video_file']['name']);
        if (move_uploaded_file($_FILES['video_file']['tmp_name'], $upload_dir . $filename)) {
            // Delete old video file 
            if ($video['video_url'] && file_exists(__DIR__ . '/' . $video['video_url'])) {
                @unlink(__DIR__ . '/' . $video['video_url']);
            }
            $video_url = 'uploads/' . $filename;
        }
    }

    $thumbnail_url = $video['thumbnail_url'];
    $thumb_b64 = $_POST['thumbnail_b64'] ?? '';
    
    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_id = uniqid();
            $thumb_name = 'uploads/thumb_' . $thumb_id . '.' . $img_type;
            if (file_put_contents(__DIR__ . '/' . $thumb_name, $img_base64)) {
                // Delete old thumbnail if it exists and is different
                if ($video['thumbnail_url'] && file_exists(__DIR__ . '/' . $video['thumbnail_url'])) {
                    @unlink(__DIR__ . '/' . $video['thumbnail_url']);
                }
                $thumbnail_url = $thumb_name;
            }
        }
    }

    $stmt = $pdo->prepare("UPDATE videos SET title = ?, price = ?, fake_views = ?, status = ?, video_url = ?, thumbnail_url = ? WHERE id = ? AND user_id = ?");
    $stmt->execute([$title, $price, $fake_views, $status, $video_url, $thumbnail_url, $id, $user_id]);

    header('Content-Type: application/json');
    echo json_encode(['status' => 'success']);
    exit;
}
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Video - SonicPesa</title>
    <link rel="icon" type="image/png" href="assets/images/favicon.png" sizes="16x16">
    <link rel="stylesheet" href="assets/css/remixicon.css">
    <link rel="stylesheet" href="assets/css/lib/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        [x-cloak] { display: none !important; }
        .upload-drop-zone {
            border: 2px dashed #d1d5db;
            border-radius: 12px;
            padding: 40px;
            transition: all 0.3s ease;
            cursor: pointer;
            background: #f9fafb;
        }
        .upload-drop-zone.dragging {
            border-color: #4f46e5;
            background: #f5f3ff;
        }
        .upload-drop-zone.disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="dashboard-main">
        <?php include 'includes/header.php'; ?>

        <div class="dashboard-main-body">
            <div class="card basic-data-table">
                <div class="card-header d-flex justify-content-between">
                    <h5 class="mb-0">Edit Video</h5>
                </div>

                <div class="card-body">
                    <div x-data="videoUploadHandler(<?= htmlspecialchars(json_encode($video), ENT_QUOTES, 'UTF-8') ?>)">
                        <form @submit.prevent="submitForm">
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label class="fw-semibold">Video Title</label>
                                    <input type="text" class="form-control" x-model="formData.title" :disabled="isUploading" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="fw-semibold">Price (TSH)</label>
                                    <input type="number" min="0" class="form-control" x-model="formData.price" :disabled="isUploading" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="fw-semibold">Fake Views</label>
                                    <input type="number" class="form-control" x-model="formData.fake_views" :disabled="isUploading" required>
                                </div>
                                <div class="col-12">
                                    <label class="fw-semibold">Replace Video File (Optional)</label>
                                    <div class="upload-drop-zone"
                                        :class="isUploading ? 'disabled' : (isDragging ? 'dragging' : '')"
                                        @dragover.prevent="isDragging = true"
                                        @dragleave.prevent="isDragging = false"
                                        @drop.prevent="handleDrop($event)"
                                        @click="$refs.file.click()">

                                        <input type="file" class="d-none" x-ref="file" accept="video/*" @change="fileChosen">
                                        <div x-show="!formData.video_file" class="text-center">
                                            <p>Click or drag video here to replace existing video (Leave blank to keep existing)</p>
                                        </div>
                                        <div x-show="formData.video_file" x-cloak class="text-center">
                                            <p x-text="formData.video_file.name"></p>
                                            <small x-text="formatBytes(formData.video_file.size)"></small>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-12 mt-3" x-show="thumbnailPreview">
                                    <label class="fw-semibold text-muted">Thumbnail Preview</label>
                                    <div class="mt-2 text-center bg-light border rounded p-2">
                                        <img :src="thumbnailPreview" class="img-fluid rounded shadow-sm" style="max-height: 250px; object-fit: contain;">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-check mt-3">
                                        <input class="form-check-input" type="checkbox" x-model="formData.agreed" required>
                                        <label class="form-check-label small">
                                            I confirm this video contains no prohibited content
                                        </label>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-switch mt-3 d-flex align-items-center">
                                        <input class="form-check-input" type="checkbox" role="switch" x-model="formData.status" :disabled="isUploading">
                                        <span class="ms-2 small">Published</span>
                                    </div>
                                </div>
                            </div>
                            <div x-show="isUploading" class="mt-4" x-cloak>
                                <div class="progress">
                                    <div class="progress-bar progress-bar-striped progress-bar-animated" :style="`width:${progress}%`"></div>
                                </div>
                            </div>
                            <button class="btn btn-primary w-100 mt-4" :disabled="isUploading || !formData.agreed">
                                <span x-show="!isUploading">Update Video</span>
                                <span x-show="isUploading">Uploading...</span>
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <?php include 'includes/footer.php'; ?>
    </main>
    
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>

    <script>
    function videoUploadHandler(existingVideo) {
        return {
            isUploading: false,
            isDragging: false,
            progress: 0,
            thumbnailPreview: existingVideo?.thumbnail_url || '',
            formData: {
                id: existingVideo?.id ?? null,
                title: existingVideo?.title ?? '',
                price: existingVideo?.price ?? '',
                fake_views: existingVideo?.fake_views ?? '',
                video_file: null,
                thumbnail_b64: '',
                agreed: !!existingVideo,
                status: existingVideo ? existingVideo.status === 'active' : true
            },

            extractThumbnail(file) {
                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', () => {
                    video.currentTime = 0;
                });

                video.addEventListener('seeked', () => {
                    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);

                    this.formData.thumbnail_b64 = canvas.toDataURL('image/jpeg', 0.8);
                    this.thumbnailPreview = this.formData.thumbnail_b64;
                    URL.revokeObjectURL(videoURL);
                });
            },

            fileChosen(e) {
                if(e.target.files.length > 0) {
                    this.formData.video_file = e.target.files[0];
                    this.extractThumbnail(e.target.files[0]);
                }
            },

            handleDrop(e) {
                this.isDragging = false;
                if(e.dataTransfer.files.length > 0) {
                    const file = e.dataTransfer.files[0];
                    if (file?.type.startsWith('video/')) {
                        this.formData.video_file = file;
                        this.extractThumbnail(file);
                    }
                }
            },

            formatBytes(bytes) {
                if (!bytes) return '';
                const i = Math.floor(Math.log(bytes) / Math.log(1024));
                return (bytes / Math.pow(1024, i)).toFixed(2) + ' ' + ['B','KB','MB','GB'][i];
            },

            submitForm() {
                this.isUploading = true;

                let data = new FormData();
                data.append('title', this.formData.title);
                data.append('price', this.formData.price);
                data.append('fake_views', this.formData.fake_views);
                data.append('status', this.formData.status ? 'active' : 'inactive');

                if (this.formData.video_file) {
                    data.append('video_file', this.formData.video_file);
                }

                if (this.formData.thumbnail_b64) {
                    data.append('thumbnail_b64', this.formData.thumbnail_b64);
                }

                if (this.formData.id) {
                    data.append('_method', 'PUT');
                }

                const url = `edit_video?id=${this.formData.id}`;

                axios.post(url, data, {
                    onUploadProgress: p => {
                        this.progress = Math.round((p.loaded * 100) / p.total);
                    }
                })
                .then(() => {
                    Swal.fire('Success', 'Saved successfully', 'success')
                    .then(() => window.location.href = "videos");
                })
                .catch(() => {
                    this.isUploading = false;
                    Swal.fire('Error', 'Something went wrong', 'error');
                });
            }
        }
    }
    </script>
</body>
</html>


