<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

// Check if admin is logged in
if (empty($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    header('Location: admin_login.php');
    exit;
}

require_once __DIR__ . '/helpers/database_helper.php';

// Load video section settings (prefer data/video_section.json)
$settingsPath = __DIR__ . '/data/video_section.json';
if (file_exists($settingsPath)) {
    $videoSection = json_decode(file_get_contents($settingsPath), true);
    if (!is_array($videoSection)) $videoSection = [];
} else {
    // Fallback to DatabaseHelper if available
    if (class_exists('DatabaseHelper') && method_exists('DatabaseHelper', 'loadJson')) {
        $videoSection = DatabaseHelper::loadJson('video_section.json', []);
    } else {
        $videoSection = [];
    }
}

// Helper to persist settings to data/video_section.json
function saveVideoSection($data) {
    $dir = __DIR__ . '/data/';
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    $path = $dir . 'video_section.json';
    return (bool) file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT));
}

$message = '';
$messageType = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && $_POST['action'] === 'update_video') {
        $videoSection['enabled'] = isset($_POST['enabled']) ? true : false;
        $videoSection['title'] = htmlspecialchars($_POST['title'] ?? 'Our Story');
        $videoSection['subtitle'] = htmlspecialchars($_POST['subtitle'] ?? '');
        $videoSection['description'] = htmlspecialchars($_POST['description'] ?? '');
        // keep existing video_url as fallback if present
        $videoSection['video_url'] = $videoSection['video_url'] ?? 'https://www.youtube.com/embed/dQw4w9WgXcQ';
        $videoSection['show_button'] = isset($_POST['show_button']) ? true : false;
        $videoSection['button_text'] = htmlspecialchars($_POST['button_text'] ?? 'Play Video');

        // handle uploads
        $uploadsDir = __DIR__ . '/uploads/';
        if (!is_dir($uploadsDir)) mkdir($uploadsDir, 0755, true);

        // Poster image upload (field name: poster_file)
        if (!empty($_FILES['poster_file']['tmp_name'])) {
            $pf = $_FILES['poster_file'];
            $ext = strtolower(pathinfo($pf['name'], PATHINFO_EXTENSION));
            $allowedImg = ['jpg','jpeg','png','webp','gif'];
            if (in_array($ext, $allowedImg) && is_uploaded_file($pf['tmp_name'])) {
                $target = 'uploads/poster_' . time() . '.' . $ext;
                if (move_uploaded_file($pf['tmp_name'], __DIR__ . '/' . $target)) {
                    $videoSection['poster_image'] = $target;
                }
            }
        }

        // Video upload (field name: video_file)
        if (!empty($_FILES['video_file']['tmp_name'])) {
            $vf = $_FILES['video_file'];
            $ext = strtolower(pathinfo($vf['name'], PATHINFO_EXTENSION));
            $allowedV = ['mp4','webm'];
            if (in_array($ext, $allowedV) && is_uploaded_file($vf['tmp_name'])) {
                $target = 'uploads/video_' . time() . '.' . $ext;
                if (move_uploaded_file($vf['tmp_name'], __DIR__ . '/' . $target)) {
                    $videoSection['uploaded_video'] = $target;
                }
            }
        }

        // save via our helper to ensure persistence
        if (saveVideoSection($videoSection)) {
            $message = 'Video section updated successfully!';
            $messageType = 'success';
        } else {
            $message = 'Error saving video section.';
            $messageType = 'error';
        }
    }
}

// include 'admin_sidebar.php';
?>

<style>
    .admin-content-area {
        padding: 30px;
        margin-left: 320px;
        background: #f9f9f9;
        min-height: calc(100vh - 200px);
    }

    .admin-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30px;
    }

    .admin-header h1 {
        font-size: 28px;
        margin: 0;
        color: #333;
    }

    .back-btn {
        background: #667eea;
        color: #fff;
        padding: 10px 20px;
        text-decoration: none;
        border-radius: 6px;
        font-size: 14px;
    }

    .back-btn:hover {
        background: #5568d3;
    }

    .message {
        padding: 15px 20px;
        border-radius: 6px;
        margin-bottom: 20px;
        font-weight: 600;
    }

    .message.success {
        background: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }

    .message.error {
        background: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }

    .form-section {
        background: #fff;
        padding: 25px;
        border-radius: 8px;
        margin-bottom: 25px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    }

    .form-section h2 {
        font-size: 18px;
        margin-top: 0;
        margin-bottom: 20px;
        color: #333;
        border-bottom: 2px solid #F07E2D;
        padding-bottom: 10px;
    }

    .form-group {
        margin-bottom: 20px;
    }

    .form-group label {
        display: block;
        margin-bottom: 8px;
        font-weight: 600;
        color: #333;
        font-size: 14px;
    }

    .form-group input[type="text"],
    .form-group input[type="url"],
    .form-group textarea,
    .form-group select {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #ddd;
        border-radius: 6px;
        font-size: 14px;
        font-family: inherit;
    }

    .form-group input[type="text"]:focus,
    .form-group input[type="url"]:focus,
    .form-group textarea:focus,
    .form-group select:focus {
        outline: none;
        border-color: #F07E2D;
        box-shadow: 0 0 0 3px rgba(225, 123, 169, 0.1);
    }

    .form-group textarea {
        resize: vertical;
        min-height: 100px;
    }

    .checkbox-group {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 15px;
    }

    .checkbox-group input[type="checkbox"] {
        width: 18px;
        height: 18px;
        cursor: pointer;
    }

    .checkbox-group label {
        margin: 0;
        cursor: pointer;
        font-weight: 500;
    }

    .preview-section {
        background: #f9f9f9;
        padding: 20px;
        border-radius: 6px;
        margin-top: 20px;
        border: 1px solid #e0e0e0;
    }

    .preview-section h3 {
        margin-top: 0;
        font-size: 14px;
        color: #667eea;
        margin-bottom: 15px;
    }

    .preview-video {
        max-width: 600px;
        margin: 0 auto;
        background: #000;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .preview-video-player {
        position: relative;
        width: 100%;
        height: auto;
        overflow: visible;
    }

    .preview-video-player iframe {
        position: relative;
        width: 100%;
        height: auto;
        border: none;
        aspect-ratio: 16 / 9;
    }

    .preview-video-player video {
        width: 100%;
        height: auto;
        display: block;
        background: #000;
    }

    .btn-group {
        display: flex;
        gap: 10px;
        margin-top: 25px;
        justify-content: flex-end;
    }

    .btn {
        padding: 12px 24px;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .btn-primary {
        background: #F07E2D;
        color: #fff;
    }

    .btn-primary:hover {
        background: #c76b8a;
    }

    .help-text {
        font-size: 12px;
        color: #999;
        margin-top: 5px;
    }

    .grid-2 {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 20px;
    }

    .info-box {
        background: #e3f2fd;
        border-left: 4px solid #667eea;
        padding: 15px;
        border-radius: 4px;
        margin-top: 20px;
        font-size: 13px;
        color: #1565c0;
    }

    .info-box ul {
        margin: 8px 0;
        padding-left: 20px;
    }

    .info-box li {
        margin: 5px 0;
    }

    @media (max-width: 768px) {
        .grid-2 {
            grid-template-columns: 1fr;
        }
    }
</style>

<div class="admin-content-area">
    <div class="admin-header">
        <h1>Video Section Management</h1>
       <?php
// Default link
$dashboardLink = "admin_dashboard.php";

// Adjust based on role
if (isset($_SESSION['role'])) {
    switch ($_SESSION['role']) {
        case 'admin':
            $dashboardLink = "admin_dashboard.php";
            break;
        case 'subadmin':
            $dashboardLink = "subadmin_dashboard.php";
            break;
        case 'editor':
            $dashboardLink = "subadmin_dashboard.php";
            break;
        default:
            $dashboardLink = "admin_dashboard.php"; // fallback
    }
}
?>

<a href="<?php echo $dashboardLink; ?>" class="back-btn">← Back to Dashboard</a>

<style>
.back-btn {
    background-color: orange;
    color: white;
    padding: 8px 14px;
    text-decoration: none;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;
}
.back-btn:hover {
    background-color: darkorange;
}
</style>
        <!-- <a href="admin_dashboard.php" class="back-btn">← Back to Dashboard</a>
     -->
    </div>

    <?php if ($message): ?>
    <div class="message <?php echo $messageType; ?>">
        <?php echo htmlspecialchars($message); ?>
    </div>
    <?php endif; ?>

    <!-- Video Section Settings Form -->
    <div class="form-section">
        <h2>Video Section Settings</h2>
        <form method="POST" action="" enctype="multipart/form-data">
            <input type="hidden" name="action" value="update_video">
            
            <div class="checkbox-group">
                <input type="checkbox" id="enabled" name="enabled" <?php echo ($videoSection['enabled'] ?? true) ? 'checked' : ''; ?>>
                <label for="enabled">Enable Video Section on Homepage</label>
            </div>

            <div class="grid-2">
                <div class="form-group">
                    <label for="title">Section Title</label>
                    <input type="text" id="title" name="title" value="<?php echo htmlspecialchars($videoSection['title'] ?? 'Our Story'); ?>" placeholder="e.g., Our Story">
                </div>

                <div class="form-group">
                    <label for="subtitle">Subtitle</label>
                    <input type="text" id="subtitle" name="subtitle" value="<?php echo htmlspecialchars($videoSection['subtitle'] ?? ''); ?>" placeholder="e.g., Experience Our Brand">
                </div>
            </div>

            <div class="form-group">
                <label for="description">Description</label>
                <textarea id="description" name="description" placeholder="Brief description for the video section"><?php echo htmlspecialchars($videoSection['description'] ?? ''); ?></textarea>
                <div class="help-text">This text appears below the title, describing what the video is about</div>
            </div>

            <div class="form-group">
                <label for="video_file">Upload Video File (mp4, webm) — optional</label>
                <input type="file" id="video_file" name="video_file" accept="video/mp4,video/webm">
                <div class="help-text">If you upload a video file, it will be used on the homepage. Otherwise the previously saved YouTube embed (if any) will be used as fallback.</div>
            </div>

            <div class="form-group">
                <label for="poster_file">Upload Poster Image — optional</label>
                <input type="file" id="poster_file" name="poster_file" accept="image/*">
                <div class="help-text">Image shown before video plays (optional). Uploading replaces the poster URL.</div>
            </div>

            <div class="form-group">
                <label for="button_text">Button Text</label>
                <input type="text" id="button_text" name="button_text" value="<?php echo htmlspecialchars($videoSection['button_text'] ?? 'Play Video'); ?>" placeholder="e.g., Play Video">
            </div>

            <div class="checkbox-group">
                <input type="checkbox" id="show_button" name="show_button" <?php echo ($videoSection['show_button'] ?? true) ? 'checked' : ''; ?>>
                <label for="show_button">Show Play Button Overlay</label>
            </div>

            <!-- Live Preview -->
            <div class="preview-section">
                <h3>Live Preview</h3>
                <div style="text-align:center; margin-bottom:20px;">
                    <h4 style="margin:0 0 8px 0; color:#333;">
                        <?php echo htmlspecialchars($videoSection['title'] ?? 'Our Story'); ?>
                    </h4>
                    <?php if (!empty($videoSection['subtitle'])): ?>
                    <p style="margin:0 0 8px 0; color:#666; font-size:13px;">
                        <?php echo htmlspecialchars($videoSection['subtitle']); ?>
                    </p>
                    <?php endif; ?>
                    <?php if (!empty($videoSection['description'])): ?>
                    <p style="margin:0; color:#999; font-size:12px;">
                        <?php echo htmlspecialchars($videoSection['description']); ?>
                    </p>
                    <?php endif; ?>
                </div>
                <div class="preview-video">
                    <div class="preview-video-player">
                        <?php if (!empty($videoSection['uploaded_video']) && file_exists(__DIR__ . '/' . $videoSection['uploaded_video'])): ?>
                            <?php $vid = '/emporio/' . ltrim($videoSection['uploaded_video'], '/'); $poster = (!empty($videoSection['poster_image']) && file_exists(__DIR__ . '/' . $videoSection['poster_image'])) ? '/emporio/' . ltrim($videoSection['poster_image'], '/') : ''; ?>
                            <video controls playsinline poster="<?php echo htmlspecialchars($poster); ?>">
                                <source src="<?php echo htmlspecialchars($vid); ?>" type="video/<?php echo htmlspecialchars(pathinfo($vid, PATHINFO_EXTENSION)); ?>">
                                Your browser does not support the video tag.
                            </video>
                        <?php else: ?>
                            <iframe 
                                src="<?php echo htmlspecialchars($videoSection['video_url'] ?? 'https://www.youtube.com/embed/dQw4w9WgXcQ'); ?>"
                                title="Video Preview"
                                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                                allowfullscreen>
                            </iframe>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="btn-group">
                <button type="submit" class="btn btn-primary">Save Video Settings</button>
            </div>
        </form>
    </div>

    <div class="info-box">
        <strong>💡 How to Use YouTube Embed URLs:</strong>
        <ul>
            <li>Find your YouTube video URL: <strong>https://www.youtube.com/watch?v=VIDEO_ID</strong></li>
            <li>Convert it to embed format: <strong>https://www.youtube.com/embed/VIDEO_ID</strong></li>
            <li>Paste the embed URL in the "Video URL" field above</li>
            <li>The video will automatically display in a responsive player</li>
            <li>Changes appear on the homepage immediately</li>
        </ul>
    </div>

    <div class="info-box" style="background:#fff3e0; border-left-color:#ff9800; color:#e65100; margin-top:15px;">
        <strong>📌 Tip:</strong> The video automatically adjusts to any screen size. Use a high-quality preview image for better appearance on slower connections.
    </div>
</div>

