<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

file_put_contents('debug_log.txt', "Script started\n", FILE_APPEND);

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

require_once 'db.php';


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

$loggedInUser = $_SESSION['logged_in_user'];

// ✅ Retrieve user data from the database
$stmt = $pdo->prepare("SELECT user_id, first_name, last_name, email, leadsleap_user_id, leadsleap_list_id, leadsleap_list_id_referrals, referrer_id FROM users WHERE user_id = ?");
$stmt->execute([$loggedInUser]);
$userData = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$userData) {
    die("<p style='color: red;'>❌ ERROR: No user found in the database with session ID ($loggedInUser)!</p>");
}

// ✅ Pagination setup
$videosPerPage = 8;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? intval($_GET['page']) : 1;
$offset = ($page - 1) * $videosPerPage;

// ✅ Get total count
$totalVideos = $pdo->query("SELECT COUNT(*) FROM video_training")->fetchColumn();
$totalPages = ceil($totalVideos / $videosPerPage);

// ✅ Get videos for current page
$stmt = $pdo->prepare("SELECT * FROM video_training ORDER BY created_at DESC LIMIT :limit OFFSET :offset");
$stmt->bindValue(':limit', $videosPerPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$videos = $stmt->fetchAll();



$referrerId = $userData['referrer_id'] ?? null;

// Fetch the referrer's LeadsLeap ID if a referrer exists
// Default LeadsLeap ID if sponsor does not have one
$defaultLeadsLeapId = 'keyte';

$referrerLeadsLeapId = $defaultLeadsLeapId; // Set default first

if ($referrerId) {
    $stmt = $pdo->prepare("SELECT leadsleap_user_id FROM users WHERE user_id = ?");
    $stmt->execute([$referrerId]);
    $referrerData = $stmt->fetch(PDO::FETCH_ASSOC);

    // Only override default if the sponsor has a valid LeadsLeap ID
    if (!empty($referrerData['leadsleap_user_id'])) {
        $referrerLeadsLeapId = $referrerData['leadsleap_user_id'];
    }
}


$user_id = $userData['user_id'];

// ✅ Process Profile Update Form
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);

    if (empty($first_name) || empty($last_name) || empty($email)) {
        $errorMessage = "All fields except password are required.";
    } else {
        // ✅ Check if email is already taken by another user
        $stmt = $pdo->prepare("SELECT user_id FROM users WHERE email = ? AND user_id != ?");
        $stmt->execute([$email, $user_id]);
        if ($stmt->fetch()) {
            $errorMessage = "Email is already in use by another user.";
        } else {
            // ✅ Prepare update query
            $updateColumns = ["first_name = ?", "last_name = ?", "email = ?"];
            $updateValues = [$first_name, $last_name, $email];

            // ✅ Hash new password if provided
            if (!empty($password)) {
                $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                $updateColumns[] = "edit_token = ?";
                $updateValues[] = $hashedPassword;
            }

            // ✅ Update user info in database
            $updateValues[] = $user_id;
            $stmt = $pdo->prepare("UPDATE users SET " . implode(", ", $updateColumns) . " WHERE user_id = ?");
            if ($stmt->execute($updateValues)) {
                // ✅ Redirect to avoid form resubmission on refresh
                header("Location: profile.php?profile_saved=1");
                exit;
            } else {
                $errorMessage = "Failed to update profile.";
            }
        }
    }
}

// ✅ Process LeadsLeap Update Form
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_leadsleap'])) {
    $leadsleap_user_id = trim($_POST['leadsleap_user_id'] ?? '');
    $leadsleap_list_id = trim($_POST['leadsleap_list_id'] ?? '');
    $leadsleap_list_id_referrals = trim($_POST['leadsleap_list_id_referrals'] ?? ''); // ✅ New field for referrals


    if (!empty($leadsleap_user_id) && !empty($leadsleap_list_id)) {
        // ✅ Update the database
        $stmt = $pdo->prepare("UPDATE users SET leadsleap_user_id = ?, leadsleap_list_id = ?, leadsleap_list_id_referrals = ? WHERE user_id = ?");
        $result = $stmt->execute([$leadsleap_user_id, $leadsleap_list_id, $leadsleap_list_id_referrals, $user_id]);

        if ($result) {
            header("Location: profile.php?leadsleap_saved=1");
            exit;
        } else {
            $errorInfo = $stmt->errorInfo();
            file_put_contents('debug_log.txt', "DB Error: " . print_r($errorInfo, true) . "\n", FILE_APPEND);
            header("Location: profile.php?leadsleap_saved=0");
            exit;
        }
    } else {
        $errorMessage = "Both LeadsLeap User ID and List ID are required!";
    }
}

// ✅ Fetch Branding Settings
$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

// ✅ Generate Gravatar URL
$gravatarEmail = strtolower(trim($userData['email']));
$gravatarHash = md5($gravatarEmail);
$gravatarURL = "https://www.gravatar.com/avatar/$gravatarHash?s=150&d=mp"; // Default to 'mp' mystery person if no Gravatar exists

$errorMessage = "";
$successMessage = "";

?>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Training Center</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;
}


    /* Ensure the sidebar stays fixed properly */
    .sidebar {
        width: 250px !important;
        min-height: 100vh;
        background-color: #f8f9fa;
    }

    /* Fix the main content so it doesn't shrink */
    .container-fluid {
        flex-grow: 1 !important;
        padding: 20px !important;
    }

    /* Ensure widgets and buttons stay aligned */
    .card {
        border-radius: 10px !important;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1) !important;
    }

    /* Fix footer width */
    footer {
        width: 100% !important;
    }
    
    /* Floating Copy Notification */
.copy-notification {
    position: fixed;
    bottom: 20px;
    right: 20px;
    background-color: #28a745; /* Green (Success) */
    color: white;
    padding: 10px 20px;
    border-radius: 8px;
    font-size: 16px;
    display: none; /* Initially hidden */
    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.2);
    z-index: 1000;
    transition: opacity 0.5s ease-in-out;
}

.copy-notification.show {
    display: block;
    opacity: 1;
}

.copy-notification i {
    margin-right: 8px;
}

/* 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 */
}

.rounded-circle {
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid #ddd;
    transition: 0.3s;
}
.rounded-circle:hover {
    border-color: #007bff;
}

      .training-grid {
  display: grid;
  gap: 1.5rem;
  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  max-width: 1000px;
  margin: 0 auto;
  justify-content: center;
    }

.training-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 14px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  display: flex;
  flex-direction: column;
}

    .training-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 22px rgba(0, 0, 0, 0.15);
    }

/* ✅ Maintain 16:9 aspect ratio */
.training-card .video-wrapper {
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* 16:9 */
  background-color: #000;
  overflow: hidden;
  border-bottom: none;

}

.training-card iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: none;
}

    .training-content {
      padding: 15px;
    }

    .training-title {
      font-size: 1.1rem;
      font-weight: 600;
      margin-bottom: 0.5rem;
      color: #222;
    }

    .training-description {
      font-size: 0.95rem;
      color: #555;
    }

    @media (max-width: 600px) {
      .training-card iframe {
        height: 160px;
      }
    }
    
    .pagination .page-item.active .page-link {
  background-color: #007bff;
  border-color: #007bff;
  color: white;
}

</style>


</head>
<body>

<!-- Floating Notification -->
<div id="copyNotification" class="copy-notification">
    <i class="fa fa-check-circle"></i> Copied to clipboard!
</div>

<?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>

<div class="sidebar-overlay" onclick="toggleSidebar()"></div>
        <div class="container-fluid p-4" style="background: #fff; min-height: 100vh;">
   <h1><i class="fas fa-graduation-cap"></i> Training Centre<?php include 'google-translate-widget.php'; ?>
</h1>

  <div class="training-grid">
    <?php foreach ($videos as $video): ?>
      <div class="training-card">
        <div class="video-wrapper">
  <iframe src="<?= htmlspecialchars($video['youtube_url']) ?>" allowfullscreen></iframe>
</div>
        <div class="training-content">
          <div class="training-title">
            <i class="fas fa-play-circle"></i> <?= htmlspecialchars($video['title']) ?>
          </div>
          <div class="training-description">
            <?= nl2br(htmlspecialchars($video['description'])) ?>
          </div>
        </div>
      </div>
    <?php endforeach; ?>
  </div>
  <?php if ($totalPages > 1): ?>
  <nav class="mt-4 text-center">
    <ul class="pagination justify-content-center">
      <?php if ($page > 1): ?>
        <li class="page-item">
          <a class="page-link" href="?page=<?= $page - 1 ?>"><i class="fas fa-chevron-left"></i> Previous</a>
        </li>
      <?php endif; ?>

      <?php for ($i = 1; $i <= $totalPages; $i++): ?>
        <li class="page-item <?= ($i == $page) ? 'active' : '' ?>">
          <a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a>
        </li>
      <?php endfor; ?>

      <?php if ($page < $totalPages): ?>
        <li class="page-item">
          <a class="page-link" href="?page=<?= $page + 1 ?>">Next <i class="fas fa-chevron-right"></i></a>
        </li>
      <?php endif; ?>
    </ul>
  </nav>
<?php endif; ?>


</div>



        
 </div>

    </div>
</div>

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


<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></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>
