<?php
require_once __DIR__ . '/config.php';
requireAdmin();
$pdo = getDB();
$videosDir = dirname(__DIR__) . '/uploads/videos/';

/**
 * Accept: YouTube watch URL, youtu.be, embed URL, or pasted iframe HTML. Returns embed URL or empty.
 */
function normalizeYoutubeUrl($input) {
    $input = trim($input);
    if ($input === '') return '';
    // Extract URL from iframe embed code (e.g. pasted <iframe src="https://www.youtube.com/embed/xxx">)
    if (preg_match('/src\s*=\s*["\']([^"\']+youtube[^"\']+)["\']/i', $input, $m)) {
        $input = $m[1];
    }
    if (preg_match('/youtube\.com\/embed\/([a-zA-Z0-9_-]+)/', $input, $m)) {
        return 'https://www.youtube.com/embed/' . $m[1];
    }
    if (preg_match('/youtube\.com\/watch\?v=([a-zA-Z0-9_-]+)/', $input, $m)) {
        return 'https://www.youtube.com/embed/' . $m[1];
    }
    if (preg_match('/youtu\.be\/([a-zA-Z0-9_-]+)/', $input, $m)) {
        return 'https://www.youtube.com/embed/' . $m[1];
    }
    return $input;
}
if (!is_dir($videosDir)) mkdir($videosDir, 0755, true);

$hasType = false;
try {
    $pdo->query("SELECT video_type FROM videos LIMIT 1");
    $hasType = true;
} catch (Exception $e) {}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_POST['delete_id'])) {
        $id = (int)$_POST['delete_id'];
        if ($hasType) {
            $stmt = $pdo->prepare("SELECT video_file FROM videos WHERE id = ?");
            $stmt->execute([$id]);
            $f = $stmt->fetchColumn();
            if ($f && is_file($videosDir . $f)) @unlink($videosDir . $f);
        }
        $pdo->prepare("DELETE FROM videos WHERE id = ?")->execute([$id]);
        header('Location: videos.php');
        exit;
    }
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $sort = (int)($_POST['sort_order'] ?? 0);
    $videoType = $hasType ? trim($_POST['video_type'] ?? 'youtube') : 'youtube';

    if ($title && $hasType && $videoType === 'upload' && !empty($_FILES['video_file']['name'])) {
        $ext = strtolower(pathinfo($_FILES['video_file']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['mp4', 'webm', 'ogg'])) {
            $fname = 'v_' . time() . '.' . $ext;
            if (move_uploaded_file($_FILES['video_file']['tmp_name'], $videosDir . $fname)) {
                $pdo->prepare("INSERT INTO videos (title, video_type, video_url, video_file, description, sort_order) VALUES (?, 'upload', '', ?, ?, ?)")->execute([$title, $fname, $description, $sort]);
            }
        }
    } elseif ($title && $videoType === 'youtube') {
        $raw = trim($_POST['video_url'] ?? '');
        $url = normalizeYoutubeUrl($raw);
        if ($url) {
            if ($hasType) {
                $pdo->prepare("INSERT INTO videos (title, video_type, video_url, video_file, description, sort_order) VALUES (?, 'youtube', ?, NULL, ?, ?)")->execute([$title, $url, $description, $sort]);
            } else {
                $pdo->prepare("INSERT INTO videos (title, video_url, description, sort_order) VALUES (?, ?, ?, ?)")->execute([$title, $url, $description, $sort]);
            }
        }
    }
    header('Location: videos.php');
    exit;
}

$videos = $pdo->query("SELECT * FROM videos ORDER BY sort_order, id")->fetchAll(PDO::FETCH_ASSOC);
$pageTitle = 'Videos';
require_once __DIR__ . '/includes/header.php';
?>
<div class="admin-page">
    <h1>Video gallery</h1>
    <?php if (!$hasType): ?>
    <p class="error">Run <code>database/video_smtp_update_simple.sql</code> to add upload support (video_type, video_file columns).</p>
    <?php endif; ?>

    <div class="admin-card" style="margin-bottom:24px;">
        <h2 style="margin-top:0;">Add video</h2>
        <form method="post" enctype="multipart/form-data" class="admin-form">
            <label>Title *</label>
            <input type="text" name="title" required placeholder="Title">
            <?php if ($hasType): ?>
            <label>Source *</label>
            <select name="video_type" id="video_type_sel" onchange="document.getElementById('yt_row').style.display=this.value==='youtube'?'block':'none';document.getElementById('up_row').style.display=this.value==='upload'?'block':'none';">
                <option value="youtube">YouTube link</option>
                <option value="upload">Upload video file (MP4, WebM, OGG)</option>
            </select>
            <div id="yt_row">
                <label>YouTube link *</label>
                <p class="muted" style="margin:0 0 8px; font-size:0.85rem;">Paste the normal link (e.g. <code>https://www.youtube.com/watch?v=xxxxx</code>) or a youtu.be link. You can also paste the full embed iframe code — we will use the link.</p>
                <input type="text" name="video_url" placeholder="https://www.youtube.com/watch?v=xxxxx" style="max-width:100%;">
            </div>
            <div id="up_row" style="display:none;">
                <label>Upload video file *</label>
                <input type="file" name="video_file" accept=".mp4,.webm,.ogg,video/mp4,video/webm">
            </div>
            <?php else: ?>
            <label>YouTube or video URL *</label>
            <input type="url" name="video_url" placeholder="https://..." required>
            <?php endif; ?>
            <label>Description</label>
            <textarea name="description" rows="2" placeholder="Optional"></textarea>
            <label>Sort order</label>
            <input type="number" name="sort_order" value="0">
            <button type="submit" class="btn">Add</button>
        </form>
    </div>

    <table class="admin-table">
        <thead><tr><th>ID</th><th>Title</th><th>Type</th><th>Source</th><th>Actions</th></tr></thead>
        <tbody>
            <?php foreach ($videos as $v):
                $type = isset($v['video_type']) ? $v['video_type'] : 'youtube';
                $src = $type === 'upload' && !empty($v['video_file']) ? 'File: ' . $v['video_file'] : mb_substr($v['video_url'] ?? '', 0, 45) . '…';
            ?>
            <tr>
                <td><?php echo (int)$v['id']; ?></td>
                <td><?php echo htmlspecialchars($v['title']); ?></td>
                <td><?php echo htmlspecialchars($type); ?></td>
                <td><?php echo htmlspecialchars($src); ?></td>
                <td>
                    <form method="post" style="display:inline;" onsubmit="return confirm('Delete?');">
                        <input type="hidden" name="delete_id" value="<?php echo (int)$v['id']; ?>">
                        <button type="submit" class="link-btn">Delete</button>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
