<?php
// ✅ Start session before any output
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ✅ Check if admin is logged in
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'] ?? '';

// ✅ Handle form submission
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['signup_url']; // Save it into url_template instead
    $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;

// ✅ Step 1: Check if the max limit (10) is reached
$slot_query = "SELECT COUNT(*) as total FROM programs";
$slot_result = $pdo->query($slot_query);
$total_programs = $slot_result->fetch(PDO::FETCH_ASSOC)['total'];

if ($total_programs >= 10) {
    echo "<script>
        alert('❌ You cannot add more than 10 programs. Please delete an existing program first.');
        window.location.href = 'admin.php';
    </script>";
    exit;
}

// ✅ Step 2: Find the next available slot_number (from 1 to 10)
$slot_query = "SELECT slot_number FROM programs ORDER BY slot_number ASC";
$slot_result = $pdo->query($slot_query);

$used_slots = [];
while ($row = $slot_result->fetch(PDO::FETCH_ASSOC)) {
    $used_slots[] = $row['slot_number'];
}

// Find the lowest available slot (1-10)
$slot_number = 1;
while (in_array($slot_number, $used_slots) && $slot_number <= 10) {
    $slot_number++;
}

// ✅ Step 2: Insert program with assigned slot_number
$stmt = $pdo->prepare("INSERT INTO programs 
(title, subtitle, video_url, cta_text, signup_url, url_template, placeholder_text, default_admin_referrer, slot_number, step_label, step_video_url, icon_class, is_new) 
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

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


echo "<script>
    alert('✅ New Program Added!');
    window.location.href = 'admin.php';
</script>";


    echo "<script>
        alert('✅ New Program Added!');
        window.location.href = 'admin.php';
    </script>";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add 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>Add New Program</h2>
<form method="POST">
    <label>Program Name:</label>
    <input type="text" name="title" placeholder="Enter program name (e.g., LiveGood)" required>
    
    <label>Subtitle:</label>
    <input type="text" name="subtitle" placeholder="Enter a short subtitle" required>
    
    <label>Video URL:</label>
    <input type="text" name="video_url" placeholder="Paste YouTube or Vimeo link" required>
    
    <label>Call-to-Action Text:</label>
    <input type="text" name="cta_text" placeholder="Enter button text (e.g., Join Now)" required>
    
    <label>Signup URL:</label>
    <small>You can use <code>{{USER_ID}}</code> to insert the user's unique ID into the URL.</small>
    <input type="text" name="signup_url" placeholder="Enter program signup link"><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" placeholder="Enter Placeholder text" required>

    <label for="default_admin_referrer">Default Admin Referral ID:</label>
    <input type="text" name="default_admin_referrer" placeholder="Enter Admin Referral ID (Optional)">
    
        <label>Step Label (Optional):</label>
    <input type="text" name="step_label" placeholder="e.g., Unlock Your First Income Stream">

    <label>Step Video URL:</label>
    <input type="text" name="step_video_url" placeholder="Paste YouTube or Loom welcome video link">

    <label>Font Awesome Icon (Optional):</label>
    <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">🔥 Fire (fa-fire)</option>
    <option value="fa-robot">🤖 Robot (fa-robot)</option>
    <option value="fa-money-bill-wave">💸 Money (fa-money-bill-wave)</option>
    <option value="fa-graduation-cap">🎓 Graduation (fa-graduation-cap)</option>
    <option value="fa-flag-checkered">🏁 Flag (fa-flag-checkered)</option>
    <option value="fa-rocket">🚀 Rocket (fa-rocket)</option>
    <option value="fa-handshake">🤝 Handshake (fa-handshake)</option>
    <option value="fa-users">👥 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);">
</div>


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

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

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