<?php
require_once __DIR__ . '/header.php';

$action = $_GET['action'] ?? 'list';
$error = '';
$success = '';

// ฟังก์ชันสำหรับอัปโหลดรูปภาพ
function handleImageUpload() {
    if (isset($_FILES['image_file']) && $_FILES['image_file']['error'] === UPLOAD_ERR_OK) {
        $fileTmpPath = $_FILES['image_file']['tmp_name'];
        $fileName = $_FILES['image_file']['name'];
        $fileSize = $_FILES['image_file']['size'];
        $fileType = $_FILES['image_file']['type'];
        $fileNameCmps = explode(".", $fileName);
        $fileExtension = strtolower(end($fileNameCmps));
        
        $allowedfileExtensions = array('jpg', 'gif', 'png', 'jpeg', 'webp');
        if (in_array($fileExtension, $allowedfileExtensions)) {
            // สร้างโฟลเดอร์ uploads หากยังไม่มี
            $uploadFileDir = dirname(__DIR__) . '/uploads/';
            if (!is_dir($uploadFileDir)) {
                mkdir($uploadFileDir, 0755, true);
            }
            
            $newFileName = md5(time() . $fileName) . '.' . $fileExtension;
            $dest_path = $uploadFileDir . $newFileName;
            
            if(move_uploaded_file($fileTmpPath, $dest_path)) {
                // คืนค่าเส้นทางของไฟล์ภาพสำหรับเก็บลงฐานข้อมูล
                $project_name = basename(dirname(__DIR__));
                return '/' . rawurlencode($project_name) . '/uploads/' . $newFileName;
            }
        }
    }
    return null;
}

// ฟังก์ชันแปลง YouTube URL เป็น embed URL (PHP side)
function getYoutubeEmbed($url) {
    if (empty($url)) return null;
    if (preg_match('/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/', $url, $m)) {
        return 'https://www.youtube.com/embed/' . $m[1];
    }
    return null;
}

// จัดการการส่งข้อมูลแบบ POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_product'])) {
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $price = (float)($_POST['price'] ?? 0);
        $stock = (int)($_POST['stock'] ?? 0);
        $category = trim($_POST['category'] ?? 'general');
        
        // จัดการอัปโหลดไฟล์รูปภาพก่อน ถ้าไม่มีให้ใช้ URL ที่กรอก
        $uploaded_url = handleImageUpload();
        $image_url = $uploaded_url ? $uploaded_url : trim($_POST['image_url'] ?? '');

        if (empty($name) || $price < 0 || $stock < 0) {
            $error = 'กรุณากรอกชื่อสินค้า ราคา และจำนวนสต็อกให้ถูกต้อง';
        } else {
            try {
                $video_url = trim($_POST['video_url'] ?? '');
                $stmt = $pdo->prepare("INSERT INTO products (name, description, price, stock, image_url, video_url, category) VALUES (?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$name, $description, $price, $stock, $image_url, $video_url, $category]);
                $success = 'เพิ่มสินค้าลงคลังเรียบร้อยแล้ว!';
                $action = 'list';
            } catch (PDOException $e) {
                $error = 'ไม่สามารถเพิ่มสินค้าได้: ' . $e->getMessage();
            }
        }
    } elseif (isset($_POST['edit_product'])) {
        $id = (int)($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $price = (float)($_POST['price'] ?? 0);
        $stock = (int)($_POST['stock'] ?? 0);
        $category = trim($_POST['category'] ?? 'general');
        $existing_image = trim($_POST['existing_image'] ?? '');

        // จัดการอัปโหลดรูปภาพใหม่
        $uploaded_url = handleImageUpload();
        $image_url = $uploaded_url ? $uploaded_url : (trim($_POST['image_url'] ?? '') ?: $existing_image);

        if ($id <= 0 || empty($name) || $price < 0 || $stock < 0) {
            $error = 'พารามิเตอร์ในการแก้ไขไม่ถูกต้อง';
        } else {
            try {
                $video_url = trim($_POST['video_url'] ?? '');
                $existing_video = trim($_POST['existing_video'] ?? '');
                $final_video_url = $video_url ?: $existing_video;
                $stmt = $pdo->prepare("UPDATE products SET name = ?, description = ?, price = ?, stock = ?, image_url = ?, video_url = ?, category = ? WHERE id = ?");
                $stmt->execute([$name, $description, $price, $stock, $image_url, $final_video_url, $category, $id]);
                $success = 'แก้ไขข้อมูลสินค้าเสร็จสิ้น!';
                $action = 'list';
            } catch (PDOException $e) {
                $error = 'ไม่สามารถแก้ไขข้อมูลสินค้าได้: ' . $e->getMessage();
            }
        }
    } elseif (isset($_POST['quick_stock_update'])) {
        $id = (int)($_POST['id'] ?? 0);
        $stock = (int)($_POST['stock'] ?? 0);

        if ($id > 0 && $stock >= 0) {
            try {
                $stmt = $pdo->prepare("UPDATE products SET stock = ? WHERE id = ?");
                $stmt->execute([$stock, $id]);
                $success = 'อัปเดตจำนวนสินค้าสำเร็จ!';
            } catch (PDOException $e) {
                $error = 'ไม่สามารถอัปเดตสต็อกสินค้าได้';
            }
        } else {
            $error = 'จำนวนสินค้าไม่ถูกต้อง';
        }
    }
}

// ลบสินค้า
if ($action === 'delete') {
    $id = (int)($_GET['id'] ?? 0);
    if ($id > 0) {
        try {
            $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
            $stmt->execute([$id]);
            $success = 'ลบสินค้าออกจากฐานข้อมูลแล้ว';
        } catch (PDOException $e) {
            $error = 'ไม่สามารถลบสินค้าได้ (สินค้านี้อาจผูกอยู่กับคำสั่งซื้อของลูกค้า)';
        }
    }
    $action = 'list';
}

// ดึงข้อมูลสินค้าที่จะแก้ไข
$editItem = null;
if ($action === 'edit') {
    $id = (int)($_GET['id'] ?? 0);
    if ($id > 0) {
        $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
        $stmt->execute([$id]);
        $editItem = $stmt->fetch();
        if (!$editItem) {
            $error = 'ไม่พบสินค้าที่ต้องการแก้ไข';
            $action = 'list';
        }
    } else {
        $action = 'list';
    }
}

// ดึงรายการสินค้าทั้งหมด
$products = [];
if ($action === 'list') {
    try {
        $stmt = $pdo->query("SELECT * FROM products ORDER BY id DESC");
        $products = $stmt->fetchAll();
    } catch (PDOException $e) {
        $error = 'ไม่สามารถดึงข้อมูลสินค้าได้';
    }
}
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
    <div>
        <h1 style="font-size: 2.2rem; text-shadow: 0 0 10px var(--glow-red); color: var(--text-white);">จัดการคลังสินค้า</h1>
        <p style="color: var(--text-gray); font-size: 0.95rem;">ระบบจัดการ เพิ่ม ลบ แก้ไข และนำเข้ารูปภาพสินค้า</p>
    </div>
    <div>
        <?php if ($action === 'list'): ?>
            <a href="products.php?action=add" class="btn-cyber btn-green">[+] เพิ่มสินค้าใหม่</a>
        <?php else: ?>
            <a href="products.php" class="btn-cyber btn-gray">&laquo; กลับไปหน้าหลัก</a>
        <?php endif; ?>
    </div>
</div>

<?php if ($error): ?>
    <div class="cyber-alert cyber-alert-error">
        <strong>[เกิดข้อผิดพลาด]</strong> <?php echo htmlspecialchars($error); ?>
    </div>
<?php endif; ?>

<?php if ($success): ?>
    <div class="cyber-alert cyber-alert-success">
        <strong>[สำเร็จ]</strong> <?php echo htmlspecialchars($success); ?>
    </div>
<?php endif; ?>

<!-- ฟอร์มเพิ่มสินค้าใหม่ -->
<?php if ($action === 'add'): ?>
    <div class="cyber-card" style="max-width: 700px; margin: 0 auto;">
        <h2 style="margin-bottom: 1.5rem; text-transform: uppercase;">&gt;_ เพิ่มสินค้าใหม่เข้าระบบ</h2>
        <form action="products.php" method="POST" enctype="multipart/form-data">
            <div class="cyber-input-group">
                <label class="cyber-label">ชื่อสินค้า</label>
                <input class="cyber-input" type="text" name="name" placeholder="เช่น Cybernetic T-Shirt" required>
            </div>

            <div class="cyber-input-group">
                <label class="cyber-label">หมวดหมู่สินค้า</label>
                <select class="cyber-input" name="category" style="background-color: var(--bg-input);">
                    <option value="clothing">เสื้อผ้า (Clothing)</option>
                    <option value="bags">กระเป๋า (Bags)</option>
                    <option value="accessories">ของใช้ไอที (Accessories)</option>
                </select>
            </div>
            
            <div class="cyber-input-group">
                <label class="cyber-label">ราคาสินค้า (บาท ฿)</label>
                <input class="cyber-input" type="number" step="0.01" name="price" placeholder="390.00" required>
            </div>

            <div class="cyber-input-group">
                <label class="cyber-label">จำนวนสินค้าเริ่มต้นในคลัง</label>
                <input class="cyber-input" type="number" name="stock" placeholder="10" required min="0">
            </div>

            <!-- อัปโหลดไฟล์ภาพ -->
            <div class="cyber-input-group" style="border: 1px dashed var(--border-color); padding: 1.5rem; border-radius: 8px; margin-bottom: 1.5rem;">
                <label class="cyber-label" style="color: var(--neon-red);">อัปโหลดรูปภาพสินค้า (แนะนำ)</label>
                <input class="cyber-input" type="file" name="image_file" accept="image/*" style="border: none; padding: 0.5rem 0;">
                <div style="font-size: 0.8rem; color: var(--text-muted); margin-top: 0.5rem;">รองรับไฟล์: JPG, JPEG, PNG, WEBP, GIF</div>
            </div>

            <div class="cyber-input-group">
                <label class="cyber-label">หรือ ใส่ลิงก์ URL รูปภาพโดยตรง</label>
                <input class="cyber-input" type="url" name="image_url" placeholder="https://images.unsplash.com/... (หากไม่ได้อัปโหลดไฟล์)">
            </div>

            <!-- วิดีโอตัวอย่าง -->
            <div class="cyber-input-group" style="border: 1px dashed rgba(255,200,0,0.4); padding: 1.5rem; border-radius: 8px; margin-bottom: 1.5rem; background: rgba(255,200,0,0.03);">
                <label class="cyber-label" style="color: #ffc400;">🎬 ลิงก์วิดีโอตัวอย่างสินค้า (ไม่บังคับ)</label>
                <input class="cyber-input" type="url" id="add_video_url" name="video_url"
                    placeholder="https://www.youtube.com/watch?v=... หรือ https://example.com/video.mp4"
                    oninput="previewVideo(this.value, 'add_video_preview')">
                <div style="font-size: 0.8rem; color: var(--text-muted); margin-top: 0.5rem;">รองรับ: YouTube, MP4, WebM</div>

                <!-- กล่อง Preview -->
                <div id="add_video_preview" style="margin-top: 1rem; display: none;">
                    <div style="font-size: 0.85rem; color: #ffc400; margin-bottom: 0.5rem;">▶ ตัวอย่างวิดีโอ:</div>
                    <div style="position: relative; width: 100%; padding-bottom: 56.25%; border-radius: 8px; overflow: hidden; border: 1px solid rgba(255,200,0,0.4); background: #000;">
                        <iframe id="add_video_iframe" style="position:absolute;top:0;left:0;width:100%;height:100%;display:none;" frameborder="0" allowfullscreen allow="autoplay; encrypted-media"></iframe>
                        <video id="add_video_tag" style="position:absolute;top:0;left:0;width:100%;height:100%;display:none;" controls></video>
                    </div>
                </div>
            </div>

            <div class="cyber-input-group">
                <label class="cyber-label">รายละเอียดสินค้า / ข้อมูลสเปก</label>
                <textarea class="cyber-input" name="description" rows="4" placeholder="ระบุคุณสมบัติ ฮาร์ดแวร์ และข้อมูลอื่นๆ..."></textarea>
            </div>

            <button type="submit" name="add_product" class="btn-cyber btn-green" style="width: 100%;">
                ยืนยันการเพิ่มสินค้า
            </button>
        </form>
    </div>

<!-- ฟอร์มแก้ไขข้อมูลสินค้า -->
<?php elseif ($action === 'edit' && $editItem): ?>
    <div class="cyber-card" style="max-width: 700px; margin: 0 auto;">
        <h2 style="margin-bottom: 1.5rem; text-transform: uppercase;">&gt;_ แก้ไขข้อมูลสินค้า #<?php echo $editItem['id']; ?></h2>
        <form action="products.php" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="id" value="<?php echo $editItem['id']; ?>">
            <input type="hidden" name="existing_image" value="<?php echo htmlspecialchars($editItem['image_url']); ?>">
            
            <div class="cyber-input-group">
                <label class="cyber-label">ชื่อสินค้า</label>
                <input class="cyber-input" type="text" name="name" value="<?php echo htmlspecialchars($editItem['name']); ?>" required>
            </div>

            <div class="cyber-input-group">
                <label class="cyber-label">หมวดหมู่สินค้า</label>
                <select class="cyber-input" name="category" style="background-color: var(--bg-input);">
                    <option value="clothing" <?php echo $editItem['category'] === 'clothing' ? 'selected' : ''; ?>>เสื้อผ้า (Clothing)</option>
                    <option value="bags" <?php echo $editItem['category'] === 'bags' ? 'selected' : ''; ?>>กระเป๋า (Bags)</option>
                    <option value="accessories" <?php echo $editItem['category'] === 'accessories' ? 'selected' : ''; ?>>ของใช้ไอที (Accessories)</option>
                </select>
            </div>
            
            <div class="cyber-input-group">
                <label class="cyber-label">ราคาสินค้า (บาท ฿)</label>
                <input class="cyber-input" type="number" step="0.01" name="price" value="<?php echo htmlspecialchars($editItem['price']); ?>" required>
            </div>

            <div class="cyber-input-group">
                <label class="cyber-label">จำนวนสินค้าในคลัง</label>
                <input class="cyber-input" type="number" name="stock" value="<?php echo htmlspecialchars($editItem['stock']); ?>" required min="0">
            </div>

            <!-- แสดงรูปปัจจุบัน -->
            <?php if ($editItem['image_url']): ?>
                <div style="margin-bottom: 1.5rem;">
                    <label class="cyber-label">รูปภาพปัจจุบัน:</label>
                    <img src="<?php echo htmlspecialchars($editItem['image_url']); ?>" alt="current_img" style="max-width: 150px; border-radius: 6px; border: 1px solid var(--neon-red); display: block; margin-top: 0.5rem; box-shadow: 0 0 10px var(--glow-light);">
                </div>
            <?php endif; ?>

            <!-- เปลี่ยนรูปโดยอัปโหลดไฟล์ -->
            <div class="cyber-input-group" style="border: 1px dashed var(--border-color); padding: 1.5rem; border-radius: 8px; margin-bottom: 1.5rem;">
                <label class="cyber-label" style="color: var(--neon-red);">อัปโหลดรูปภาพใหม่เพื่อเปลี่ยน</label>
                <input class="cyber-input" type="file" name="image_file" accept="image/*" style="border: none; padding: 0.5rem 0;">
                <div style="font-size: 0.8rem; color: var(--text-muted); margin-top: 0.5rem;">หากไม่อัปโหลดภาพใหม่ ระบบจะใช้รูปเดิม</div>
            </div>

            <div class="cyber-input-group">
                <label class="cyber-label">หรือ เปลี่ยนเป็นลิงก์ URL รูปภาพใหม่</label>
                <input class="cyber-input" type="url" name="image_url" value="<?php echo htmlspecialchars(strpos($editItem['image_url'], '/uploads/') === false ? $editItem['image_url'] : ''); ?>" placeholder="https://images.unsplash.com/... (ใส่ URL ใหม่ถ้าต้องการเปลี่ยนแบบลิงก์)">
            </div>

            <!-- วิดีโอตัวอย่าง -->
            <input type="hidden" name="existing_video" value="<?php echo htmlspecialchars($editItem['video_url'] ?? ''); ?>">
            <div class="cyber-input-group" style="border: 1px dashed rgba(255,200,0,0.4); padding: 1.5rem; border-radius: 8px; margin-bottom: 1.5rem; background: rgba(255,200,0,0.03);">
                <label class="cyber-label" style="color: #ffc400;">🎬 ลิงก์วิดีโอตัวอย่างสินค้า (ไม่บังคับ)</label>
                <input class="cyber-input" type="url" id="edit_video_url" name="video_url"
                    value="<?php echo htmlspecialchars($editItem['video_url'] ?? ''); ?>"
                    placeholder="https://www.youtube.com/watch?v=... หรือ https://example.com/video.mp4"
                    oninput="previewVideo(this.value, 'edit_video_preview')">
                <div style="font-size: 0.8rem; color: var(--text-muted); margin-top: 0.5rem;">รองรับ: YouTube, MP4, WebM — ลบ URL ออกเพื่อลบวิดีโอ</div>

                <!-- กล่อง Preview -->
                <div id="edit_video_preview" style="margin-top: 1rem; <?php echo empty($editItem['video_url']) ? 'display:none;' : ''; ?>">
                    <div style="font-size: 0.85rem; color: #ffc400; margin-bottom: 0.5rem;">▶ ตัวอย่างวิดีโอ:</div>
                    <div style="position: relative; width: 100%; padding-bottom: 56.25%; border-radius: 8px; overflow: hidden; border: 1px solid rgba(255,200,0,0.4); background: #000;">
                        <iframe id="edit_video_iframe" style="position:absolute;top:0;left:0;width:100%;height:100%;<?php echo empty($editItem['video_url']) ? 'display:none;' : ''; ?>" frameborder="0" allowfullscreen allow="autoplay; encrypted-media"
                            src="<?php echo !empty($editItem['video_url']) ? htmlspecialchars(getYoutubeEmbed($editItem['video_url']) ?: '') : ''; ?>"></iframe>
                        <video id="edit_video_tag" style="position:absolute;top:0;left:0;width:100%;height:100%;<?php
                            $ev = $editItem['video_url'] ?? '';
                            echo (!empty($ev) && !getYoutubeEmbed($ev)) ? '' : 'display:none;';
                        ?>" controls src="<?php echo !empty($ev) && !getYoutubeEmbed($ev) ? htmlspecialchars($ev) : ''; ?>"></video>
                    </div>
                </div>
            </div>

            <div class="cyber-input-group">
                <label class="cyber-label">รายละเอียดสินค้า / ข้อมูลสเปก</label>
                <textarea class="cyber-input" name="description" rows="4"><?php echo htmlspecialchars($editItem['description']); ?></textarea>
            </div>

            <button type="submit" name="edit_product" class="btn-cyber" style="width: 100%;">
                บันทึกการแก้ไขข้อมูล
            </button>
        </form>
    </div>

<!-- ตารางรายการสินค้าทั้งหมด -->
<?php else: ?>
    <div class="cyber-card">
        <h3 style="margin-bottom: 1.5rem; text-transform: uppercase;">&gt;_ รายการคลังสินค้าทั้งหมด</h3>
        <div class="table-responsive">
            <table class="cyber-table">
                <thead>
                    <tr>
                        <th>รหัส (ID)</th>
                        <th>ภาพตัวอย่าง</th>
                        <th>รายละเอียดสินค้า</th>
                        <th>หมวดหมู่</th>
                        <th>ราคา</th>
                        <th style="width: 150px;">สินค้าในคลัง</th>
                        <th style="text-align: right;">การดำเนินการ</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($products)): ?>
                        <tr>
                            <td colspan="7" style="text-align: center; color: var(--text-muted);">ไม่มีรายการสินค้าในระบบ</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($products as $prod): ?>
                            <tr>
                                <td style="font-family: 'Orbitron', sans-serif;">#<?php echo $prod['id']; ?></td>
                                <td>
                                    <?php if ($prod['image_url']): ?>
                                        <img src="<?php echo htmlspecialchars($prod['image_url']); ?>" alt="img" style="width: 50px; height: 50px; object-fit: cover; border-radius: 6px; border: 1px solid var(--border-color);">
                                    <?php else: ?>
                                        <div style="width: 50px; height: 50px; background: #222; border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 0.75rem; color: #555;">ไม่มีรูป</div>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <strong style="color: var(--text-white);"><?php echo htmlspecialchars($prod['name']); ?></strong>
                                    <div style="font-size: 0.85rem; color: var(--text-muted); max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                                        <?php echo htmlspecialchars($prod['description']); ?>
                                    </div>
                                </td>
                                <td>
                                    <span class="badge" style="background: rgba(255, 255, 255, 0.05); border: 1px solid #333;">
                                        <?php 
                                            if ($prod['category'] === 'clothing') echo "เสื้อผ้า";
                                            elseif ($prod['category'] === 'bags') echo "กระเป๋า";
                                            else echo "ของใช้ไอที";
                                        ?>
                                    </span>
                                </td>
                                <td>฿<?php echo number_format($prod['price'], 2); ?></td>
                                <td>
                                    <form action="products.php" method="POST" style="display: flex; gap: 0.5rem; align-items: center;">
                                        <input type="hidden" name="id" value="<?php echo $prod['id']; ?>">
                                        <input class="cyber-input" type="number" name="stock" value="<?php echo $prod['stock']; ?>" min="0" style="padding: 0.3rem 0.5rem; font-size: 0.9rem; text-align: center; width: 60px;">
                                        <button type="submit" name="quick_stock_update" class="btn-cyber" style="padding: 0.3rem 0.5rem; border-radius: 4px; border-color: var(--text-gray); box-shadow: none;" title="บันทึกจำนวนสต็อก">✔</button>
                                    </form>
                                </td>
                                <td style="text-align: right; white-space: nowrap;">
                                    <a href="products.php?action=edit&id=<?php echo $prod['id']; ?>" class="btn-cyber" style="padding: 0.4rem 0.8rem; font-size: 0.75rem; border-color: rgba(255,255,255,0.3); box-shadow: none; margin-right: 0.5rem;">แก้ไข</a>
                                    <a href="products.php?action=delete&id=<?php echo $prod['id']; ?>" class="btn-cyber btn-cyber-danger" style="padding: 0.4rem 0.8rem; font-size: 0.75rem; border-color: var(--neon-red); box-shadow: none; color: var(--neon-red);" onclick="return confirm('ยืนยันที่จะลบสินค้าชิ้นนี้ใช่หรือไม่?');">ลบ</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
<?php endif; ?>

<?php
require_once __DIR__ . '/footer.php';
?>

<script>
// ฟังก์ชันสำหรับ preview วิดีโอ (YouTube หรือ MP4)
function previewVideo(url, containerId) {
    const container = document.getElementById(containerId);
    const iframe = document.getElementById(containerId.replace('_preview', '_iframe'));
    const videoTag = document.getElementById(containerId.replace('_preview', '_tag'));

    if (!url || url.trim() === '') {
        container.style.display = 'none';
        iframe.style.display = 'none';
        videoTag.style.display = 'none';
        iframe.src = '';
        videoTag.src = '';
        return;
    }

    container.style.display = 'block';
    const embedUrl = getYoutubeEmbedJS(url);

    if (embedUrl) {
        // YouTube
        iframe.src = embedUrl;
        iframe.style.display = 'block';
        videoTag.style.display = 'none';
        videoTag.src = '';
    } else {
        // Direct video file
        videoTag.src = url;
        videoTag.style.display = 'block';
        iframe.style.display = 'none';
        iframe.src = '';
    }
}

function getYoutubeEmbedJS(url) {
    // รองรับ youtube.com/watch?v= และ youtu.be/
    const patterns = [
        /(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/
    ];
    for (const p of patterns) {
        const m = url.match(p);
        if (m) return 'https://www.youtube.com/embed/' + m[1];
    }
    return null;
}

// Auto-preview existing edit form video on page load
window.addEventListener('DOMContentLoaded', () => {
    const editInput = document.getElementById('edit_video_url');
    if (editInput && editInput.value) {
        previewVideo(editInput.value, 'edit_video_preview');
    }
});
</script>
