<?php
ob_start();
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit;
}



require_once 'db.php';

// ✅ Fetch branding settings
$stmt = $pdo->query("SELECT background_image, logo_image FROM branding WHERE id = 1");
$branding = $stmt->fetch();

// ✅ Define variables
$backgroundImage = $branding['background_image'] ?? '';
$logoImage = $branding['logo_image'] ?? '';

// ✅ Get Program ID from URL
$id = $_GET['id'] ?? 0;

// ✅ Fetch Program Details
$stmt = $pdo->prepare("SELECT * FROM programs WHERE id = ?");
$stmt->execute([$id]);
$program = $stmt->fetch(PDO::FETCH_ASSOC);


// ✅ If the program doesn't exist, stop here
if (!$program) {
    die("Program not found.");
}

// ✅ Handle Form Submission (Update Program)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'];
    $subtitle = $_POST['subtitle'];
    // Function to extract YouTube Video ID and convert it to embed format
function getEmbedURL($url) {
    // YouTube
    if (preg_match('/(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=))([\w-]+)/', $url, $matches)) {
        return "https://www.youtube.com/embed/" . $matches[1];
    }

    // Loom
    if (preg_match('/loom\.com\/share\/([a-zA-Z0-9]+)/', $url, $matches)) {
        return "https://www.loom.com/embed/" . $matches[1];
    }

    // Vimeo
    if (preg_match('/vimeo\.com\/(\d+)/', $url, $matches)) {
        return "https://player.vimeo.com/video/" . $matches[1];
    }

    // Fallback
    return $url;
}


// Process the video URL input
$video_url = isset($_POST['video_url']) ? getEmbedURL(trim($_POST['video_url'])) : '';
    $cta_text = $_POST['cta_text'];
    $url_template = $_POST['url_template'];
    $placeholder_text = $_POST['placeholder_text'];
    $step_label = $_POST['step_label'] ?? '';
$step_video_url = isset($_POST['step_video_url']) ? getEmbedURL(trim($_POST['step_video_url'])) : '';
$icon_class = $_POST['icon_class'] ?? '';



$default_admin_referrer = $_POST['default_admin_referrer'] ?? '';
$is_new = isset($_POST['is_new']) ? 1 : 0;

$stmt = $pdo->prepare("UPDATE programs 
SET title=?, subtitle=?, video_url=?, cta_text=?, url_template=?, placeholder_text=?, default_admin_referrer=?, 
step_label=?, step_video_url=?, icon_class=?, is_new=? 
WHERE id=?");

$stmt->execute([
    $title, $subtitle, $video_url, $cta_text, $url_template, $placeholder_text, $default_admin_referrer,
    $step_label, $step_video_url, $icon_class, $is_new,
    $id
]);


    echo "<script>
    alert('✅ Program Updated Successfully!');
    window.location.href = 'edit_program.php?id=$id';
</script>";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Program</title>
<link rel="stylesheet" href="assets/css/styles.css">
 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
body {
    font-family: Arial, sans-serif;
    text-align: center;
    background: #f8f9fa; /* Default background */
    <?php if (!empty($backgroundImage)): ?>
        background-image: url('<?= $backgroundImage; ?>');
        background-repeat: no-repeat;
        background-position: center center;
        background-attachment: fixed;
        background-size: cover;
    <?php endif; ?>
}

.container {
    margin: 0;
    width: 100%;
    background: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0px 4px 12px rgba(0,0,0,0.15);
}

table { 
    width: 100%; 
    border-collapse: collapse; 
    margin-top: 20px; 
}

th, td { 
    padding: 10px; 
    border: 1px solid #ddd; 
    text-align: left; 
}

th { 
    background: #007bff; 
    color: white; 
}

.edit-btn { 
    background: #28a745; 
    color: white; 
    padding: 5px 10px; 
    border: none; 
    cursor: pointer; 
    border-radius: 5px; 
}

.edit-btn:hover { 
    background: #218838; 
}

.footer {
    text-align: center;
    padding: 20px;
    font-size: 14px;
    color: white;
    background: rgba(0, 0, 0, 0.6); /* Semi-transparent */
    border-radius: 8px;
    width: 80%;
    margin: 40px auto 10px; /* Ensures spacing from other elements */
    position: relative;
    bottom: 0;
    clear: both; /* Forces it to clear any floating elements */
}

/* Force admin sidebar links to look right on dark background */
.admin-sidebar a {
  color: #fff !important;
  text-decoration: none;
}
.admin-sidebar a:hover {
  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;">
<?php if (!empty($logoImage)): ?>
    <div style="text-align: center; padding: 20px;">
        <img src="<?= $logoImage; ?>" alt="Logo" style="max-width: 200px; height: auto;">
    </div>
<?php endif; ?>


<div class="container">
    <h2>Edit Program</h2>
<form method="POST">
    <label>Program Name:</label>
    <input type="text" name="title" value="<?php echo htmlspecialchars($program['title']); ?>" placeholder="Enter program name (e.g., LiveGood)" required>
    
    <label>Subtitle:</label>
    <input type="text" name="subtitle" value="<?php echo htmlspecialchars($program['subtitle']); ?>" placeholder="Enter a short subtitle" required>
    
    <label>Video URL:</label>
    <input type="text" name="video_url" value="<?php echo htmlspecialchars($program['video_url']); ?>" placeholder="Paste YouTube or Vimeo link" required>
    
    <label>Call-to-Action Text:</label>
    <input type="text" name="cta_text" value="<?php echo htmlspecialchars($program['cta_text']); ?>" placeholder="Enter button text (e.g., Join Now)" required>
    
    <label>Program URL Template:</label>
    <small>You can use <code>{{USER_ID}}</code> to insert the user's unique ID into the URL.</small>
    <input type="text" name="url_template" value="<?php echo htmlspecialchars($program['url_template'] ?? ''); ?>" placeholder="Enter URL with {{USER_ID}}"><small class="text-muted">Leave blank if this step is training only (no CTA button).</small>

    <label>Placeholder Text:</label>
    <input type="text" name="placeholder_text" value="<?php echo htmlspecialchars($program['placeholder_text']); ?>" placeholder="Enter placeholder text" required>

    <label for="default_admin_referrer">Default Admin Referral ID:</label>
    <input type="text" name="default_admin_referrer" value="<?php echo htmlspecialchars($program['default_admin_referrer'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="Enter Default Admin Referral ID">


    <label>Step Label (Optional):</label>
    <input type="text" name="step_label" value="<?= htmlspecialchars($program['step_label'] ?? '') ?>" placeholder="e.g., Unlock Your First Income Stream">

    <label>Step Video URL:</label>
    <input type="text" name="step_video_url" value="<?= htmlspecialchars($program['step_video_url'] ?? '') ?>" placeholder="Paste YouTube or Loom welcome video link">

<label for="icon_class" class="form-label">Icon (Font Awesome)</label>
<select name="icon_class" id="icon_class" class="form-select">
    <option value="">— Select Icon —</option>
    <option value="fa-fire" <?= ($program['icon_class'] == 'fa-fire') ? 'selected' : '' ?>>🔥 Fire (fa-fire)</option>
    <option value="fa-robot" <?= ($program['icon_class'] == 'fa-robot') ? 'selected' : '' ?>>🤖 Robot (fa-robot)</option>
    <option value="fa-money-bill-wave" <?= ($program['icon_class'] == 'fa-money-bill-wave') ? 'selected' : '' ?>>💸 Money (fa-money-bill-wave)</option>
    <option value="fa-graduation-cap" <?= ($program['icon_class'] == 'fa-graduation-cap') ? 'selected' : '' ?>>🎓 Graduation (fa-graduation-cap)</option>
    <option value="fa-flag-checkered" <?= ($program['icon_class'] == 'fa-flag-checkered') ? 'selected' : '' ?>>🏁 Flag (fa-flag-checkered)</option>
    <option value="fa-rocket" <?= ($program['icon_class'] == 'fa-rocket') ? 'selected' : '' ?>>🚀 Rocket (fa-rocket)</option>
    <option value="fa-handshake" <?= ($program['icon_class'] == 'fa-handshake') ? 'selected' : '' ?>>🤝 Handshake (fa-handshake)</option>
    <option value="fa-users" <?= ($program['icon_class'] == 'fa-users') ? 'selected' : '' ?>>👥 Users (fa-users)</option>
</select>


<div style="margin-top: 30px; text-align: left;">
  <label for="is_new" style="font-weight: bold; display: block; margin-bottom: 8px;">
    Mark this program as <span style="color: #e83e8c;">NEW</span>
  </label>
  <input type="checkbox" id="is_new" name="is_new" value="1" style="transform: scale(1.2);" <?= ($program['is_new'] == 1) ? 'checked' : '' ?>>
</div>


    <br><br>
    <button type="submit">Save Changes</button>
</form>

    <br>
    <a href="admin.php">Cancel</a>
</div>
<?php include 'admin-footer.php'; ?>

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