<?php
// ✅ Start session before any output
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
// ✅ Check admin login
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit;
}
?>
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once 'db.php';
// ✅ Initialize variables
$msg = '';
$editMode = false;
$editId = null;
$editTitle = '';
$editDescription = '';
$editUrl = '';

// ✅ Check if we're editing an existing video
if (isset($_GET['edit'])) {
    $editId = intval($_GET['edit']);
    $stmt = $pdo->prepare("SELECT * FROM video_training WHERE id = ?");
    $stmt->execute([$editId]);
    $videoToEdit = $stmt->fetch();

    if ($videoToEdit) {
        $editMode = true;
        $editTitle = $videoToEdit['title'];
        $editDescription = $videoToEdit['description'];
        $editUrl = $videoToEdit['youtube_url'];
    }
}

// ✅ Handle form submission (Add or Update)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $url = trim($_POST['youtube_url'] ?? '');
    $id = $_POST['video_id'] ?? null;

// ✅ Extract Video ID and convert to proper embed URL
$embed_url = '';

if (preg_match('/youtu\.be\/([^\?&]+)/', $url, $matches) ||
    preg_match('/v=([^\?&]+)/', $url, $matches) ||
    preg_match('/embed\/([^\?&]+)/', $url, $matches)) {
    // YouTube
    $video_id = $matches[1];
    $embed_url = "https://www.youtube.com/embed/" . $video_id;
} elseif (preg_match('/vimeo\.com\/(?:video\/)?([0-9]+)/', $url, $matches)) {
    // Vimeo
    $video_id = $matches[1];
    $embed_url = "https://player.vimeo.com/video/" . $video_id;
} elseif (preg_match('/loom\.com\/share\/([a-zA-Z0-9]+)/', $url, $matches)) {
    // Loom
    $video_id = $matches[1];
    $embed_url = "https://www.loom.com/embed/" . $video_id;
} else {
    $msg = "❌ Invalid video URL. Only YouTube, Vimeo, and Loom are supported.";
}

if ($embed_url) {
    if (is_numeric($id) && $id > 0) {
        // ✅ UPDATE
        $stmt = $pdo->prepare("UPDATE video_training SET title = ?, description = ?, youtube_url = ? WHERE id = ?");
        $stmt->execute([$title, $description, $embed_url, $id]);
    } else {
        // ✅ INSERT
        $stmt = $pdo->prepare("INSERT INTO video_training (title, description, youtube_url) VALUES (?, ?, ?)");
        $stmt->execute([$title, $description, $embed_url]);
    }

    header("Location: video-admin.php?success=1");
    exit;
}
}


// ✅ Handle delete
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $pdo->prepare("DELETE FROM video_training WHERE id = ?")->execute([$id]);
    header("Location: video-admin.php");
    exit;
}

// ✅ Fetch all videos
$videos = $pdo->query("SELECT * FROM video_training ORDER BY created_at DESC");
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Video Admin Panel</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  
  
  <style>
    body { font-family: sans-serif; max-width: 900px; margin: 40px auto; padding: 0 20px; }
    h2 { margin-top: 40px; }
    .msg { background: #f0f8ff; padding: 10px; border: 1px solid #b2d4ff; color: #036; margin-bottom: 15px; }
    form input, form textarea { width: 100%; padding: 8px; margin: 6px 0; }
    form button { padding: 10px 20px; background: #28a745; color: #fff; border: none; cursor: pointer; }
    form button:hover { background: #218838; }
    iframe { max-width: 100%; height: 150px; border: none; }
    .video-row { border: 1px solid #ddd; padding: 10px; margin: 15px 0; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
    .actions { margin-top: 5px; }
    .actions a { margin-right: 10px; text-decoration: none; }
    .edit { color: #007bff; }
    .delete { color: #c00; }
    
    .admin-sidebar {
  color: #fff;
}
.admin-sidebar h4 {
  color: #fff;
  margin-bottom: 20px;
}
.admin-sidebar a {
  color: #fff !important;
  display: block;
  margin-bottom: 10px;
  text-decoration: none;
}
.admin-sidebar a:hover {
  color: #ffc107 !important;
  text-decoration: underline;
}

  </style>
</head>
<body style="display: flex; min-height: 100vh; margin: 0;">
  <div class="admin-sidebar" style="width:220px; background:#343a40; padding:20px;">
  <?php include 'google-translate-widget-front-end.php'; ?>
  <?php include 'admin-links.php'; ?>
</div>

  <div style="flex-grow: 1; padding: 20px;">


  <h1><i class="fas fa-video"></i> Video Training Admin</h1>

  <?php if ($msg): ?>
    <div class="msg"><?= $msg ?></div>
  <?php endif; ?>

  <h2><?= $editMode ? "Edit Video" : "Add New Video" ?></h2>
  <form method="post">
    <input type="hidden" name="video_id" value="<?= htmlspecialchars($editId) ?>">
    <label>Video Title:</label>
    <input type="text" name="title" value="<?= htmlspecialchars($editTitle) ?>" required>

    <label>Description:</label>
    <textarea name="description" rows="10" required><?= htmlspecialchars($editDescription) ?></textarea>

    <label>Video URL (YouTube, Vimeo, or Loom):</label>
    <input type="text" name="youtube_url" value="<?= htmlspecialchars($editUrl) ?>" required>

    <button type="submit">
      <i class="fas fa-<?= $editMode ? 'save' : 'plus-circle' ?>"></i>
      <?= $editMode ? 'Update Video' : 'Add Video' ?>
    </button>
  </form>

  <h2>Current Videos</h2>
  <?php foreach ($videos as $row): ?>
    <div class="video-row">
      <strong><?= htmlspecialchars($row['title']) ?></strong>
      <p><?= htmlspecialchars($row['description']) ?></p>
      <iframe src="<?= htmlspecialchars($row['youtube_url']) ?>" allowfullscreen></iframe>
      <div class="actions">
        <a class="edit" href="?edit=<?= $row['id'] ?>"><i class="fas fa-pen"></i> Edit</a>
        <a class="delete" href="?delete=<?= $row['id'] ?>" onclick="return confirm('Delete this video?')"><i class="fas fa-trash"></i> Delete</a>
      </div>
    </div>
  <?php endforeach; ?>
<?php include 'admin-footer.php'; ?>

</div> <!-- Close main-content -->
</body>
</html>
