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

$user_id = $_SESSION['user_id'];
$is_admin = (isset($_SESSION['role']) && $_SESSION['role'] === 'admin');
$success = '';
$error = '';

// 1. Handle POST Actions (Admin Only)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $is_admin) {
    
    // UPLOAD / ADD
    if (isset($_POST['action']) && $_POST['action'] === 'add') {
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $thumb_b64 = $_POST['thumbnail_b64'] ?? '';
        
        if (empty($title)) {
            $error = "Title is required.";
        } else {
            $video_url = '';
            $thumbnail_url = '';
            $upload_id = bin2hex(random_bytes(8));

            // Save Video
            if (isset($_FILES['video']) && $_FILES['video']['error'] === 0) {
                $ext = pathinfo($_FILES['video']['name'], PATHINFO_EXTENSION);
                $vid_name = 'uploads/tutorial_' . $upload_id . '.' . ($ext ?: 'mp4');
                if (move_uploaded_file($_FILES['video']['tmp_name'], __DIR__ . '/' . $vid_name)) {
                    $video_url = $vid_name;
                }
            }

            // Save Thumbnail (Base64)
            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_base64 = base64_decode($img_parts[1]);
                    $thumb_name = 'uploads/tutorial_thumb_' . $upload_id . '.' . $img_type;
                    if (file_put_contents(__DIR__ . '/' . $thumb_name, $img_base64)) {
                        $thumbnail_url = $thumb_name;
                    }
                }
            }

            if ($video_url) {
                try {
                    $stmt = $pdo->prepare("INSERT INTO tutorials (title, description, video_url, thumbnail_url) VALUES (?, ?, ?, ?)");
                    $stmt->execute([$title, $description, $video_url, $thumbnail_url]);
                    $success = "Tutorial uploaded successfully!";
                } catch (PDOException $e) { $error = "Database error."; }
            } else {
                $error = "Video upload failed.";
            }
        }
    }

    // EDIT
    elseif (isset($_POST['action']) && $_POST['action'] === 'edit') {
        $id = (int)$_POST['id'];
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        
        try {
            $stmt = $pdo->prepare("UPDATE tutorials SET title = ?, description = ? WHERE id = ?");
            $stmt->execute([$title, $description, $id]);
            $success = "Tutorial updated!";
        } catch (PDOException $e) { $error = "Update failed."; }
    }

    // DELETE
    elseif (isset($_POST['action']) && $_POST['action'] === 'delete') {
        $id = (int)$_POST['id'];
        try {
            // Fetch files to delete
            $stmt = $pdo->prepare("SELECT video_url, thumbnail_url FROM tutorials WHERE id = ?");
            $stmt->execute([$id]);
            $tut = $stmt->fetch();
            if ($tut) {
                if ($tut['video_url'] && file_exists(__DIR__ . '/' . $tut['video_url'])) unlink(__DIR__ . '/' . $tut['video_url']);
                if ($tut['thumbnail_url'] && file_exists(__DIR__ . '/' . $tut['thumbnail_url'])) unlink(__DIR__ . '/' . $tut['thumbnail_url']);
                
                $pdo->prepare("DELETE FROM tutorials WHERE id = ?")->execute([$id]);
                $success = "Tutorial removed.";
            }
        } catch (PDOException $e) { $error = "Delete failed."; }
    }
}

// 2. Fetch Tutorials
try {
    $tutorials = $pdo->query("SELECT * FROM tutorials ORDER BY created_at DESC")->fetchAll();
} catch (PDOException $e) { $tutorials = []; }

$pageTitle = "Tutorials - SonicPesa";
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<?php include 'includes/head.php'; ?>
<style>
    .tutorial-card { transition: transform 0.3s, box-shadow 0.3s; border: none; overflow: hidden; height: 100%; }
    .tutorial-card:hover { transform: translateY(-5px); box-shadow: 0 10px 20px rgba(0,0,0,0.1); }
    .tutorial-card .card-img-top { aspect-ratio: 16/9; object-fit: cover; }
    .video-play-btn { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 60px; height: 60px; background: rgba(93, 102, 229, 0.9); color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; opacity: 0; transition: opacity 0.3s; font-size: 24px; pointer-events: none; }
    .tutorial-card:hover .video-play-btn { opacity: 1; }
    .admin-actions { position: absolute; top: 10px; right: 10px; z-index: 5; }
    .player-modal .modal-content { background: #000; border: none; border-radius: 12px; overflow: hidden; }
    .player-modal .modal-header { border: none; position: absolute; top: 10px; right: 10px; z-index: 10; padding: 0; }
    .player-modal .btn-close { filter: invert(1); background-color: rgba(255,255,255,0.3); border-radius: 50%; padding: 10px; }
    .player-modal video { width: 100%; max-height: 80vh; outline: none; }
</style>
<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">System Tutorials</h6>
                <div class="d-flex gap-2">
                    <?php if($is_admin): ?>
                    <button class="btn btn-primary-600 radius-8 px-20 py-11 d-flex align-items-center gap-2" data-bs-toggle="modal" data-bs-target="#uploadModal">
                        <i class="ri-upload-cloud-2-line"></i> Upload Tutorial
                    </button>
                    <?php endif; ?>
                </div>
            </div>

            <?php if($success || $error): ?>
            <div class="alert alert-<?= $success ? 'success' : 'danger' ?> radius-8 px-16 py-11 text-sm mb-24">
                <?= $success ?: $error ?>
            </div>
            <?php endif; ?>

            <div class="row g-4">
                <?php if(empty($tutorials)): ?>
                <div class="col-12 text-center py-50">
                    <iconify-icon icon="solar:videocamera-off-bold" class="text-secondary-light" style="font-size: 64px;"></iconify-icon>
                    <p class="text-secondary-light mt-12">No tutorials available yet.</p>
                </div>
                <?php else: ?>
                    <?php foreach($tutorials as $t): ?>
                    <div class="col-xxl-3 col-xl-4 col-md-6">
                        <div class="card tutorial-card radius-12 bg-base">
                            <div class="position-relative cursor-pointer" onclick='playVideo("<?= SITE_URL ?>/<?= $t['video_url'] ?>", "<?= htmlspecialchars($t['title']) ?>")'>
                                <img src="<?= $t['thumbnail_url'] ? SITE_URL . '/' . $t['thumbnail_url'] : 'assets/images/placeholder.jpg' ?>" class="card-img-top" alt="...">
                                <div class="video-play-btn"><i class="ri-play-fill"></i></div>
                                
                                <?php if($is_admin): ?>
                                <div class="admin-actions d-flex gap-1" onclick="event.stopPropagation()">
                                    <button class="btn btn-xs btn-primary-600 rounded-pill p-4 d-flex" onclick='openEditModal(<?= json_encode($t) ?>)'><iconify-icon icon="material-symbols:edit"></iconify-icon></button>
                                    <button class="btn btn-xs btn-danger-600 rounded-pill p-4 d-flex" onclick="deleteTutorial(<?= $t['id'] ?>)"><iconify-icon icon="material-symbols:delete-rounded"></iconify-icon></button>
                                </div>
                                <?php endif; ?>
                            </div>
                            <div class="card-body p-16">
                                <h6 class="mb-8 text-md font-bold text-dark limit-2-lines"><?= htmlspecialchars($t['title']) ?></h6>
                                <p class="text-secondary-light text-xs limit-2-lines mb-0"><?= htmlspecialchars($t['description'] ?: 'No description.') ?></p>
                                <div class="mt-12 d-flex align-items-center gap-2 text-xs text-secondary-light">
                                    <iconify-icon icon="solar:calendar-outline"></iconify-icon>
                                    <?= date('M d, Y', strtotime($t['created_at'])) ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <?php include 'includes/footer.php'; ?>
    </main>

    <!-- Upload Modal -->
    <div class="modal fade" id="uploadModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content radius-12 p-12">
                <div class="modal-header border-0">
                    <h6 class="modal-title">Upload New Tutorial</h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="uploadForm" method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="add">
                    <input type="hidden" name="thumbnail_b64" id="thumbnail_b64">
                    <div class="modal-body p-12">
                        <div class="mb-16">
                            <label class="form-label text-sm fw-semibold">Tutorial Title</label>
                            <input type="text" name="title" class="form-control" placeholder="e.g. How to use Landing Pages" required>
                        </div>
                        <div class="mb-16">
                            <label class="form-label text-sm fw-semibold">Description</label>
                            <textarea name="description" class="form-control" rows="3" placeholder="Brief explanation..."></textarea>
                        </div>
                        <div class="mb-16">
                            <label class="form-label text-sm fw-semibold">Video File</label>
                            <div class="card border-dashed border-2 radius-12 p-24 text-center cursor-pointer hover-bg-primary-50 position-relative">
                                <i class="ri-video-add-line text-2xl text-primary-600"></i>
                                <p class="text-sm mt-8 mb-0" id="fileName">Click to select video</p>
                                <input type="file" name="video" id="videoFile" accept="video/*" class="position-absolute top-0 start-0 w-100 h-100 opacity-0 cursor-pointer" required onchange="handleFile(this)">
                            </div>
                            <div id="thumbPreview" class="mt-12 text-center" style="display:none;">
                                <p class="text-xs text-secondary-light mb-4">Auto-captured Thumbnail:</p>
                                <img id="thumbImg" src="" class="radius-8 shadow-sm w-100" style="max-height: 150px; object-fit: cover;">
                            </div>
                        </div>
                        <div class="progress mt-16 radius-8" style="height: 8px; display:none;" id="progressBar">
                            <div class="progress-bar bg-primary-600" id="progressFill" style="width: 0%;"></div>
                        </div>
                    </div>
                    <div class="modal-footer border-0">
                        <button type="submit" class="btn btn-primary-600 w-100" id="submitBtn">Publish Tutorial</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Modal -->
    <div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content radius-12 p-12">
                <div class="modal-header border-0">
                    <h6 class="modal-title">Edit Tutorial</h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="id" id="editId">
                    <div class="modal-body p-12">
                        <div class="mb-16">
                            <label class="form-label text-sm fw-semibold">Title</label>
                            <input type="text" name="title" id="editTitle" class="form-control" required>
                        </div>
                        <div class="mb-16">
                            <label class="form-label text-sm fw-semibold">Description</label>
                            <textarea name="description" id="editDesc" class="form-control" rows="4"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer border-0">
                        <button type="submit" class="btn btn-primary-600 w-100">Save Changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Player Modal -->
    <div class="modal fade player-modal" id="playerModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="btn-close" data-bs-dismiss="modal" onclick="stopVideo()"></button>
                </div>
                <div class="modal-body p-0">
                    <video id="mainVideo" controls controlsList="nodownload"></video>
                </div>
            </div>
        </div>
    </div>

    <!-- Hidden delete form -->
    <form id="deleteForm" method="POST" style="display:none;">
        <input type="hidden" name="action" value="delete">
        <input type="hidden" name="id" id="deleteId">
    </form>

    <script>
        function handleFile(input) {
            if (input.files && input.files[0]) {
                const file = input.files[0];
                document.getElementById('fileName').innerText = file.name;
                
                const videoURL = URL.createObjectURL(file);
                const video = document.createElement('video');
                video.src = videoURL;
                video.muted = true;
                video.crossOrigin = 'anonymous';

                video.addEventListener('loadedmetadata', function() {
                    video.currentTime = video.duration * 0.30;
                });

                video.addEventListener('seeked', function() {
                    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;
                    document.getElementById('thumbImg').src = dataURL;
                    document.getElementById('thumbPreview').style.display = 'block';
                    URL.revokeObjectURL(videoURL);
                });
            }
        }

        function playVideo(url, title) {
            const video = document.getElementById('mainVideo');
            video.src = url;
            video.play();
            const modal = new bootstrap.Modal(document.getElementById('playerModal'));
            modal.show();
        }
        
        function stopVideo() {
            const video = document.getElementById('mainVideo');
            video.pause();
            video.src = '';
        }

        function openEditModal(tut) {
            document.getElementById('editId').value = tut.id;
            document.getElementById('editTitle').value = tut.title;
            document.getElementById('editDesc').value = tut.description;
            const modal = new bootstrap.Modal(document.getElementById('editModal'));
            modal.show();
        }

        function deleteTutorial(id) {
            if(confirm("Are you sure you want to remove this tutorial? This will also delete the video file from the server.")) {
                document.getElementById('deleteId').value = id;
                document.getElementById('deleteForm').submit();
            }
        }
        
        // Modal cleanup
        document.getElementById('playerModal').addEventListener('hidden.bs.modal', stopVideo);
    </script>
</body>
</html>


