<?php
if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.gc_maxlifetime', 31536000);
    ini_set('session.cookie_lifetime', 31536000);
    session_start();
}

require_once 'db.php';


// ✅ Ensure user is logged in
if (!isset($_SESSION['logged_in_user'])) {
    header('Location: user-login.php');
    exit();
}

$loggedInUser = $_SESSION['logged_in_user'];

// ✅ Fetch Branding Settings (Logo)
$stmt = $pdo->query("SELECT logo_image FROM branding WHERE id = 1");
$branding = $stmt->fetch(PDO::FETCH_ASSOC);
$logoImage = $branding['logo_image'] ?? ''; // Default to empty if not set


// Retrieve numeric user ID
$stmt = $pdo->prepare("SELECT id FROM users WHERE user_id = ?");
$stmt->execute([$loggedInUser]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$user_id = $user['id'] ?? 0;

// Fetch current override program slot
$stmt = $pdo->prepare("SELECT override_program_slot FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$overrideSlot = (int)($stmt->fetchColumn());


// Fetch user's programs
$stmt = $pdo->prepare("SELECT * FROM user_programs WHERE user_id = ?");
$stmt->execute([$user_id]);
$programs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Count user's programs
$program_count = count($programs);

// Function to Convert YouTube URLs to Embed Format
function convertToEmbedURL($url) {
    if (strpos($url, 'youtu.be') !== false) {
        return preg_replace('/https:\/\/youtu\.be\//', 'https://www.youtube.com/embed/', $url);
    } elseif (strpos($url, 'watch?v=') !== false) {
        return preg_replace('/watch\?v=/', 'embed/', str_replace('https://www.youtube.com/', 'https://www.youtube.com/', $url));
    }
    return $url; // Return unchanged if not a match
}

// Handle Program Deletion
if (isset($_POST['delete'])) {
    $program_id = $_POST['program_id'];
    $stmt = $pdo->prepare("DELETE FROM user_programs WHERE id = ? AND user_id = ?");
    $stmt->execute([$program_id, $user_id]);
    $_SESSION['message'] = "Program deleted successfully!";
    header("Location: user-programs.php");
    exit();
}

// Handle Program Addition
if (isset($_POST['add_program']) && $program_count < 5) {
    $program_name = $_POST['program_name'];
    $sub_headline = $_POST['sub_headline'];
    $youtube_link = !empty($_POST['youtube_link']) ? convertToEmbedURL($_POST['youtube_link']) : '';
    $join_link = $_POST['join_link'];
    $created_at = date("Y-m-d H:i:s");
    
    $stmt = $pdo->prepare("INSERT INTO user_programs (user_id, program_name, sub_headline, youtube_link, join_link, created_at) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([$user_id, $program_name, $sub_headline, $youtube_link, $join_link, $created_at]);
    $_SESSION['message'] = "Program added successfully!";
    header("Location: user-programs.php");
    exit();
}

// Handle Program Editing
if (isset($_POST['edit_program'])) {
    $program_id = $_POST['program_id'];
    $program_name = $_POST['program_name'];
    $sub_headline = $_POST['sub_headline'];
    $youtube_link = !empty($_POST['youtube_link']) ? convertToEmbedURL($_POST['youtube_link']) : '';
    $join_link = $_POST['join_link'];
    
    $stmt = $pdo->prepare("UPDATE user_programs SET program_name = ?, sub_headline = ?, youtube_link = ?, join_link = ? WHERE id = ? AND user_id = ?");
    $stmt->execute([$program_name, $sub_headline, $youtube_link, $join_link, $program_id, $user_id]);
    $_SESSION['message'] = "Program updated successfully!";
    header("Location: user-programs.php");
    exit();
}

// ✅ Handle Step 3 Override Toggle
if (isset($_POST['toggle_override'])) {
    $program_id = $_POST['program_id'];

    // Get the slot index of this program
    $slotIndex = array_search($program_id, array_column($programs, 'id'));
    $slot = $slotIndex !== false ? $slotIndex + 1 : null;

    if ($slot) {
        if ($overrideSlot === $slot) {
            // ✅ If already selected, turn it off
            $stmt = $pdo->prepare("UPDATE users SET override_program_slot = NULL, override_dashboard_step = NULL WHERE id = ?");
            $stmt->execute([$user_id]);
        } else {
            // ✅ Set new override AND set dashboard_step = 3
            $stmt = $pdo->prepare("UPDATE users SET override_program_slot = ?, override_dashboard_step = 3 WHERE id = ?");
            $stmt->execute([$slot, $user_id]);
        }
        header("Location: user-programs.php");
        exit();
    }
}
?>

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Your Programs</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <link rel="stylesheet" href="assets/css/nav-style.css">

    <style>
        body {
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }
        .container-fluid {
            flex-grow: 1;
            padding: 20px !important;
        }
        .sidebar {
            width: 250px !important;
            min-height: 100vh;
            background-color: #f8f9fa;
        }
        .card {
            border-radius: 10px !important;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1) !important;
        }

/* Footer */
.footer {
    background-color: #343a40; /* Dark background */
    color: #ffffff; /* White text */
    text-align: center;
    padding: 15px;
    font-size: 14px;
    width: 100%;
    box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
    position: relative; /* Ensures it stays below content */
    margin-top: 20px; /* Adds space above the footer */
}


/* ✅ Style the program cards like settings.php */
.program-card {
    background: #ffffff;
    border-radius: 10px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    padding: 20px;
    border-left: 6px solid #007bff; /* Blue left border */
}

/* ✅ Program Title Styling */
.program-card h3 {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 5px;
}

/* ✅ Make videos responsive */
.embed-responsive {
    position: relative;
    width: 100%;
    padding-top: 56.25%; /* 16:9 Aspect Ratio */
    overflow: hidden;
    border-radius: 8px;
    margin-top: 10px;
}

.embed-responsive iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: 8px;
}

/* ✅ Clean, responsive grid layout */
.program-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
    gap: 20px;
    justify-items: center;
}


/* ✅ Fix overly large card issue */
.program-card {
    width: 100%;
    max-width: 380px;
}


/* ✅ Responsive Cards */
@media (max-width: 768px) {
    .program-grid {
        grid-template-columns: 1fr; /* Stack in one column on small screens */
    }
}

.override-btn {
    margin-left: 5px;
    background-color: #6c757d;
    border: none;
    color: white;
    padding: 4px 10px;
    font-size: 13px;
    border-radius: 5px;
    display: inline-flex;
    align-items: center;
    gap: 5px;
}

.override-btn.active {
    background-color: #ffc107;
    color: black;
    font-weight: bold;
}

    </style>
</head>
<body>

<?php include 'top-navbar.php'; ?>


<?php include 'sidebar.php'; ?><!-- Sidebar Toggle Button (Mobile Only) -->
<button onclick="toggleSidebar()" class="sidebar-toggle-btn">
    <i class="fas fa-bars"></i>
</button>

<!-- Overlay for sidebar on mobile -->
    <div class="sidebar-overlay" onclick="toggleSidebar()"></div>

    <!-- ✅ Main Content Area -->
    <div class="container-fluid p-4" style="background: #fff; min-height: 100vh;">
    <h2>Your Programs<?php include 'google-translate-widget.php'; ?>
</h2>
    <?php if (!empty($message)): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <?php echo $message; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>
<?php if ($program_count < 5): ?>
<button class="btn btn-success mb-3" 
    data-bs-toggle="modal" 
    data-bs-target="#addProgramModal" 
    data-bs-backdrop="static" 
    data-bs-keyboard="false">
    Add New Program
</button>

<?php else: ?>
    <button class="btn btn-secondary mb-3" disabled>Program Limit Reached</button>
    <div class="alert alert-warning">You have reached the limit of 5 programs.</div>
<?php endif; ?>
<div class="program-grid">
<?php foreach ($programs as $program): ?>
    <?php $loopIndex = array_search($program, $programs) + 1; ?>
    <div class="program-card <?php echo ($overrideSlot === $loopIndex) ? 'border border-warning border-3' : ''; ?>">
        <h3><?php echo htmlspecialchars($program['program_name']); ?></h3>
        <p class="text-muted"><?php echo htmlspecialchars($program['sub_headline']); ?></p>

        <?php if (!empty($program['youtube_link'])): ?>
            <div class="embed-responsive">
                <iframe class="embed-responsive-item" src="<?php echo htmlspecialchars($program['youtube_link']); ?>" allowfullscreen></iframe>
            </div>
        <?php endif; ?>

        <div class="mt-3 d-flex flex-wrap gap-2">
            <a href="<?php echo htmlspecialchars($program['join_link']); ?>" target="_blank" class="btn btn-primary btn-sm">
                <i class="fa fa-link"></i> Join Link
            </a>

            <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#editProgramModal<?php echo htmlspecialchars($program['id']); ?>">
                <i class="fa fa-edit"></i> Edit
            </button>

            <form method="post" onsubmit="return confirmDelete();" style="display:inline;">
                <input type="hidden" name="program_id" value="<?php echo $program['id']; ?>">
                <button type="submit" name="delete" class="btn btn-danger btn-sm">
                    <i class="fa fa-trash"></i> Delete
                </button>
            </form>

            <form method="post" style="display:inline;">
                <input type="hidden" name="program_id" value="<?php echo $program['id']; ?>">
                <button type="submit" name="toggle_override"
                        class="btn btn-outline-secondary btn-sm <?php echo ($overrideSlot === $loopIndex) ? 'active border-warning text-dark fw-bold' : ''; ?>">
                    <i class="fa fa-star<?php echo ($overrideSlot === $loopIndex) ? ' text-warning' : ''; ?>"></i>
                    <?php echo ($overrideSlot === $loopIndex) ? 'Step 3 Override (On)' : 'Set as Step 3'; ?>
                </button>
            </form>
        </div>
    </div>
    
    <!-- ✅ Edit Modal for this program -->
<div class="modal fade" id="editProgramModal<?php echo $program['id']; ?>" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Program</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <input type="hidden" name="program_id" value="<?php echo $program['id']; ?>">

                    <label>Program Title:</label>
                    <small class="text-muted d-block mb-2">Update the name of your program (e.g., 'Affiliate Pro' or 'My Business Opportunity').</small>
                    <input type="text" name="program_name" value="<?php echo htmlspecialchars($program['program_name']); ?>" class="form-control" required>

                    <label>Sub Headline:</label>
                    <small class="text-muted d-block mb-2">Modify the short tagline or description (e.g., 'Earn passive income with ease').</small>
                    <input type="text" name="sub_headline" value="<?php echo htmlspecialchars($program['sub_headline']); ?>" class="form-control" required>

                    <label>YouTube Video (Optional):</label>
                    <small class="text-muted d-block mb-2">Update the YouTube video link to showcase your program (e.g., a presentation or review video).</small>
                    <input type="url" name="youtube_link" value="<?php echo htmlspecialchars($program['youtube_link']); ?>" class="form-control">

                    <label>Join Link:</label>
                    <small class="text-muted d-block mb-2">Edit the referral link where users can sign up (e.g., 'https://yourprogram.com/join?ref=12345').</small>
                    <input type="url" name="join_link" value="<?php echo htmlspecialchars($program['join_link']); ?>" class="form-control" required>
                </div>
                <div class="modal-footer">
                    <button type="submit" name="edit_program" class="btn btn-success">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php endforeach; ?>
</div>


        
        <script>
function confirmDelete() {
    return confirm("Are you sure you want to delete this program?");
}
</script>


    </div>
</div>







<!-- Add Program Modal -->
<div class="modal fade" id="addProgramModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add New Program</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
<form method="post">
    <div class="modal-body">
        <label>Program Title:</label>
        <small class="text-muted d-block mb-2">Enter the name of your program (e.g., 'Affiliate Pro' or 'My Business Opportunity').</small>
        <input type="text" name="program_name" class="form-control" required>

        <label>Sub Headline:</label>
        <small class="text-muted d-block mb-2">A short tagline or brief description (e.g., 'Earn passive income with ease').</small>
        <input type="text" name="sub_headline" class="form-control" required>

        <label>YouTube Video (Optional):</label>
        <small class="text-muted d-block mb-2">Paste a YouTube video link to showcase your program (e.g., a presentation or review video).</small>
        <input type="url" name="youtube_link" class="form-control">

        <label>Join Link:</label>
        <small class="text-muted d-block mb-2">Enter the referral link where users can sign up (e.g., 'https://yourprogram.com/join?ref=12345').</small>
        <input type="url" name="join_link" class="form-control" required>
    </div>
    <div class="modal-footer">
        <button type="submit" name="add_program" class="btn btn-success">Add Program</button>
    </div>
</form>

        </div>
    </div>
</div>


        
    </div>
</div>
</div> <!-- ✅ Close Main Content Container -->
</div> <!-- ✅ Close Sidebar & Main Content Wrapper -->

<?php include 'footer.php'; ?>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>

<script>
document.addEventListener("DOMContentLoaded", function () {
    // ✅ Ensure Edit Modal always loads with correct data
    var editButtons = document.querySelectorAll('[data-bs-target^="#editProgramModal"]');
    editButtons.forEach(function (button) {
        button.addEventListener("click", function () {
            var programId = this.getAttribute("data-bs-target").replace("#editProgramModal", "");
            var modal = document.querySelector("#editProgramModal" + programId);
            
            if (modal) {
                var inputs = modal.querySelectorAll("input, textarea");
                inputs.forEach(input => {
                    if (!input.value.trim()) {
                        input.value = input.getAttribute("placeholder") || "";
                    }
                });
            }
        });
    });

    // ✅ Fix Modal Backdrop Issue (Prevent Page from Freezing)
    document.addEventListener("hidden.bs.modal", function () {
        var backdrop = document.querySelector(".modal-backdrop");
        if (backdrop) {
            backdrop.remove();
            document.body.classList.remove("modal-open");
        }
    });
});
</script>

    
    <script>
function toggleSidebar() {
  const sidebar = document.querySelector('.sidebar');
  const overlay = document.querySelector('.sidebar-overlay');
  const toggleBtn = document.querySelector('.sidebar-toggle-btn');

  sidebar.classList.toggle('open');
  overlay.classList.toggle('show');
  document.body.classList.toggle('sidebar-opened');

  // Optional: toggle button visibility while sidebar is open
  if (document.body.classList.contains('sidebar-opened')) {
    toggleBtn.style.display = 'none';
  } else {
    toggleBtn.style.display = 'block';
  }
}

// ✅ Hide sidebar if top navbar is toggled (on mobile)
document.querySelector('.navbar-toggler')?.addEventListener('click', function () {
  document.querySelector('.sidebar')?.classList.remove('open');
  document.querySelector('.sidebar-overlay')?.classList.remove('show');
  document.body.classList.remove('sidebar-opened');
});
</script>


</body>
</html>

